Skip to main content

torsh_data/collate/
stacking.rs

1//! Tensor stacking utilities
2
3use torsh_core::{
4    dtype::TensorElement,
5    error::{Result, TorshError},
6};
7use torsh_tensor::Tensor;
8
9#[cfg(not(feature = "std"))]
10use alloc::vec::Vec;
11
12// ✅ SciRS2 POLICY: Use scirs2_core::parallel_ops instead of rayon::prelude
13#[cfg(feature = "std")]
14use scirs2_core::parallel_ops::*;
15
16/// Consolidated tensor stacking utility that reduces code duplication
17pub struct TensorStacker {
18    use_parallel: bool,
19    parallel_threshold: usize,
20    memory_mapped: bool,
21}
22
23impl Default for TensorStacker {
24    fn default() -> Self {
25        Self {
26            use_parallel: cfg!(feature = "std"),
27            parallel_threshold: 1000,
28            memory_mapped: false,
29        }
30    }
31}
32
33impl TensorStacker {
34    /// Create a new tensor stacker with default settings
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Enable/disable parallel processing
40    pub fn with_parallel(mut self, enabled: bool) -> Self {
41        self.use_parallel = enabled && cfg!(feature = "std");
42        self
43    }
44
45    /// Set threshold for parallel processing
46    pub fn parallel_threshold(mut self, threshold: usize) -> Self {
47        self.parallel_threshold = threshold;
48        self
49    }
50
51    /// Enable memory-mapped stacking for very large batches
52    pub fn with_memory_mapping(mut self, enabled: bool) -> Self {
53        self.memory_mapped = enabled && cfg!(all(feature = "std", feature = "mmap-support"));
54        self
55    }
56
57    /// Stack tensors along the specified dimension
58    pub fn stack<T: TensorElement + Copy>(
59        &self,
60        tensors: &[Tensor<T>],
61        dim: usize,
62    ) -> Result<Tensor<T>> {
63        if tensors.is_empty() {
64            return Err(TorshError::InvalidArgument(
65                "Cannot stack empty tensor list".to_string(),
66            ));
67        }
68
69        // Validate shapes
70        self.validate_shapes(tensors)?;
71
72        // Choose stacking strategy based on configuration and batch size
73        if self.memory_mapped && tensors.len() > 100 {
74            self.stack_with_mmap(tensors, dim)
75        } else if self.use_parallel && self.should_use_parallel(tensors) {
76            self.stack_parallel(tensors, dim)
77        } else {
78            self.stack_sequential(tensors, dim)
79        }
80    }
81
82    /// Check if all tensors have the same shape
83    fn validate_shapes<T: TensorElement>(&self, tensors: &[Tensor<T>]) -> Result<()> {
84        let first_shape = tensors[0].shape();
85        for tensor in tensors[1..].iter() {
86            if tensor.shape() != first_shape {
87                return Err(TorshError::ShapeMismatch {
88                    expected: first_shape.dims().to_vec(),
89                    got: tensor.shape().dims().to_vec(),
90                });
91            }
92        }
93        Ok(())
94    }
95
96    /// Determine if parallel processing should be used
97    fn should_use_parallel<T: TensorElement>(&self, tensors: &[Tensor<T>]) -> bool {
98        tensors.len() > 4 && tensors[0].numel() > self.parallel_threshold
99    }
100
101    /// Create new shape with additional dimension
102    fn create_new_shape(
103        &self,
104        original_dims: &[usize],
105        batch_size: usize,
106        dim: usize,
107    ) -> Vec<usize> {
108        let mut new_dims = Vec::with_capacity(original_dims.len() + 1);
109
110        if dim == 0 {
111            new_dims.push(batch_size);
112            new_dims.extend_from_slice(original_dims);
113        } else {
114            new_dims.extend_from_slice(&original_dims[..dim.min(original_dims.len())]);
115            new_dims.push(batch_size);
116            if dim < original_dims.len() {
117                new_dims.extend_from_slice(&original_dims[dim..]);
118            }
119        }
120
121        new_dims
122    }
123
124    /// Split each source tensor's flat buffer into an `outer_size` (product of
125    /// dims before `dim`) by `inner_size` (product of dims from `dim` onward)
126    /// view. Stacking a new batch axis at `dim` means each of the
127    /// `outer_size` blocks gets one `inner_size`-long chunk copied in from
128    /// every source tensor in turn, which is exactly `dim == 0` (`outer_size
129    /// == 1`) generalized to any `dim`.
130    fn outer_inner_split(&self, dims: &[usize], dim: usize) -> (usize, usize) {
131        let dim = dim.min(dims.len());
132        let outer_size: usize = dims[..dim].iter().product();
133        let inner_size: usize = dims[dim..].iter().product();
134        (outer_size, inner_size)
135    }
136
137    /// Sequential tensor stacking
138    fn stack_sequential<T: TensorElement + Copy>(
139        &self,
140        tensors: &[Tensor<T>],
141        dim: usize,
142    ) -> Result<Tensor<T>> {
143        let original_dims = tensors[0].shape().dims().to_vec();
144        let new_dims = self.create_new_shape(&original_dims, tensors.len(), dim);
145        let (outer_size, inner_size) = self.outer_inner_split(&original_dims, dim);
146        let total_elements = new_dims.iter().product::<usize>();
147
148        // Gather every source tensor's data BEFORE allocating the output
149        // buffer, so a mid-batch conversion error surfaces via `?` before any
150        // partially-filled buffer exists (avoids the set_len-before-fully-
151        // initialized UB the old implementation had).
152        let all_data: Vec<Vec<T>> = tensors
153            .iter()
154            .map(|tensor| tensor.to_vec())
155            .collect::<Result<Vec<_>>>()?;
156
157        let mut new_data = Vec::with_capacity(total_elements);
158        for outer in 0..outer_size {
159            let offset = outer * inner_size;
160            for data in &all_data {
161                new_data.extend_from_slice(&data[offset..offset + inner_size]);
162            }
163        }
164
165        torsh_tensor::Tensor::from_data(new_data, new_dims, tensors[0].device())
166    }
167
168    /// Parallel tensor stacking
169    #[cfg(feature = "std")]
170    fn stack_parallel<T: TensorElement + Copy>(
171        &self,
172        tensors: &[Tensor<T>],
173        dim: usize,
174    ) -> Result<Tensor<T>> {
175        let original_dims = tensors[0].shape().dims().to_vec();
176        let new_dims = self.create_new_shape(&original_dims, tensors.len(), dim);
177        let (outer_size, inner_size) = self.outer_inner_split(&original_dims, dim);
178
179        // Parallel data collection - gathered fully before any output buffer
180        // exists, so a conversion error surfaces via `?` before any
181        // partially-filled buffer would need to be dropped.
182        let parallel_data: std::result::Result<Vec<Vec<T>>, TorshError> =
183            tensors.par_iter().map(|tensor| tensor.to_vec()).collect();
184        let all_data = parallel_data?;
185
186        // Stack each of the `outer_size` interleaved blocks in parallel, then
187        // flatten the per-block chunks back together in order.
188        let chunks: Vec<Vec<T>> = (0..outer_size)
189            .into_par_iter()
190            .map(|outer| {
191                let offset = outer * inner_size;
192                let mut chunk = Vec::with_capacity(all_data.len() * inner_size);
193                for data in &all_data {
194                    chunk.extend_from_slice(&data[offset..offset + inner_size]);
195                }
196                chunk
197            })
198            .collect();
199
200        let new_data: Vec<T> = chunks.into_iter().flatten().collect();
201        torsh_tensor::Tensor::from_data(new_data, new_dims, tensors[0].device())
202    }
203
204    /// Fallback for no_std
205    #[cfg(not(feature = "std"))]
206    fn stack_parallel<T: TensorElement + Copy>(
207        &self,
208        tensors: &[Tensor<T>],
209        dim: usize,
210    ) -> Result<Tensor<T>> {
211        self.stack_sequential(tensors, dim)
212    }
213
214    /// Memory-mapped stacking for very large batches
215    #[cfg(all(feature = "std", feature = "mmap-support"))]
216    fn stack_with_mmap<T: TensorElement + Copy>(
217        &self,
218        tensors: &[Tensor<T>],
219        dim: usize,
220    ) -> Result<Tensor<T>> {
221        // Placeholder implementation - in practice would use memory mapping
222        // For now, fallback to parallel stacking
223        self.stack_parallel(tensors, dim)
224    }
225
226    /// Fallback when mmap is not available
227    #[cfg(not(all(feature = "std", feature = "mmap-support")))]
228    fn stack_with_mmap<T: TensorElement + Copy>(
229        &self,
230        tensors: &[Tensor<T>],
231        dim: usize,
232    ) -> Result<Tensor<T>> {
233        if cfg!(feature = "std") {
234            self.stack_parallel(tensors, dim)
235        } else {
236            self.stack_sequential(tensors, dim)
237        }
238    }
239}