torsh_data/dataloader/mod.rs
1//! DataLoader implementation for efficient data loading
2//!
3//! This module provides comprehensive data loading capabilities with support for
4//! batching, parallel processing, prefetching, and memory optimization.
5//!
6//! # Overview
7//!
8//! The DataLoader system consists of several key components:
9//!
10//! - **Core**: Fundamental DataLoader functionality including the main struct, iterator, and builder
11//! - **Simple**: Convenience functions for quick DataLoader creation
12//! - **Prefetch**: Performance optimization through background data loading
13//! - **Workers**: Multi-process data loading with worker pools
14//! - **Memory**: Memory pinning for optimized GPU transfers
15//!
16//! # Quick Start
17//!
18//! ```rust,ignore
19//! use torsh_data::dataloader::{DataLoader, simple_dataloader};
20//! use torsh_data::dataset::TensorDataset;
21//!
22//! // Using the builder pattern. NOTE: `.build()` only ever produces a
23//! // sequential-order loader; it now returns an error if `.shuffle(true)` was
24//! // requested. Use `build_with_random_sampling()` (or `build_auto()`, which
25//! // dispatches on `.shuffle(..)`) to actually shuffle.
26//! let dataset = TensorDataset::new(vec![1, 2, 3, 4, 5]);
27//! let dataloader = DataLoader::builder(dataset)
28//! .batch_size(2)
29//! .num_workers(4)
30//! .build_with_random_sampling()?;
31//!
32//! for batch in dataloader.iter() {
33//! // Process batch
34//! }
35//!
36//! // Using the simple API
37//! let dataset = TensorDataset::new(vec![1, 2, 3, 4, 5]);
38//! let dataloader = simple_dataloader(dataset, 2, false)?;
39//! ```
40//!
41//! # Advanced Usage
42//!
43//! ## Prefetching for Performance
44//!
45//! ```rust,ignore
46//! use torsh_data::dataloader::{DataLoader, prefetch::PrefetchExt};
47//! use torsh_data::dataset::TensorDataset;
48//!
49//! let dataset = TensorDataset::new(vec![1, 2, 3, 4, 5]);
50//! let dataloader = DataLoader::builder(dataset).batch_size(2).build()?;
51//!
52//! // Add prefetching for better performance
53//! let prefetch_iter = dataloader.iter().prefetch(2);
54//! for batch in prefetch_iter {
55//! // Process batch while next batches are being prefetched
56//! }
57//! ```
58//!
59//! ## Multi-Process Loading
60//!
61//! ```rust,ignore
62//! use std::sync::Arc;
63//! use torsh_data::dataloader::{DataLoader, workers::WorkerPool};
64//! use torsh_data::dataset::TensorDataset;
65//! use torsh_data::collate::DefaultCollate;
66//!
67//! let dataset = Arc::new(TensorDataset::new(vec![1, 2, 3, 4, 5]));
68//! let collate_fn = Arc::new(DefaultCollate);
69//! let worker_pool = WorkerPool::new(dataset, collate_fn, 4);
70//!
71//! // Submit tasks and collect results
72//! worker_pool.submit_task(0, vec![0, 1])?;
73//! let result = worker_pool.get_result()?;
74//! ```
75//!
76//! ## Memory Pinning for GPU
77//!
78//! ```rust,ignore
79//! use torsh_data::dataloader::memory::{MemoryPinningManager, PinningConfig};
80//! use torsh_core::device::DeviceType;
81//!
82//! let mut manager = MemoryPinningManager::new();
83//! let config = PinningConfig::cuda(0);
84//!
85//! // Pin memory for faster GPU transfers
86//! if manager.supports_pinning(Some(DeviceType::Cuda(0))) {
87//! // Use pinned memory for data transfers
88//! }
89//! ```
90
91use torsh_core::error::Result;
92
93// Re-export sub-modules
94pub mod core;
95pub mod memory;
96pub mod prefetch;
97pub mod simple;
98pub mod workers;
99
100// Re-export core types for backward compatibility and convenience
101pub use core::{
102 DataLoader, DataLoaderBuilder, DataLoaderIterator, DataLoaderTrait, RandomDataLoader,
103 SimpleDataLoader,
104};
105
106// Re-export simple API functions
107pub use simple::{
108 simple_dataloader, simple_random_dataloader, SimpleConfig, SimpleRandomDataLoader,
109};
110
111// Re-export prefetch functionality
112pub use prefetch::{PrefetchConfig, PrefetchExt, PrefetchIterator};
113
114// Re-export worker functionality
115pub use workers::{
116 MultiProcessIterator, PersistentWorkerPool, WorkerConfig, WorkerPool, WorkerResult,
117};
118
119// Re-export memory functionality
120pub use memory::{CpuMemoryPinner, MemoryPinning, MemoryPinningManager, PinningConfig};
121
122#[cfg(feature = "cuda")]
123pub use memory::CudaMemoryPinner;
124
125/// Configuration for DataLoader creation with all options
126///
127/// This struct provides a comprehensive configuration interface that combines
128/// options from all DataLoader components.
129#[derive(Debug, Clone)]
130pub struct DataLoaderConfig {
131 /// Batch size for data loading
132 pub batch_size: usize,
133 /// Whether to shuffle the data
134 pub shuffle: bool,
135 /// Number of worker threads
136 pub num_workers: usize,
137 /// Whether to pin memory for GPU transfers
138 pub pin_memory: bool,
139 /// Whether to drop the last incomplete batch
140 pub drop_last: bool,
141 /// Timeout for batch collection
142 pub timeout: Option<std::time::Duration>,
143 /// Random seed for reproducible shuffling
144 pub generator: Option<u64>,
145 /// Prefetch buffer size (0 to disable prefetching)
146 pub prefetch_buffer_size: usize,
147 /// Whether to use persistent workers
148 pub persistent_workers: bool,
149 /// Memory pinning configuration
150 pub pinning_config: Option<PinningConfig>,
151}
152
153impl Default for DataLoaderConfig {
154 fn default() -> Self {
155 Self {
156 batch_size: 1,
157 shuffle: false,
158 num_workers: 0,
159 pin_memory: false,
160 drop_last: false,
161 timeout: None,
162 generator: None,
163 prefetch_buffer_size: 0,
164 persistent_workers: false,
165 pinning_config: None,
166 }
167 }
168}
169
170impl DataLoaderConfig {
171 /// Create a new DataLoader configuration
172 pub fn new() -> Self {
173 Self::default()
174 }
175
176 /// Set batch size
177 pub fn batch_size(mut self, batch_size: usize) -> Self {
178 self.batch_size = batch_size;
179 self
180 }
181
182 /// Set shuffle
183 pub fn shuffle(mut self, shuffle: bool) -> Self {
184 self.shuffle = shuffle;
185 self
186 }
187
188 /// Set number of workers
189 pub fn num_workers(mut self, num_workers: usize) -> Self {
190 self.num_workers = num_workers;
191 self
192 }
193
194 /// Set pin memory
195 pub fn pin_memory(mut self, pin_memory: bool) -> Self {
196 self.pin_memory = pin_memory;
197 self
198 }
199
200 /// Set drop last
201 pub fn drop_last(mut self, drop_last: bool) -> Self {
202 self.drop_last = drop_last;
203 self
204 }
205
206 /// Set timeout
207 pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
208 self.timeout = Some(timeout);
209 self
210 }
211
212 /// Set generator seed
213 pub fn generator(mut self, seed: u64) -> Self {
214 self.generator = Some(seed);
215 self
216 }
217
218 /// Set prefetch buffer size
219 pub fn prefetch_buffer_size(mut self, size: usize) -> Self {
220 self.prefetch_buffer_size = size;
221 self
222 }
223
224 /// Enable persistent workers
225 pub fn persistent_workers(mut self, persistent: bool) -> Self {
226 self.persistent_workers = persistent;
227 self
228 }
229
230 /// Set memory pinning configuration
231 pub fn pinning_config(mut self, config: PinningConfig) -> Self {
232 self.pinning_config = Some(config);
233 self
234 }
235
236 /// Create a configuration optimized for training
237 pub fn for_training() -> Self {
238 Self::new()
239 .batch_size(32)
240 .shuffle(true)
241 .num_workers(workers::utils::optimal_worker_count(false))
242 .pin_memory(true)
243 .prefetch_buffer_size(4)
244 .persistent_workers(true)
245 }
246
247 /// Create a configuration optimized for inference
248 pub fn for_inference() -> Self {
249 Self::new()
250 .batch_size(1)
251 .shuffle(false)
252 .num_workers(workers::utils::optimal_worker_count(true))
253 .pin_memory(false)
254 .prefetch_buffer_size(2)
255 .persistent_workers(false)
256 }
257
258 /// Create a configuration optimized for evaluation
259 pub fn for_evaluation() -> Self {
260 Self::new()
261 .batch_size(32)
262 .shuffle(false)
263 .num_workers(workers::utils::optimal_worker_count(false))
264 .pin_memory(false)
265 .prefetch_buffer_size(2)
266 .persistent_workers(false)
267 .drop_last(false)
268 }
269}
270
271/// Create a DataLoader with comprehensive configuration
272///
273/// Note: This function was removed due to lifetime issues with returning boxed iterators.
274/// Use DataLoader::builder() directly for configuration, or simple_dataloader()/simple_random_dataloader() for basic usage.
275///
276/// # Examples
277///
278/// ```rust,ignore
279/// use torsh_data::dataloader::{DataLoader, simple_dataloader, simple_random_dataloader};
280/// use torsh_data::dataset::TensorDataset;
281///
282/// let dataset = TensorDataset::new(vec![1, 2, 3, 4, 5]);
283///
284/// // Option 1: Use simple functions
285/// let dataloader = simple_dataloader(dataset, 2, false)?;
286/// for batch in dataloader.iter() {
287/// // Process batch
288/// }
289///
290/// // Option 2: Use builder pattern
291/// let dataloader = DataLoader::builder(dataset)
292/// .batch_size(16)
293/// .shuffle(true)
294/// .build()?;
295/// ```
296
297/// Utility functions for DataLoader operations
298pub mod utils {
299 use super::*;
300 use torsh_core::device::DeviceType;
301
302 /// Determine optimal DataLoader configuration for a given scenario
303 ///
304 /// # Arguments
305 ///
306 /// * `dataset_size` - Size of the dataset
307 /// * `scenario` - Training, inference, or evaluation scenario
308 /// * `target_device` - Target device for data
309 ///
310 /// # Returns
311 ///
312 /// Optimized DataLoaderConfig for the scenario
313 pub fn optimal_config(
314 dataset_size: usize,
315 scenario: &str,
316 target_device: Option<DeviceType>,
317 ) -> DataLoaderConfig {
318 let base_config = match scenario.to_lowercase().as_str() {
319 "training" | "train" => DataLoaderConfig::for_training(),
320 "inference" | "infer" => DataLoaderConfig::for_inference(),
321 "evaluation" | "eval" | "test" => DataLoaderConfig::for_evaluation(),
322 _ => DataLoaderConfig::new(),
323 };
324
325 let mut config = base_config;
326
327 // Adjust batch size based on dataset size
328 if dataset_size < 100 {
329 config = config.batch_size(dataset_size.min(8));
330 } else if dataset_size < 1000 {
331 config = config.batch_size(16);
332 } else {
333 config = config.batch_size(32);
334 }
335
336 // Configure memory pinning based on target device
337 if let Some(device) = target_device {
338 match device {
339 DeviceType::Cuda(device_id) => {
340 config = config
341 .pin_memory(true)
342 .pinning_config(PinningConfig::cuda(device_id));
343 }
344 _ => {
345 config = config.pin_memory(false);
346 }
347 }
348 }
349
350 config
351 }
352
353 /// Create a DataLoader with automatic configuration
354 ///
355 /// # Arguments
356 ///
357 /// * `dataset` - The dataset to load from
358 /// * `scenario` - Training scenario ("training", "inference", "evaluation")
359 ///
360 /// # Returns
361 ///
362 /// A DataLoader with automatically optimized configuration
363 ///
364 /// Note: This function was removed due to lifetime issues.
365 /// Use DataLoader::builder() with manual configuration instead.
366 // pub fn auto_dataloader(...) -- removed due to lifetime issues
367
368 /// Validate DataLoader configuration for common issues
369 ///
370 /// # Arguments
371 ///
372 /// * `config` - Configuration to validate
373 /// * `dataset_size` - Size of the dataset
374 ///
375 /// # Returns
376 ///
377 /// Result with validation messages or errors
378 pub fn validate_config(config: &DataLoaderConfig, dataset_size: usize) -> Result<Vec<String>> {
379 let mut warnings = Vec::new();
380
381 // Check batch size
382 if config.batch_size > dataset_size {
383 warnings.push(format!(
384 "Batch size ({}) is larger than dataset size ({})",
385 config.batch_size, dataset_size
386 ));
387 }
388
389 // Check worker configuration
390 if config.num_workers
391 > std::thread::available_parallelism()
392 .map(|n| n.get())
393 .unwrap_or(1)
394 * 2
395 {
396 warnings.push(format!(
397 "Number of workers ({}) may be too high for system capabilities",
398 config.num_workers
399 ));
400 }
401
402 // Check prefetch buffer size
403 if config.prefetch_buffer_size > 0 && config.num_workers == 0 {
404 warnings.push(
405 "Prefetching enabled but no workers configured, may not improve performance"
406 .to_string(),
407 );
408 }
409
410 // Check memory pinning
411 if config.pin_memory && config.pinning_config.is_none() {
412 warnings
413 .push("Memory pinning enabled but no pinning configuration provided".to_string());
414 }
415
416 Ok(warnings)
417 }
418
419 /// Get performance recommendations for DataLoader configuration
420 ///
421 /// # Arguments
422 ///
423 /// * `dataset_size` - Size of the dataset
424 /// * `batch_size` - Current batch size
425 /// * `scenario` - Use case scenario
426 ///
427 /// # Returns
428 ///
429 /// Vector of performance recommendations
430 pub fn performance_recommendations(
431 dataset_size: usize,
432 batch_size: usize,
433 scenario: &str,
434 ) -> Vec<String> {
435 let mut recommendations = Vec::new();
436
437 // Batch size recommendations
438 if scenario == "training" && batch_size < 16 {
439 recommendations.push(
440 "Consider increasing batch size for training (recommended: 16-32)".to_string(),
441 );
442 }
443
444 if batch_size > dataset_size / 10 {
445 recommendations.push(
446 "Large batch size relative to dataset may reduce training effectiveness"
447 .to_string(),
448 );
449 }
450
451 // Worker recommendations
452 let optimal_workers = workers::utils::optimal_worker_count(scenario == "inference");
453 recommendations.push(format!(
454 "Consider using {} workers for optimal performance",
455 optimal_workers
456 ));
457
458 // Prefetching recommendations
459 if scenario == "training" {
460 recommendations.push(
461 "Enable prefetching (buffer size 2-4) for better training performance".to_string(),
462 );
463 }
464
465 // Memory pinning recommendations
466 recommendations.push("Enable memory pinning if transferring data to GPU".to_string());
467
468 recommendations
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475 use crate::dataset::TensorDataset;
476 use torsh_core::device::DeviceType;
477
478 #[test]
479 fn test_dataloader_config() {
480 let config = DataLoaderConfig::new()
481 .batch_size(16)
482 .shuffle(true)
483 .num_workers(4)
484 .prefetch_buffer_size(2);
485
486 assert_eq!(config.batch_size, 16);
487 assert!(config.shuffle);
488 assert_eq!(config.num_workers, 4);
489 assert_eq!(config.prefetch_buffer_size, 2);
490 }
491
492 #[test]
493 fn test_training_config() {
494 let config = DataLoaderConfig::for_training();
495 assert!(config.shuffle);
496 assert!(config.persistent_workers);
497 assert!(config.pin_memory);
498 assert!(config.prefetch_buffer_size > 0);
499 }
500
501 #[test]
502 fn test_inference_config() {
503 let config = DataLoaderConfig::for_inference();
504 assert!(!config.shuffle);
505 assert!(!config.persistent_workers);
506 assert!(!config.pin_memory);
507 }
508
509 #[test]
510 fn test_evaluation_config() {
511 let config = DataLoaderConfig::for_evaluation();
512 assert!(!config.shuffle);
513 assert!(!config.drop_last);
514 assert!(!config.persistent_workers);
515 }
516
517 // test_create_dataloader removed - function was removed due to lifetime issues
518 // Use DataLoader::builder() directly instead
519
520 #[test]
521 fn test_utils_optimal_config() {
522 let config = utils::optimal_config(1000, "training", Some(DeviceType::Cuda(0)));
523 assert!(config.shuffle);
524 assert!(config.pin_memory);
525 assert!(config.pinning_config.is_some());
526 }
527
528 // test_utils_auto_dataloader removed - function was removed due to lifetime issues
529
530 #[test]
531 fn test_utils_validate_config() {
532 let config = DataLoaderConfig::new().batch_size(100);
533 let warnings = utils::validate_config(&config, 50).expect("utils should succeed");
534 assert!(!warnings.is_empty());
535 assert!(warnings[0].contains("Batch size"));
536 }
537
538 #[test]
539 fn test_utils_performance_recommendations() {
540 let recommendations = utils::performance_recommendations(1000, 8, "training");
541 assert!(!recommendations.is_empty());
542 assert!(recommendations.iter().any(|r| r.contains("batch size")));
543 }
544
545 #[test]
546 fn test_backward_compatibility() {
547 // Test that original API still works
548 use torsh_core::device::DeviceType;
549 use torsh_tensor::Tensor;
550
551 let tensor = Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5], DeviceType::Cpu)
552 .expect("Tensor should succeed");
553 let dataset = TensorDataset::from_tensor(tensor);
554 let dataloader =
555 simple_dataloader(dataset, 2, false).expect("simple dataloader should succeed");
556 assert_eq!(dataloader.len(), 3);
557 }
558
559 #[test]
560 fn test_prefetch_integration() {
561 use torsh_core::device::DeviceType;
562 use torsh_tensor::Tensor;
563
564 let tensor = Tensor::from_data(vec![1.0f32, 2.0, 3.0, 4.0, 5.0], vec![5], DeviceType::Cpu)
565 .expect("Tensor should succeed");
566 let dataset = TensorDataset::from_tensor(tensor);
567 let dataloader = DataLoader::builder(dataset)
568 .batch_size(2)
569 .build()
570 .expect("build should succeed with valid configuration");
571
572 // Test regular iteration instead of prefetch to avoid lifetime issues
573 let mut iter = dataloader.iter();
574 let first_batch = iter
575 .next()
576 .expect("iterator should have a next element")
577 .expect("operation should succeed");
578 assert_eq!(first_batch.len(), 1); // Should have 1 stacked tensor
579
580 // Verify the tensor shape: [batch_size, sample_features]
581 // Original tensor is [5], each sample is [1], batched becomes [2, 1]
582 assert_eq!(first_batch[0].shape().dims(), &[2, 1]);
583 }
584}