Skip to main content

torsh_data/sampler/
batch.rs

1//! Batch sampling functionality
2//!
3//! This module provides utilities for converting individual samplers into
4//! batch samplers that yield batches of indices instead of individual indices.
5
6#[cfg(not(feature = "std"))]
7use alloc::vec::Vec;
8
9use super::core::{BatchSampler, Sampler};
10
11/// Wrapper that converts any sampler into a batch sampler
12///
13/// This sampler takes an underlying sampler and groups its output into batches
14/// of a specified size. The last batch may be smaller than the batch size
15/// unless `drop_last` is set to true.
16///
17/// # Examples
18///
19/// ```rust,ignore
20/// use torsh_data::sampler::{SequentialSampler, BatchingSampler, BatchSampler};
21///
22/// let base_sampler = SequentialSampler::new(10);
23/// let batch_sampler = BatchingSampler::new(base_sampler, 3, false);
24///
25/// let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
26/// assert_eq!(batches.len(), 4); // [0,1,2], [3,4,5], [6,7,8], [9]
27/// ```
28#[derive(Debug, Clone)]
29pub struct BatchingSampler<S: Sampler> {
30    sampler: S,
31    batch_size: usize,
32    drop_last: bool,
33}
34
35impl<S: Sampler> BatchingSampler<S> {
36    /// Create a new batching sampler
37    ///
38    /// # Arguments
39    ///
40    /// * `sampler` - The underlying sampler to batch
41    /// * `batch_size` - Size of each batch
42    /// * `drop_last` - Whether to drop the last incomplete batch
43    ///
44    /// # Panics
45    ///
46    /// Panics if `batch_size` is 0
47    pub fn new(sampler: S, batch_size: usize, drop_last: bool) -> Self {
48        assert!(batch_size > 0, "Batch size must be positive");
49        Self {
50            sampler,
51            batch_size,
52            drop_last,
53        }
54    }
55
56    /// Fallible variant of [`new`](Self::new) that returns an error instead of
57    /// panicking when `batch_size` is 0.
58    pub fn try_new(
59        sampler: S,
60        batch_size: usize,
61        drop_last: bool,
62    ) -> torsh_core::error::Result<Self> {
63        crate::utils::validate_positive(batch_size, "batch_size")?;
64        Ok(Self {
65            sampler,
66            batch_size,
67            drop_last,
68        })
69    }
70
71    /// Get the batch size
72    pub fn batch_size(&self) -> usize {
73        self.batch_size
74    }
75
76    /// Check if dropping last incomplete batch
77    pub fn drop_last(&self) -> bool {
78        self.drop_last
79    }
80
81    /// Get a reference to the underlying sampler
82    pub fn sampler(&self) -> &S {
83        &self.sampler
84    }
85
86    /// Get the underlying sampler by value
87    pub fn into_sampler(self) -> S {
88        self.sampler
89    }
90
91    /// Convert this batching sampler into a distributed version
92    ///
93    /// This creates a distributed wrapper around the underlying sampler
94    /// and then wraps it with a new BatchingSampler.
95    ///
96    /// # Arguments
97    ///
98    /// * `num_replicas` - Total number of processes
99    /// * `rank` - Current process rank (0-based)
100    pub fn into_distributed(
101        self,
102        num_replicas: usize,
103        rank: usize,
104    ) -> BatchingSampler<super::distributed::DistributedWrapper<S>> {
105        let distributed_sampler = self.sampler.into_distributed(num_replicas, rank);
106        BatchingSampler::new(distributed_sampler, self.batch_size, self.drop_last)
107    }
108}
109
110// F008: forward `set_epoch` through `BatchingSampler` for the epoch-aware
111// sampler types, so a `DataLoader` built with e.g. `RandomSampler` doesn't
112// need to unwrap its batch sampler just to advance the epoch each training
113// loop iteration.
114impl BatchingSampler<super::basic::RandomSampler> {
115    /// Advance the underlying [`RandomSampler`](super::basic::RandomSampler) to
116    /// a new epoch. See `RandomSampler::set_epoch`.
117    pub fn set_epoch(&mut self, epoch: usize) {
118        self.sampler.set_epoch(epoch);
119    }
120}
121
122impl BatchingSampler<super::distributed::DistributedSampler> {
123    /// Advance the underlying
124    /// [`DistributedSampler`](super::distributed::DistributedSampler) to a new
125    /// epoch. See `DistributedSampler::set_epoch`.
126    pub fn set_epoch(&mut self, epoch: usize) {
127        self.sampler.set_epoch(epoch);
128    }
129}
130
131impl<S: Sampler> BatchingSampler<super::distributed::DistributedWrapper<S>> {
132    /// Advance the underlying
133    /// [`DistributedWrapper`](super::distributed::DistributedWrapper) to a new
134    /// epoch. See `DistributedWrapper::set_epoch`.
135    pub fn set_epoch(&mut self, epoch: usize) {
136        self.sampler.set_epoch(epoch);
137    }
138}
139
140impl<S: Sampler> BatchSampler for BatchingSampler<S> {
141    type Iter = BatchSamplerIter<S::Iter>;
142
143    fn iter(&self) -> Self::Iter {
144        BatchSamplerIter::new(self.sampler.iter(), self.batch_size, self.drop_last)
145    }
146
147    fn num_batches(&self) -> usize {
148        let total_samples = self.sampler.len();
149        if total_samples == 0 {
150            return 0;
151        }
152
153        if self.drop_last {
154            total_samples / self.batch_size
155        } else {
156            (total_samples + self.batch_size - 1) / self.batch_size
157        }
158    }
159}
160
161/// Iterator that groups indices from an underlying iterator into batches
162#[derive(Debug)]
163pub struct BatchSamplerIter<I: Iterator<Item = usize>> {
164    inner: I,
165    batch_size: usize,
166    drop_last: bool,
167}
168
169impl<I: Iterator<Item = usize>> BatchSamplerIter<I> {
170    /// Create a new batch sampler iterator
171    pub fn new(inner: I, batch_size: usize, drop_last: bool) -> Self {
172        Self {
173            inner,
174            batch_size,
175            drop_last,
176        }
177    }
178
179    /// Get the batch size
180    pub fn batch_size(&self) -> usize {
181        self.batch_size
182    }
183
184    /// Check if dropping last incomplete batch
185    pub fn drop_last(&self) -> bool {
186        self.drop_last
187    }
188}
189
190impl<I: Iterator<Item = usize>> Iterator for BatchSamplerIter<I> {
191    type Item = Vec<usize>;
192
193    fn next(&mut self) -> Option<Self::Item> {
194        let mut batch = Vec::with_capacity(self.batch_size);
195
196        // Collect items for this batch
197        for _ in 0..self.batch_size {
198            if let Some(item) = self.inner.next() {
199                batch.push(item);
200            } else {
201                break;
202            }
203        }
204
205        if batch.is_empty() {
206            None
207        } else if batch.len() < self.batch_size && self.drop_last {
208            None
209        } else {
210            Some(batch)
211        }
212    }
213
214    fn size_hint(&self) -> (usize, Option<usize>) {
215        let (lower, upper) = self.inner.size_hint();
216
217        let lower_batches = if self.drop_last {
218            lower / self.batch_size
219        } else {
220            (lower + self.batch_size - 1) / self.batch_size
221        };
222
223        let upper_batches = upper.map(|u| {
224            if self.drop_last {
225                u / self.batch_size
226            } else {
227                (u + self.batch_size - 1) / self.batch_size
228            }
229        });
230
231        (lower_batches, upper_batches)
232    }
233}
234
235/// Create a batch sampler from any sampler
236///
237/// Convenience function for creating a batch sampler.
238///
239/// # Arguments
240///
241/// * `sampler` - The underlying sampler
242/// * `batch_size` - Size of each batch
243/// * `drop_last` - Whether to drop the last incomplete batch
244pub fn batch<S: Sampler>(sampler: S, batch_size: usize, drop_last: bool) -> BatchingSampler<S> {
245    BatchingSampler::new(sampler, batch_size, drop_last)
246}
247
248/// Create a batch sampler that keeps the last incomplete batch
249///
250/// Convenience function for creating a batch sampler that doesn't drop
251/// the last batch even if it's incomplete.
252///
253/// # Arguments
254///
255/// * `sampler` - The underlying sampler
256/// * `batch_size` - Size of each batch
257pub fn batch_keep_last<S: Sampler>(sampler: S, batch_size: usize) -> BatchingSampler<S> {
258    BatchingSampler::new(sampler, batch_size, false)
259}
260
261/// Create a batch sampler that drops the last incomplete batch
262///
263/// Convenience function for creating a batch sampler that drops
264/// the last batch if it's incomplete.
265///
266/// # Arguments
267///
268/// * `sampler` - The underlying sampler
269/// * `batch_size` - Size of each batch
270pub fn batch_drop_last<S: Sampler>(sampler: S, batch_size: usize) -> BatchingSampler<S> {
271    BatchingSampler::new(sampler, batch_size, true)
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277    use crate::sampler::basic::SequentialSampler;
278
279    #[test]
280    fn test_batching_sampler_basic() {
281        let base_sampler = SequentialSampler::new(10);
282        let batch_sampler = BatchingSampler::new(base_sampler, 3, false);
283
284        assert_eq!(batch_sampler.batch_size(), 3);
285        assert!(!batch_sampler.drop_last());
286        assert_eq!(batch_sampler.num_batches(), 4); // 10 items, 3 per batch = 4 batches
287
288        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
289        assert_eq!(batches.len(), 4);
290        assert_eq!(batches[0], vec![0, 1, 2]);
291        assert_eq!(batches[1], vec![3, 4, 5]);
292        assert_eq!(batches[2], vec![6, 7, 8]);
293        assert_eq!(batches[3], vec![9]); // Last incomplete batch
294    }
295
296    #[test]
297    fn test_batching_sampler_drop_last() {
298        let base_sampler = SequentialSampler::new(10);
299        let batch_sampler = BatchingSampler::new(base_sampler, 3, true);
300
301        assert!(batch_sampler.drop_last());
302        assert_eq!(batch_sampler.num_batches(), 3); // Drops last incomplete batch
303
304        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
305        assert_eq!(batches.len(), 3);
306        assert_eq!(batches[0], vec![0, 1, 2]);
307        assert_eq!(batches[1], vec![3, 4, 5]);
308        assert_eq!(batches[2], vec![6, 7, 8]);
309        // Last batch [9] is dropped
310    }
311
312    #[test]
313    fn test_batching_sampler_exact_division() {
314        let base_sampler = SequentialSampler::new(9);
315        let batch_sampler = BatchingSampler::new(base_sampler, 3, true);
316
317        assert_eq!(batch_sampler.num_batches(), 3);
318
319        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
320        assert_eq!(batches.len(), 3);
321        assert_eq!(batches[0], vec![0, 1, 2]);
322        assert_eq!(batches[1], vec![3, 4, 5]);
323        assert_eq!(batches[2], vec![6, 7, 8]);
324    }
325
326    #[test]
327    fn test_batching_sampler_empty() {
328        let base_sampler = SequentialSampler::new(0);
329        let batch_sampler = BatchingSampler::new(base_sampler, 3, false);
330
331        assert_eq!(batch_sampler.num_batches(), 0);
332        assert!(batch_sampler.is_empty());
333
334        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
335        assert_eq!(batches.len(), 0);
336    }
337
338    #[test]
339    fn test_batching_sampler_single_item() {
340        let base_sampler = SequentialSampler::new(1);
341        let batch_sampler = BatchingSampler::new(base_sampler, 3, false);
342
343        assert_eq!(batch_sampler.num_batches(), 1);
344
345        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
346        assert_eq!(batches.len(), 1);
347        assert_eq!(batches[0], vec![0]);
348    }
349
350    #[test]
351    fn test_batching_sampler_single_item_drop_last() {
352        let base_sampler = SequentialSampler::new(1);
353        let batch_sampler = BatchingSampler::new(base_sampler, 3, true);
354
355        assert_eq!(batch_sampler.num_batches(), 0);
356
357        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
358        assert_eq!(batches.len(), 0);
359    }
360
361    #[test]
362    #[should_panic(expected = "Batch size must be positive")]
363    fn test_batching_sampler_zero_batch_size() {
364        let base_sampler = SequentialSampler::new(10);
365        BatchingSampler::new(base_sampler, 0, false);
366    }
367
368    #[test]
369    fn test_batch_sampler_iter_size_hint() {
370        let base_sampler = SequentialSampler::new(10);
371        let batch_sampler = BatchingSampler::new(base_sampler, 3, false);
372
373        let iter = batch_sampler.iter();
374        assert_eq!(iter.size_hint(), (4, Some(4)));
375
376        let batch_sampler_drop = BatchingSampler::new(SequentialSampler::new(10), 3, true);
377        let iter_drop = batch_sampler_drop.iter();
378        assert_eq!(iter_drop.size_hint(), (3, Some(3)));
379    }
380
381    #[test]
382    fn test_batching_sampler_into_sampler() {
383        let base_sampler = SequentialSampler::new(5);
384        let batch_sampler = BatchingSampler::new(base_sampler, 2, false);
385
386        let recovered_sampler = batch_sampler.into_sampler();
387        assert_eq!(recovered_sampler.len(), 5);
388    }
389
390    #[test]
391    fn test_convenience_functions() {
392        let base_sampler = SequentialSampler::new(10);
393
394        let batch_keep = batch_keep_last(base_sampler.clone(), 3);
395        assert!(!batch_keep.drop_last());
396        assert_eq!(batch_keep.num_batches(), 4);
397
398        let batch_drop = batch_drop_last(base_sampler.clone(), 3);
399        assert!(batch_drop.drop_last());
400        assert_eq!(batch_drop.num_batches(), 3);
401
402        let batch_generic = batch(base_sampler, 3, true);
403        assert!(batch_generic.drop_last());
404        assert_eq!(batch_generic.num_batches(), 3);
405    }
406
407    #[test]
408    fn test_batch_sampler_iter_properties() {
409        let base_sampler = SequentialSampler::new(7);
410        let batch_sampler = BatchingSampler::new(base_sampler, 3, false);
411
412        let mut iter = batch_sampler.iter();
413        assert_eq!(iter.batch_size(), 3);
414        assert!(!iter.drop_last());
415
416        // Test collecting batches one by one
417        let batch1 = iter.next().expect("iterator should have a next element");
418        assert_eq!(batch1, vec![0, 1, 2]);
419
420        let batch2 = iter.next().expect("iterator should have a next element");
421        assert_eq!(batch2, vec![3, 4, 5]);
422
423        let batch3 = iter.next().expect("iterator should have a next element");
424        assert_eq!(batch3, vec![6]);
425
426        assert!(iter.next().is_none());
427    }
428
429    #[test]
430    fn test_batch_sizes() {
431        // Test various batch sizes
432        let test_cases = vec![
433            (10, 1, false, 10), // Each item is its own batch
434            (10, 10, false, 1), // Single batch with all items
435            (10, 15, false, 1), // Batch size larger than dataset
436            (0, 5, false, 0),   // Empty dataset
437        ];
438
439        for (dataset_size, batch_size, drop_last, expected_batches) in test_cases {
440            if dataset_size == 0 && batch_size > 0 {
441                // Skip invalid combinations handled by SequentialSampler
442                continue;
443            }
444
445            let base_sampler = SequentialSampler::new(dataset_size);
446            let batch_sampler = BatchingSampler::new(base_sampler, batch_size, drop_last);
447
448            assert_eq!(
449                batch_sampler.num_batches(),
450                expected_batches,
451                "Failed for dataset_size={}, batch_size={}, drop_last={}",
452                dataset_size,
453                batch_size,
454                drop_last
455            );
456
457            let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
458            assert_eq!(
459                batches.len(),
460                expected_batches,
461                "Actual batch count doesn't match for dataset_size={}, batch_size={}, drop_last={}",
462                dataset_size,
463                batch_size,
464                drop_last
465            );
466        }
467    }
468
469    #[test]
470    fn test_edge_case_large_batch_size() {
471        let base_sampler = SequentialSampler::new(3);
472        let batch_sampler = BatchingSampler::new(base_sampler, 100, false);
473
474        let batches: Vec<Vec<usize>> = batch_sampler.iter().collect();
475        assert_eq!(batches.len(), 1);
476        assert_eq!(batches[0], vec![0, 1, 2]);
477    }
478}