coeus-ops 0.13.0

Numerical tensor operators for Coeus.
Documentation
// ── Concatenation ──
// Concatenates a list of tensors along a given dimension.
// Zero-copy when a single input is given (returns a clone of the storage view).

use coeus_core::{ComputeBackend, CpuAddressableStorage, CpuAddressableStorageMut, Scalar};
use coeus_tensor::Tensor;

/// Concatenate `tensors` along `dim`.
///
/// All tensors must have the same shape in every dimension except `dim`.
///
/// # Panics
/// - `tensors` is empty.
/// - Any tensor has mismatched shape on a non-cat dimension.
/// - `dim` is out of range for any tensor.
#[inline]
pub fn cat<T: Scalar, B: ComputeBackend + Default>(
    tensors: &[&Tensor<T, B>],
    dim: usize,
) -> Result<Tensor<T, B>, B::Error>
where
    B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
{
    assert!(!tensors.is_empty(), "cat: input list is empty");
    // Fast path: single input.
    if tensors.len() == 1 {
        return Ok((*tensors[0]).clone());
    }

    let backend = B::default();
    let ndim = tensors[0].ndim();
    assert!(dim < ndim, "cat: dim {dim} out of range for {ndim}D tensor");

    // Validate shapes and compute output dim size.
    let mut out_shape = tensors[0].shape_cloned();
    let out_dim_size = tensors
        .iter()
        .map(|t| {
            assert_eq!(t.ndim(), ndim, "cat: all tensors must have the same rank");
            for d in 0..ndim {
                if d != dim {
                    assert_eq!(
                        t.shape()[d],
                        out_shape[d],
                        "cat: shape mismatch at dimension {d}"
                    );
                }
            }
            t.shape()[dim]
        })
        .sum::<usize>();
    out_shape[dim] = out_dim_size;

    let layouts: Vec<_> = tensors.iter().map(|tensor| tensor.layout()).collect();
    let inputs: Vec<_> = tensors
        .iter()
        .map(|tensor| tensor.storage().as_slice())
        .collect();
    let values = coeus_cpu::concat_values(&layouts, &inputs, dim).expect("coeus-cpu concat failed");
    Tensor::from_slice_on(out_shape, &values, &backend)
}