Skip to main content

torsh_data/dataloader/
core.rs

1//! Core DataLoader implementation
2//!
3//! This module contains the fundamental DataLoader functionality including the main
4//! DataLoader struct, its iterator, builder pattern, and core traits.
5
6use crate::{
7    collate::{Collate, DefaultCollate},
8    dataset::Dataset,
9    sampler::{BatchSampler, BatchingSampler, RandomSampler, SequentialSampler},
10};
11// ✅ SciRS2 POLICY: Use scirs2_core::parallel_ops instead of rayon::prelude
12use scirs2_core::parallel_ops::*;
13use torsh_core::error::{Result, TorshError};
14
15#[cfg(not(feature = "std"))]
16use alloc::{boxed::Box, vec::Vec};
17
18/// Trait for DataLoader functionality
19pub trait DataLoaderTrait<D: Dataset, C: Collate<D::Item>> {
20    /// Get the number of batches
21    fn len(&self) -> usize;
22
23    /// Check if the dataloader is empty
24    fn is_empty(&self) -> bool;
25}
26
27/// DataLoader for batching and iterating over datasets
28///
29/// The DataLoader provides an efficient way to iterate over datasets in batches,
30/// with support for parallel loading, shuffling, and various optimization strategies.
31///
32/// # Type Parameters
33///
34/// - `D`: Dataset type implementing the Dataset trait
35/// - `S`: Sampler type implementing the BatchSampler trait
36/// - `C`: Collate function type implementing the Collate trait
37///
38/// # Examples
39///
40/// ```rust,ignore
41/// use torsh_data::dataloader::core::DataLoader;
42/// use torsh_data::dataset::TensorDataset;
43///
44/// let dataset = TensorDataset::new(vec![1, 2, 3, 4, 5]);
45/// let dataloader = DataLoader::builder(dataset)
46///     .batch_size(2)
47///     .num_workers(4)
48///     .build()?;
49///
50/// for batch in dataloader.iter() {
51///     // Process batch
52/// }
53/// ```
54pub struct DataLoader<D, S, C> {
55    dataset: D,
56    sampler: S,
57    collate_fn: C,
58    num_workers: usize,
59    #[allow(dead_code)]
60    pin_memory: bool,
61    #[allow(dead_code)]
62    drop_last: bool,
63    #[allow(dead_code)]
64    timeout: Option<std::time::Duration>,
65}
66
67impl<D: Dataset> DataLoader<D, (), ()> {
68    /// Create a new DataLoader builder
69    ///
70    /// This provides a fluent API for configuring DataLoader options.
71    ///
72    /// # Arguments
73    ///
74    /// * `dataset` - The dataset to iterate over
75    ///
76    /// # Returns
77    ///
78    /// A DataLoaderBuilder for configuring the DataLoader
79    pub fn builder(dataset: D) -> DataLoaderBuilder<D> {
80        DataLoaderBuilder::new(dataset)
81    }
82}
83
84impl<D, S, C> DataLoader<D, S, C>
85where
86    D: Dataset,
87    S: BatchSampler,
88    C: Collate<D::Item>,
89{
90    /// Create an iterator over the dataset
91    ///
92    /// Returns a DataLoaderIterator that will yield batches according to
93    /// the configured sampler and collation function.
94    pub fn iter(&self) -> DataLoaderIterator<'_, D, S, C> {
95        DataLoaderIterator {
96            dataset: &self.dataset,
97            sampler_iter: self.sampler.iter(),
98            collate_fn: &self.collate_fn,
99            num_workers: self.num_workers,
100        }
101    }
102
103    /// Get the number of batches
104    ///
105    /// Returns the total number of batches that will be produced by this DataLoader,
106    /// based on the underlying sampler's batch count.
107    pub fn len(&self) -> usize {
108        self.sampler.len()
109    }
110
111    /// Check if the dataloader is empty
112    ///
113    /// Returns true if the DataLoader will produce zero batches.
114    pub fn is_empty(&self) -> bool {
115        self.sampler.is_empty()
116    }
117
118    /// Get the dataset
119    pub fn dataset(&self) -> &D {
120        &self.dataset
121    }
122
123    /// Get the sampler
124    pub fn sampler(&self) -> &S {
125        &self.sampler
126    }
127
128    /// Get the collate function
129    pub fn collate_fn(&self) -> &C {
130        &self.collate_fn
131    }
132
133    /// Get the number of workers
134    pub fn num_workers(&self) -> usize {
135        self.num_workers
136    }
137}
138
139impl<D, S, C> DataLoaderTrait<D, C> for DataLoader<D, S, C>
140where
141    D: Dataset + Sync,
142    S: BatchSampler + Sync,
143    C: Collate<D::Item> + Sync,
144    D::Item: Send,
145    C::Output: Send,
146    S::Iter: Iterator<Item = Vec<usize>>,
147{
148    fn len(&self) -> usize {
149        self.sampler.len()
150    }
151
152    fn is_empty(&self) -> bool {
153        self.sampler.is_empty()
154    }
155}
156
157/// Iterator for DataLoader
158///
159/// This iterator handles the actual batch loading process, including parallel
160/// processing when multiple workers are configured.
161pub struct DataLoaderIterator<'a, D, S, C>
162where
163    D: Dataset,
164    S: BatchSampler,
165    C: Collate<D::Item>,
166{
167    dataset: &'a D,
168    sampler_iter: S::Iter,
169    collate_fn: &'a C,
170    num_workers: usize,
171}
172
173impl<D, S, C> Iterator for DataLoaderIterator<'_, D, S, C>
174where
175    D: Dataset + Sync,
176    D::Item: Send,
177    S: BatchSampler,
178    S::Iter: Iterator<Item = Vec<usize>>,
179    C: Collate<D::Item> + Sync,
180    C::Output: Send,
181{
182    type Item = Result<C::Output>;
183
184    fn next(&mut self) -> Option<Self::Item> {
185        let indices = self.sampler_iter.next()?;
186
187        let batch_result = if self.num_workers > 1 {
188            // Parallel loading using Rayon
189            let samples: Result<Vec<_>> = indices
190                .into_par_iter()
191                .map(|idx| self.dataset.get(idx))
192                .collect();
193
194            match samples {
195                Ok(samples) => self.collate_fn.collate(samples),
196                Err(e) => return Some(Err(e)),
197            }
198        } else {
199            // Sequential loading
200            let mut samples = Vec::with_capacity(indices.len());
201            for idx in indices {
202                match self.dataset.get(idx) {
203                    Ok(sample) => samples.push(sample),
204                    Err(e) => return Some(Err(e)),
205                }
206            }
207            self.collate_fn.collate(samples)
208        };
209
210        // Apply memory pinning if enabled
211        match batch_result {
212            Ok(batch) => {
213                // Note: Memory pinning implementation would be applied here
214                // For now, this is a placeholder for the pin_memory flag
215                Some(Ok(batch))
216            }
217            Err(e) => Some(Err(e)),
218        }
219    }
220}
221
222/// Builder for DataLoader
223///
224/// Provides a fluent API for configuring DataLoader instances with various options
225/// such as batch size, shuffling, number of workers, and memory pinning.
226///
227/// # Examples
228///
229/// ```rust,ignore
230/// use torsh_data::dataloader::core::DataLoaderBuilder;
231/// use torsh_data::dataset::TensorDataset;
232///
233/// let dataset = TensorDataset::new(vec![1, 2, 3, 4, 5]);
234/// // NOTE: `build()` only produces sequential-order loaders; shuffling
235/// // requires `build_with_random_sampling()` (or `build_auto()`, which
236/// // dispatches on `.shuffle(..)` automatically).
237/// let dataloader = DataLoaderBuilder::new(dataset)
238///     .batch_size(32)
239///     .num_workers(4)
240///     .pin_memory(true)
241///     .drop_last(true)
242///     .build_with_random_sampling()?;
243/// ```
244pub struct DataLoaderBuilder<D: Dataset> {
245    dataset: D,
246    batch_size: Option<usize>,
247    shuffle: bool,
248    num_workers: usize,
249    pin_memory: bool,
250    drop_last: bool,
251    timeout: Option<std::time::Duration>,
252    generator: Option<u64>,
253}
254
255impl<D: Dataset> DataLoaderBuilder<D> {
256    /// Create a new builder
257    ///
258    /// # Arguments
259    ///
260    /// * `dataset` - The dataset to create a DataLoader for
261    pub fn new(dataset: D) -> Self {
262        Self {
263            dataset,
264            batch_size: None,
265            shuffle: false,
266            num_workers: 0,
267            pin_memory: false,
268            drop_last: false,
269            timeout: None,
270            generator: None,
271        }
272    }
273
274    /// Set batch size
275    ///
276    /// # Arguments
277    ///
278    /// * `batch_size` - Number of samples per batch
279    pub fn batch_size(mut self, batch_size: usize) -> Self {
280        self.batch_size = Some(batch_size);
281        self
282    }
283
284    /// Set whether to shuffle the data
285    ///
286    /// # Arguments
287    ///
288    /// * `shuffle` - Whether to randomly shuffle the dataset
289    pub fn shuffle(mut self, shuffle: bool) -> Self {
290        self.shuffle = shuffle;
291        self
292    }
293
294    /// Set the number of worker threads
295    ///
296    /// # Arguments
297    ///
298    /// * `num_workers` - Number of worker threads for parallel data loading
299    pub fn num_workers(mut self, num_workers: usize) -> Self {
300        self.num_workers = num_workers;
301        self
302    }
303
304    /// Set whether to pin memory
305    ///
306    /// # Arguments
307    ///
308    /// * `pin_memory` - Whether to pin memory for faster GPU transfers
309    pub fn pin_memory(mut self, pin_memory: bool) -> Self {
310        self.pin_memory = pin_memory;
311        self
312    }
313
314    /// Set whether to drop the last incomplete batch
315    ///
316    /// # Arguments
317    ///
318    /// * `drop_last` - Whether to drop the last batch if it's smaller than batch_size
319    pub fn drop_last(mut self, drop_last: bool) -> Self {
320        self.drop_last = drop_last;
321        self
322    }
323
324    /// Set timeout for collecting a batch
325    ///
326    /// # Arguments
327    ///
328    /// * `timeout` - Maximum time to wait for batch collection
329    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
330        self.timeout = Some(timeout);
331        self
332    }
333
334    /// Set random generator seed
335    ///
336    /// # Arguments
337    ///
338    /// * `seed` - Random seed for reproducible shuffling
339    pub fn generator(mut self, seed: u64) -> Self {
340        self.generator = Some(seed);
341        self
342    }
343
344    /// Build the DataLoader with sequential sampling
345    ///
346    /// Creates a DataLoader that processes the dataset in sequential order.
347    /// This is the default behavior when shuffle is false or not specified.
348    ///
349    /// # Errors
350    ///
351    /// Returns an error if `.shuffle(true)` was set on this builder: `build()`
352    /// can only construct a sequential-order `DataLoader` (its return type is
353    /// fixed to `BatchingSampler<SequentialSampler>`), so honoring a shuffle
354    /// request here is not possible without silently producing the wrong
355    /// iteration order. Use [`Self::build_with_random_sampling`] or
356    /// [`Self::build_auto`] instead when shuffling is desired.
357    pub fn build(
358        self,
359    ) -> Result<DataLoader<D, BatchingSampler<SequentialSampler>, DefaultCollate>> {
360        if self.shuffle {
361            return Err(TorshError::InvalidArgument(
362                "DataLoaderBuilder::build() only supports sequential sampling and cannot honor \
363                 shuffle(true); call build_with_random_sampling() or build_auto() instead"
364                    .to_string(),
365            ));
366        }
367        let batch_size = self.batch_size.unwrap_or(1);
368        let base_sampler = SequentialSampler::new(self.dataset.len());
369        let batch_sampler = BatchingSampler::new(base_sampler, batch_size, self.drop_last);
370
371        Ok(DataLoader {
372            dataset: self.dataset,
373            sampler: batch_sampler,
374            collate_fn: DefaultCollate,
375            num_workers: self.num_workers,
376            pin_memory: self.pin_memory,
377            drop_last: self.drop_last,
378            timeout: self.timeout,
379        })
380    }
381
382    /// Build the DataLoader with random sampling (shuffled)
383    ///
384    /// Creates a DataLoader that randomly shuffles the dataset order.
385    /// Useful for training scenarios where data order should be randomized.
386    pub fn build_with_random_sampling(
387        self,
388    ) -> Result<DataLoader<D, BatchingSampler<RandomSampler>, DefaultCollate>> {
389        let batch_size = self.batch_size.unwrap_or(1);
390        let mut base_sampler = RandomSampler::new(self.dataset.len(), None, false);
391
392        if let Some(seed) = self.generator {
393            base_sampler = base_sampler.with_generator(seed);
394        }
395
396        let batch_sampler = BatchingSampler::new(base_sampler, batch_size, self.drop_last);
397
398        Ok(DataLoader {
399            dataset: self.dataset,
400            sampler: batch_sampler,
401            collate_fn: DefaultCollate,
402            num_workers: self.num_workers,
403            pin_memory: self.pin_memory,
404            drop_last: self.drop_last,
405            timeout: self.timeout,
406        })
407    }
408
409    /// Build the DataLoader with auto-selected sampling strategy
410    ///
411    /// Automatically chooses between sequential and random sampling based on
412    /// the shuffle setting configured in the builder.
413    pub fn build_auto(self) -> Result<Box<dyn DataLoaderTrait<D, DefaultCollate> + Send + Sync>>
414    where
415        D: Send + Sync + 'static,
416        D::Item: Send + Sync + 'static,
417        DefaultCollate: Collate<D::Item>,
418        <DefaultCollate as Collate<D::Item>>::Output: Send,
419    {
420        if self.shuffle {
421            Ok(Box::new(self.build_with_random_sampling()?))
422        } else {
423            Ok(Box::new(self.build()?))
424        }
425    }
426}
427
428/// Simplified DataLoader type for common use cases
429///
430/// This type alias provides a convenient shorthand for the most common DataLoader
431/// configuration using sequential sampling and default collation.
432pub type SimpleDataLoader<D> = DataLoader<D, BatchingSampler<SequentialSampler>, DefaultCollate>;
433
434/// Simplified DataLoader type for random sampling use cases
435///
436/// This type alias provides a convenient shorthand for DataLoader with random sampling.
437pub type RandomDataLoader<D> = DataLoader<D, BatchingSampler<RandomSampler>, DefaultCollate>;
438
439impl<D, C> DataLoader<D, BatchingSampler<RandomSampler>, C>
440where
441    D: Dataset,
442    C: Collate<D::Item>,
443{
444    /// Advance the underlying [`RandomSampler`] to a new epoch.
445    ///
446    /// Call this once per training epoch before `iter()` so each epoch draws a
447    /// fresh, epoch-derived permutation instead of repeating the same order
448    /// (see `RandomSampler::set_epoch`). Reproducible: the same `(generator,
449    /// epoch)` pair always yields the same order.
450    pub fn set_epoch(&mut self, epoch: usize) {
451        self.sampler.set_epoch(epoch);
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use crate::dataset::TensorDataset;
459
460    #[test]
461    fn test_dataloader_builder() {
462        // Create a tensor with 5 samples (first dimension is number of samples)
463        let tensor = torsh_tensor::creation::ones::<f32>(&[5]).expect("operation should succeed");
464        let dataset = TensorDataset::from_tensor(tensor);
465        let builder = DataLoaderBuilder::new(dataset);
466
467        assert_eq!(builder.batch_size, None);
468        assert!(!builder.shuffle);
469        assert_eq!(builder.num_workers, 0);
470        assert!(!builder.pin_memory);
471        assert!(!builder.drop_last);
472    }
473
474    #[test]
475    fn test_dataloader_builder_configuration() {
476        // Create a tensor with 5 samples (first dimension is number of samples)
477        let tensor = torsh_tensor::creation::ones::<f32>(&[5]).expect("operation should succeed");
478        let dataset = TensorDataset::from_tensor(tensor);
479        let builder = DataLoaderBuilder::new(dataset)
480            .batch_size(2)
481            .shuffle(true)
482            .num_workers(4)
483            .pin_memory(true)
484            .drop_last(true);
485
486        assert_eq!(builder.batch_size, Some(2));
487        assert!(builder.shuffle);
488        assert_eq!(builder.num_workers, 4);
489        assert!(builder.pin_memory);
490        assert!(builder.drop_last);
491    }
492
493    #[test]
494    fn test_dataloader_sequential_build() {
495        // Create a tensor with 5 samples (first dimension is number of samples)
496        let tensor = torsh_tensor::creation::ones::<f32>(&[5]).expect("operation should succeed");
497        let dataset = TensorDataset::from_tensor(tensor);
498        let dataloader = DataLoaderBuilder::new(dataset)
499            .batch_size(2)
500            .build()
501            .expect("operation should succeed");
502
503        assert_eq!(dataloader.len(), 3); // 5 items, batch size 2 = 3 batches (last with 1 item)
504        assert!(!dataloader.is_empty());
505    }
506
507    #[test]
508    fn test_dataloader_random_build() {
509        // Create a tensor with 5 samples (first dimension is number of samples)
510        let tensor = torsh_tensor::creation::ones::<f32>(&[5]).expect("operation should succeed");
511        let dataset = TensorDataset::from_tensor(tensor);
512        let dataloader = DataLoaderBuilder::new(dataset)
513            .batch_size(2)
514            .generator(42)
515            .build_with_random_sampling()
516            .expect("operation should succeed");
517
518        assert_eq!(dataloader.len(), 3);
519        assert!(!dataloader.is_empty());
520    }
521
522    #[test]
523    fn test_dataloader_iteration() {
524        // Create a tensor with 4 samples (first dimension is number of samples)
525        let tensor = torsh_tensor::creation::ones::<f32>(&[4]).expect("operation should succeed");
526        let dataset = TensorDataset::from_tensor(tensor);
527        let dataloader = DataLoaderBuilder::new(dataset)
528            .batch_size(2)
529            .build()
530            .expect("operation should succeed");
531
532        let mut iter = dataloader.iter();
533        let batch1 = iter
534            .next()
535            .expect("iterator should have a next element")
536            .expect("operation should succeed");
537        let batch2 = iter
538            .next()
539            .expect("iterator should have a next element")
540            .expect("operation should succeed");
541        assert!(iter.next().is_none());
542
543        // Verify batch contents (each batch should have 1 stacked tensor)
544        assert_eq!(batch1.len(), 1);
545        assert_eq!(batch2.len(), 1);
546
547        // Verify the stacked tensor shape: [batch_size, sample_features]
548        // Original tensor is [4], each sample is [1], batched becomes [2, 1]
549        assert_eq!(batch1[0].shape().dims(), &[2, 1]); // 2 samples batched
550        assert_eq!(batch2[0].shape().dims(), &[2, 1]); // 2 samples batched
551    }
552
553    #[test]
554    fn test_dataloader_drop_last() {
555        // Create a tensor with 5 samples (first dimension is number of samples)
556        let tensor = torsh_tensor::creation::ones::<f32>(&[5]).expect("operation should succeed");
557        let dataset = TensorDataset::from_tensor(tensor);
558        let dataloader = DataLoaderBuilder::new(dataset)
559            .batch_size(2)
560            .drop_last(true)
561            .build()
562            .expect("operation should succeed");
563
564        assert_eq!(dataloader.len(), 2); // 5 items, batch size 2, drop_last = 2 complete batches
565    }
566
567    #[test]
568    fn test_dataloader_trait_implementation() {
569        // Create a tensor with 5 samples (first dimension is number of samples)
570        let tensor = torsh_tensor::creation::ones::<f32>(&[5]).expect("operation should succeed");
571        let dataset = TensorDataset::from_tensor(tensor);
572        let dataloader = DataLoaderBuilder::new(dataset)
573            .batch_size(2)
574            .build()
575            .expect("operation should succeed");
576
577        // Test trait methods
578        assert_eq!(DataLoaderTrait::len(&dataloader), 3);
579        assert!(!DataLoaderTrait::is_empty(&dataloader));
580    }
581
582    #[test]
583    fn test_empty_dataloader() {
584        let tensors: Vec<torsh_tensor::Tensor<f32>> = vec![];
585        let dataset = TensorDataset::new(tensors);
586        let dataloader = DataLoaderBuilder::new(dataset)
587            .batch_size(2)
588            .build()
589            .expect("operation should succeed");
590
591        assert_eq!(dataloader.len(), 0);
592        assert!(dataloader.is_empty());
593
594        let mut iter = dataloader.iter();
595        assert!(iter.next().is_none());
596    }
597}