Skip to main content

coeus_ops/shape/concat_split_stack/
split.rs

1// ── Split ──
2// Splits a tensor into multiple tensors along a given dimension.
3
4use coeus_core::{ComputeBackend, CpuAddressableStorage, CpuAddressableStorageMut, Scalar};
5use coeus_tensor::Tensor;
6
7/// Split `x` into chunks of size `chunk_size` along `dim`.
8///
9/// The last chunk may be smaller if `x.shape()[dim]` is not divisible.
10///
11/// # Panics
12/// - `chunk_size` is zero.
13/// - `dim` is out of range.
14#[inline]
15pub fn split<T: Scalar, B: ComputeBackend + Default>(
16    x: &Tensor<T, B>,
17    chunk_size: usize,
18    dim: usize,
19) -> Result<Vec<Tensor<T, B>>, B::Error>
20where
21    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
22{
23    assert!(chunk_size > 0, "split: chunk_size must be > 0");
24    let ndim = x.ndim();
25    assert!(
26        dim < ndim,
27        "split: dim {dim} out of range for {ndim}D tensor"
28    );
29
30    let backend = B::default();
31    let dim_size = x.shape()[dim];
32    let sizes: Vec<_> = (0..dim_size)
33        .step_by(chunk_size)
34        .map(|start| (dim_size - start).min(chunk_size))
35        .collect();
36    let (flat, offsets) = coeus_cpu::split_values(x.layout(), x.storage().as_slice(), dim, &sizes)
37        .expect("coeus-cpu split failed");
38
39    offsets
40        .windows(2)
41        .zip(sizes)
42        .map(|(bounds, chunk_dim)| {
43            let mut out_shape = x.shape_cloned();
44            out_shape[dim] = chunk_dim;
45            Tensor::from_slice_on(out_shape, &flat[bounds[0]..bounds[1]], &backend)
46        })
47        .collect()
48}