Skip to main content

torsh_data/collate/
advanced.rs

1//! Advanced collation implementations
2
3use super::{optimized::stack_tensors, Collate};
4use torsh_core::{
5    dtype::TensorElement,
6    error::{Result, TorshError},
7};
8use torsh_tensor::Tensor;
9
10#[cfg(feature = "sparse")]
11use torsh_sparse::{CooTensor, SparseTensor};
12
13#[cfg(not(feature = "std"))]
14use alloc::{boxed::Box, vec::Vec};
15
16#[cfg(feature = "std")]
17use std::sync::Arc;
18
19/// Cached collation function that reuses allocated memory
20pub struct CachedCollate<T: TensorElement> {
21    tensor_pool: Arc<parking_lot::Mutex<Vec<Vec<T>>>>,
22    max_pool_size: usize,
23}
24
25impl<T: TensorElement> CachedCollate<T> {
26    /// Create a new cached collation function
27    pub fn new(max_pool_size: usize) -> Self {
28        Self {
29            tensor_pool: Arc::new(parking_lot::Mutex::new(Vec::with_capacity(max_pool_size))),
30            max_pool_size,
31        }
32    }
33
34    /// Get a reusable buffer from the pool
35    fn get_buffer(&self, capacity: usize) -> Vec<T> {
36        let mut pool = self.tensor_pool.lock();
37        if let Some(mut buffer) = pool.pop() {
38            buffer.clear();
39            if buffer.capacity() >= capacity {
40                buffer.reserve(capacity - buffer.capacity());
41            }
42            buffer
43        } else {
44            Vec::with_capacity(capacity)
45        }
46    }
47
48    /// Return a buffer to the pool
49    fn return_buffer(&self, buffer: Vec<T>) {
50        let mut pool = self.tensor_pool.lock();
51        if pool.len() < self.max_pool_size {
52            pool.push(buffer);
53        }
54    }
55}
56
57impl<T: TensorElement + Copy> Collate<Tensor<T>> for CachedCollate<T> {
58    type Output = Tensor<T>;
59
60    fn collate(&self, batch: Vec<Tensor<T>>) -> Result<Self::Output> {
61        if batch.is_empty() {
62            return Err(TorshError::InvalidArgument(
63                "Cannot collate empty batch".to_string(),
64            ));
65        }
66
67        // Check that all tensors have the same shape
68        let first_shape = batch[0].shape();
69        for tensor in &batch[1..] {
70            if tensor.shape() != first_shape {
71                return Err(TorshError::ShapeMismatch {
72                    expected: first_shape.dims().to_vec(),
73                    got: tensor.shape().dims().to_vec(),
74                });
75            }
76        }
77
78        // Create new shape with batch dimension
79        let original_dims = first_shape.dims();
80        let mut new_dims = Vec::with_capacity(original_dims.len() + 1);
81        new_dims.push(batch.len());
82        new_dims.extend_from_slice(original_dims);
83
84        let tensor_size = batch[0].numel();
85        let total_elements = tensor_size * batch.len();
86
87        // Get a reusable buffer
88        let mut new_data = self.get_buffer(total_elements);
89        new_data.reserve_exact(total_elements);
90
91        // Copy tensor data efficiently
92        for tensor in batch.iter() {
93            let data = tensor.to_vec()?;
94            new_data.extend_from_slice(&data);
95        }
96
97        let result =
98            torsh_tensor::Tensor::from_data(new_data.clone(), new_dims, batch[0].device())?;
99
100        // Return buffer to pool (create a new empty vector to return)
101        self.return_buffer(Vec::with_capacity(new_data.capacity()));
102
103        Ok(result)
104    }
105}
106
107/// Dynamic batching collation for variable-size sequences
108pub struct DynamicBatchCollate<T: TensorElement> {
109    padding_value: T,
110    max_sequence_length: Option<usize>,
111    pack_sequences: bool,
112}
113
114impl<T: TensorElement> DynamicBatchCollate<T> {
115    /// Create a new dynamic batch collation function
116    pub fn new(padding_value: T) -> Self {
117        Self {
118            padding_value,
119            max_sequence_length: None,
120            pack_sequences: false,
121        }
122    }
123
124    /// Set maximum sequence length (sequences longer than this will be truncated)
125    pub fn with_max_length(mut self, max_length: usize) -> Self {
126        self.max_sequence_length = Some(max_length);
127        self
128    }
129
130    /// Enable sequence packing to minimize padding
131    pub fn with_packing(mut self, pack: bool) -> Self {
132        self.pack_sequences = pack;
133        self
134    }
135}
136
137impl<
138        T: TensorElement
139            + Copy
140            + std::ops::Add<Output = T>
141            + std::ops::Sub<Output = T>
142            + std::ops::Mul<Output = T>
143            + std::ops::Div<Output = T>
144            + Default,
145    > Collate<Tensor<T>> for DynamicBatchCollate<T>
146{
147    type Output = (Tensor<T>, Tensor<i64>); // (padded_sequences, lengths)
148
149    fn collate(&self, batch: Vec<Tensor<T>>) -> Result<Self::Output> {
150        if batch.is_empty() {
151            return Err(TorshError::InvalidArgument(
152                "Cannot collate empty batch".to_string(),
153            ));
154        }
155
156        // Collect sequence lengths
157        let mut lengths = Vec::with_capacity(batch.len());
158        let mut max_length = 0;
159
160        for tensor in &batch {
161            if tensor.ndim() == 0 {
162                return Err(TorshError::InvalidArgument(
163                    "Cannot dynamically batch scalar tensors".to_string(),
164                ));
165            }
166
167            let seq_len = tensor.size(0)?;
168            lengths.push(seq_len as i64);
169            max_length = max_length.max(seq_len);
170        }
171
172        // Apply max length constraint if specified
173        if let Some(max_len) = self.max_sequence_length {
174            max_length = max_length.min(max_len);
175        }
176
177        // Clamp reported lengths to the (possibly truncated) max_length: a
178        // sequence longer than max_length gets narrow()'d below, so its
179        // reported length must reflect the truncated size, not the original
180        // one, or downstream masking/packed-sequence code would index past
181        // the end of the padded tensor.
182        for length in &mut lengths {
183            *length = (*length).min(max_length as i64);
184        }
185
186        // If packing is enabled, sort by length to minimize padding
187        let mut batch_with_indices: Vec<_> = batch.into_iter().enumerate().collect();
188        if self.pack_sequences {
189            batch_with_indices.sort_by_key(|(_, tensor)| tensor.size(0).unwrap_or(0));
190        }
191
192        // Get the shape for creating padded tensors
193        let first_tensor = &batch_with_indices[0].1;
194        let mut padded_shape = first_tensor.shape().dims().to_vec();
195        padded_shape[0] = max_length; // Set sequence dimension to max length
196
197        // Create padded batch
198        let batch_size = batch_with_indices.len();
199        let mut padded_batch = Vec::with_capacity(batch_size);
200
201        for (original_idx, tensor) in batch_with_indices {
202            let seq_len = tensor.size(0)?;
203            let actual_len = seq_len.min(max_length);
204
205            if actual_len == max_length {
206                // No padding needed, just truncate if necessary
207                if seq_len > max_length {
208                    let truncated = tensor.narrow(0, 0, max_length)?;
209                    padded_batch.push((original_idx, truncated));
210                } else {
211                    padded_batch.push((original_idx, tensor));
212                }
213            } else {
214                // Need to pad
215                let mut padding_shape = padded_shape.clone();
216                let padding_elements =
217                    (max_length - actual_len) * padding_shape[1..].iter().product::<usize>();
218
219                // Create padding tensor
220                let padding_data = vec![self.padding_value; padding_elements];
221                padding_shape[0] = max_length - actual_len;
222
223                let padding_tensor =
224                    Tensor::from_data(padding_data, padding_shape.clone(), tensor.device())?;
225
226                // Truncate if necessary
227                let tensor_to_pad = if seq_len > max_length {
228                    tensor.narrow(0, 0, max_length)?
229                } else {
230                    tensor
231                };
232
233                // Manual concatenation since Tensor::cat is not working correctly
234                let tensor_data = tensor_to_pad.to_vec()?;
235                let padding_data = padding_tensor.to_vec()?;
236
237                // Combine the data
238                let mut combined_data = tensor_data;
239                combined_data.extend(padding_data);
240
241                // Create new tensor with correct shape
242                let mut final_shape = tensor_to_pad.shape().dims().to_vec();
243                final_shape[0] = max_length; // Set to max_length
244
245                let padded = Tensor::from_data(combined_data, final_shape, tensor_to_pad.device())?;
246                padded_batch.push((original_idx, padded));
247            }
248        }
249
250        // Restore original order if packing was used
251        if self.pack_sequences {
252            padded_batch.sort_by_key(|(idx, _)| *idx);
253        }
254
255        // Extract tensors and stack them
256        let tensors: Vec<_> = padded_batch.into_iter().map(|(_, tensor)| tensor).collect();
257
258        let stacked = stack_tensors(&tensors, 0)?;
259
260        // Create lengths tensor
261        let lengths_tensor = Tensor::from_data(lengths, vec![batch_size], tensors[0].device())?;
262
263        Ok((stacked, lengths_tensor))
264    }
265}
266
267/// Wrapper for DynamicBatchCollate that only returns padded sequences (not lengths)
268/// This allows compatibility with the CollateBuilder which expects `Tensor<T>` output
269pub struct DynamicBatchCollateWrapper<T: TensorElement> {
270    inner: DynamicBatchCollate<T>,
271}
272
273impl<T: TensorElement> DynamicBatchCollateWrapper<T> {
274    pub fn new(padding_value: T) -> Self {
275        Self {
276            inner: DynamicBatchCollate::new(padding_value),
277        }
278    }
279
280    pub fn with_max_length(mut self, max_length: usize) -> Self {
281        self.inner = self.inner.with_max_length(max_length);
282        self
283    }
284
285    pub fn with_packing(mut self, pack: bool) -> Self {
286        self.inner = self.inner.with_packing(pack);
287        self
288    }
289}
290
291impl<
292        T: TensorElement
293            + Copy
294            + std::ops::Add<Output = T>
295            + std::ops::Sub<Output = T>
296            + std::ops::Mul<Output = T>
297            + std::ops::Div<Output = T>
298            + Default,
299    > Collate<Tensor<T>> for DynamicBatchCollateWrapper<T>
300{
301    type Output = Tensor<T>;
302
303    fn collate(&self, batch: Vec<Tensor<T>>) -> Result<Self::Output> {
304        // Call the inner collate function and extract only the padded sequences
305        let (padded_sequences, _lengths) = self.inner.collate(batch)?;
306        Ok(padded_sequences)
307    }
308}
309
310/// Bucket sampler for dynamic batching
311/// Groups sequences of similar lengths to minimize padding
312pub struct BucketBatchSampler {
313    lengths: Vec<usize>,
314    batch_size: usize,
315    bucket_boundaries: Vec<usize>,
316    drop_last: bool,
317}
318
319impl BucketBatchSampler {
320    /// Create a new bucket batch sampler
321    pub fn new(lengths: Vec<usize>, batch_size: usize, drop_last: bool) -> Self {
322        // Create bucket boundaries based on length distribution
323        let mut sorted_lengths = lengths.clone();
324        sorted_lengths.sort_unstable();
325
326        let num_buckets = (lengths.len() / batch_size).clamp(1, 10);
327        let mut bucket_boundaries = Vec::with_capacity(num_buckets + 1);
328
329        for i in 0..=num_buckets {
330            let idx = (i * sorted_lengths.len()) / num_buckets;
331            let boundary = if idx >= sorted_lengths.len() {
332                sorted_lengths.last().copied().unwrap_or(0) + 1
333            } else {
334                sorted_lengths[idx]
335            };
336            bucket_boundaries.push(boundary);
337        }
338
339        Self {
340            lengths,
341            batch_size,
342            bucket_boundaries,
343            drop_last,
344        }
345    }
346
347    /// Generate batches grouped by sequence length buckets
348    pub fn generate_batches(&self) -> Vec<Vec<usize>> {
349        // Group indices by bucket
350        let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); self.bucket_boundaries.len() - 1];
351
352        for (idx, &length) in self.lengths.iter().enumerate() {
353            for (bucket_idx, bucket) in buckets.iter_mut().enumerate() {
354                if length >= self.bucket_boundaries[bucket_idx]
355                    && length < self.bucket_boundaries[bucket_idx + 1]
356                {
357                    bucket.push(idx);
358                    break;
359                }
360            }
361        }
362
363        // Shuffle within each bucket and create batches
364        let mut batches = Vec::new();
365
366        for mut bucket in buckets {
367            // ✅ SciRS2 Policy Enhanced - Using scientific shuffle for optimal ML batching
368            use scirs2_core::random::prelude::*;
369            use scirs2_core::random::seq::ScientificSliceRandom;
370
371            let mut rng = thread_rng();
372            bucket.scientific_shuffle(&mut rng);
373
374            for chunk in bucket.chunks(self.batch_size) {
375                if chunk.len() == self.batch_size || !self.drop_last {
376                    batches.push(chunk.to_vec());
377                }
378            }
379        }
380
381        // Enhanced scientific shuffle to optimize ML training batch distribution
382        // ✅ SciRS2 Policy Enhanced - Using scientific shuffle for superior randomness
383        use scirs2_core::random::prelude::*;
384        use scirs2_core::random::seq::ScientificSliceRandom;
385        let mut rng = thread_rng();
386        batches.scientific_shuffle(&mut rng);
387
388        batches
389    }
390}
391
392/// Adaptive batch size sampler that adjusts batch size based on sequence lengths
393pub struct AdaptiveBatchSampler {
394    target_tokens: usize,
395    max_batch_size: usize,
396    min_batch_size: usize,
397    lengths: Vec<usize>,
398}
399
400impl AdaptiveBatchSampler {
401    /// Create a new adaptive batch sampler
402    pub fn new(
403        lengths: Vec<usize>,
404        target_tokens: usize,
405        max_batch_size: usize,
406        min_batch_size: usize,
407    ) -> Self {
408        Self {
409            target_tokens,
410            max_batch_size,
411            min_batch_size,
412            lengths,
413        }
414    }
415
416    /// Generate batches with adaptive batch sizes
417    pub fn generate_batches(&self) -> Vec<Vec<usize>> {
418        let mut indices: Vec<usize> = (0..self.lengths.len()).collect();
419
420        // Sort by length to process similar lengths together
421        indices.sort_by_key(|&i| self.lengths[i]);
422
423        let mut batches = Vec::new();
424        let mut current_batch = Vec::new();
425        let mut _current_tokens = 0;
426
427        for idx in indices {
428            let length = self.lengths[idx];
429            let batch_size = current_batch.len();
430            let tokens_if_added = (batch_size + 1)
431                * length.max(
432                    current_batch
433                        .iter()
434                        .map(|&i| self.lengths[i])
435                        .max()
436                        .unwrap_or(0),
437                );
438
439            // Check if adding this sequence would exceed limits
440            if tokens_if_added > self.target_tokens || batch_size >= self.max_batch_size {
441                // Finish current batch if it meets minimum size
442                if batch_size >= self.min_batch_size {
443                    batches.push(current_batch);
444                }
445
446                // Start new batch
447                current_batch = vec![idx];
448                _current_tokens = length;
449            } else {
450                // Add to current batch
451                current_batch.push(idx);
452                _current_tokens = tokens_if_added;
453            }
454        }
455
456        // Add final batch if it meets minimum size
457        if current_batch.len() >= self.min_batch_size {
458            batches.push(current_batch);
459        }
460
461        batches
462    }
463}
464
465/// Padding collation for variable-length sequences
466pub struct PadCollate<T: TensorElement> {
467    #[allow(dead_code)]
468    padding_value: T,
469}
470
471impl<T: TensorElement> PadCollate<T> {
472    /// Create a new padding collation function
473    pub fn new(padding_value: T) -> Self {
474        Self { padding_value }
475    }
476}
477
478impl<T: TensorElement + Copy> Collate<Tensor<T>> for PadCollate<T> {
479    type Output = Tensor<T>;
480
481    fn collate(&self, batch: Vec<Tensor<T>>) -> Result<Self::Output> {
482        if batch.is_empty() {
483            return Err(TorshError::InvalidArgument(
484                "Cannot collate empty batch".to_string(),
485            ));
486        }
487
488        // Find maximum dimensions
489        let ndim = batch[0].ndim();
490        let mut max_dims = vec![0; ndim];
491
492        for tensor in &batch {
493            if tensor.ndim() != ndim {
494                return Err(TorshError::InvalidArgument(
495                    "All tensors must have the same number of dimensions".to_string(),
496                ));
497            }
498
499            for (i, max_dim) in max_dims.iter_mut().enumerate().take(ndim) {
500                let size = tensor.size(i as i32)?;
501                if size > *max_dim {
502                    *max_dim = size;
503                }
504            }
505        }
506
507        // Create padded tensors
508        let batch_size = batch.len();
509        let mut padded_batch = Vec::with_capacity(batch_size);
510
511        for tensor in batch {
512            // For each tensor, pad to match max_dims
513            let shape_ref = tensor.shape();
514            let current_shape = shape_ref.dims();
515            let padded_tensor = tensor;
516
517            // Check if padding is needed
518            let needs_padding = current_shape
519                .iter()
520                .zip(max_dims.iter())
521                .any(|(&current, &max)| current < max);
522
523            if needs_padding {
524                // For now, just use the tensor as-is since we don't have full broadcasting yet
525                // In a full implementation, we'd properly pad with padding_value
526                // For this placeholder, we'll just use the original tensor
527            }
528
529            padded_batch.push(padded_tensor);
530        }
531
532        // Stack the padded tensors
533        stack_tensors(&padded_batch, 0)
534    }
535}
536
537/// Sparse tensor collation function
538#[cfg(feature = "sparse")]
539pub struct SparseCollate;
540
541#[cfg(feature = "sparse")]
542impl Collate<CooTensor> for SparseCollate {
543    type Output = CooTensor;
544
545    fn collate(&self, batch: Vec<CooTensor>) -> Result<Self::Output> {
546        if batch.is_empty() {
547            return Err(TorshError::InvalidArgument(
548                "Cannot collate empty batch".to_string(),
549            ));
550        }
551
552        // For sparse tensors, we concatenate them along the batch dimension
553        // This creates a larger sparse tensor with all the non-zero elements
554        collate_sparse_tensors(&batch)
555    }
556}
557
558/// Stack sparse tensors along a new batch dimension
559#[cfg(feature = "sparse")]
560pub fn collate_sparse_tensors(tensors: &[CooTensor]) -> Result<CooTensor> {
561    if tensors.is_empty() {
562        return Err(TorshError::InvalidArgument(
563            "Cannot collate empty sparse tensor batch".to_string(),
564        ));
565    }
566
567    // Check that all tensors have the same shape (except batch dimension)
568    let first_shape = tensors[0].shape();
569    for tensor in &tensors[1..] {
570        if tensor.shape() != first_shape {
571            return Err(TorshError::ShapeMismatch {
572                expected: first_shape.dims().to_vec(),
573                got: tensor.shape().dims().to_vec(),
574            });
575        }
576    }
577
578    // Calculate new shape with batch dimension
579    let original_dims = first_shape.dims();
580    let mut new_dims = Vec::with_capacity(original_dims.len() + 1);
581    new_dims.push(tensors.len());
582    new_dims.extend_from_slice(original_dims);
583
584    // For COO format, we need to:
585    // 1. Collect all indices and values
586    // 2. Adjust indices to account for batch dimension
587    // 3. Create new COO tensor
588
589    let mut all_row_indices = Vec::new();
590    let mut all_col_indices = Vec::new();
591    let mut all_values = Vec::new();
592    let mut _total_nnz = 0;
593
594    for (batch_idx, tensor) in tensors.iter().enumerate() {
595        let _row_indices = tensor.row_indices();
596        let col_indices = tensor.col_indices();
597        let values = tensor.values();
598
599        // Adjust indices to include batch dimension
600        for i in 0..tensor.nnz() {
601            all_row_indices.push(batch_idx);
602            all_col_indices.push(col_indices[i]);
603        }
604
605        all_values.extend_from_slice(values);
606        _total_nnz += tensor.nnz();
607    }
608
609    // Create new COO tensor
610    let shape = torsh_core::Shape::new(new_dims);
611    CooTensor::new(all_row_indices, all_col_indices, all_values, shape)
612}
613
614/// Collation function for mixed dense and sparse tensors
615#[cfg(feature = "sparse")]
616pub struct MixedCollate;
617
618#[cfg(feature = "sparse")]
619impl Collate<Box<dyn SparseTensor>> for MixedCollate {
620    type Output = Box<dyn SparseTensor>;
621
622    fn collate(&self, batch: Vec<Box<dyn SparseTensor>>) -> Result<Self::Output> {
623        if batch.is_empty() {
624            return Err(TorshError::InvalidArgument(
625                "Cannot collate empty batch".to_string(),
626            ));
627        }
628
629        // Convert all to COO format for consistency
630        let mut coo_tensors = Vec::with_capacity(batch.len());
631        for tensor in batch {
632            coo_tensors.push(tensor.to_coo()?);
633        }
634
635        // Use sparse collation
636        let collated = collate_sparse_tensors(&coo_tensors)?;
637        Ok(Box::new(collated))
638    }
639}