coeus_ops/shape/concat_split_stack/
stack.rs1use coeus_core::{ComputeBackend, CpuAddressableStorage, CpuAddressableStorageMut, Scalar, Shape};
5use coeus_tensor::Tensor;
6
7#[inline]
17pub fn stack<T: Scalar, B: ComputeBackend + Default>(
18 tensors: &[&Tensor<T, B>],
19 dim: usize,
20) -> Result<Tensor<T, B>, B::Error>
21where
22 B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
23{
24 assert!(!tensors.is_empty(), "stack: input list is empty");
25
26 let backend = B::default();
27 let ndim = tensors[0].ndim();
28 assert!(
29 dim <= ndim,
30 "stack: dim {dim} out of range for insertion into {ndim}D tensor"
31 );
32
33 let base_shape = tensors[0].shape();
34 for tensor in tensors {
35 assert_eq!(
36 tensor.shape(),
37 base_shape,
38 "stack: all tensors must have identical shape"
39 );
40 }
41
42 let mut out_shape = Shape::with_capacity(ndim + 1);
43 for &extent in &base_shape[..dim] {
44 out_shape.push(extent);
45 }
46 out_shape.push(tensors.len());
47 for &extent in &base_shape[dim..] {
48 out_shape.push(extent);
49 }
50
51 let layouts: Vec<_> = tensors.iter().map(|tensor| tensor.layout()).collect();
52 let inputs: Vec<_> = tensors
53 .iter()
54 .map(|tensor| tensor.storage().as_slice())
55 .collect();
56 let values = coeus_cpu::stack_values(&layouts, &inputs, dim).expect("coeus-cpu stack failed");
57 Tensor::from_slice_on(out_shape, &values, &backend)
58}