use coeus_core::{ComputeBackend, CpuAddressableStorage, CpuAddressableStorageMut, Scalar};
use coeus_tensor::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");
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");
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)
}