Skip to main content

torsh_data/sampler/
distributed.rs

1//! Distributed sampling for multi-process training
2//!
3//! This module provides samplers for distributed training scenarios where
4//! multiple processes need to sample different subsets of the data to avoid
5//! overlap and ensure balanced workloads.
6
7#[cfg(not(feature = "std"))]
8use alloc::vec::Vec;
9
10// ✅ SciRS2 Policy Compliant - Using scirs2_core for all random operations
11use scirs2_core::random::Random;
12
13use super::core::{Sampler, SamplerIterator};
14
15/// Wrapper that makes any sampler work in a distributed setting
16///
17/// This wrapper takes an underlying sampler and distributes its indices across
18/// multiple replicas (processes). Each replica gets a disjoint subset of the
19/// indices, ensuring no overlap between processes.
20///
21/// # Examples
22///
23/// ```rust,ignore
24/// use torsh_data::sampler::{SequentialSampler, DistributedWrapper, Sampler};
25///
26/// let base_sampler = SequentialSampler::new(10);
27/// // Process 0 of 2 processes
28/// let distributed = DistributedWrapper::new(base_sampler, 2, 0);
29///
30/// let indices: Vec<usize> = distributed.iter().collect();
31/// // Process 0 gets: [0, 2, 4, 6, 8]
32/// // Process 1 would get: [1, 3, 5, 7, 9]
33/// ```
34#[derive(Debug, Clone)]
35pub struct DistributedWrapper<S: Sampler> {
36    sampler: S,
37    num_replicas: usize,
38    rank: usize,
39    shuffle: bool,
40    generator: Option<u64>,
41    epoch: usize,
42}
43
44impl<S: Sampler> DistributedWrapper<S> {
45    /// Create a new distributed wrapper
46    ///
47    /// # Arguments
48    ///
49    /// * `sampler` - The underlying sampler to distribute
50    /// * `num_replicas` - Total number of processes
51    /// * `rank` - Current process rank (0-based)
52    ///
53    /// # Panics
54    ///
55    /// Panics if `num_replicas` is 0 or `rank` >= `num_replicas`
56    pub fn new(sampler: S, num_replicas: usize, rank: usize) -> Self {
57        assert!(num_replicas > 0, "Number of replicas must be positive");
58        assert!(rank < num_replicas, "Rank must be less than num_replicas");
59
60        Self {
61            sampler,
62            num_replicas,
63            rank,
64            shuffle: true,
65            generator: None,
66            epoch: 0,
67        }
68    }
69
70    /// Enable or disable shuffling
71    ///
72    /// When shuffling is enabled, the indices are shuffled before distribution.
73    /// This ensures different ordering across epochs.
74    pub fn with_shuffle(mut self, shuffle: bool) -> Self {
75        self.shuffle = shuffle;
76        self
77    }
78
79    /// Set the random number generator seed
80    ///
81    /// # Arguments
82    ///
83    /// * `seed` - Random seed for reproducible shuffling
84    pub fn with_generator(mut self, seed: u64) -> Self {
85        self.generator = Some(seed);
86        self
87    }
88
89    /// Get the number of replicas
90    pub fn num_replicas(&self) -> usize {
91        self.num_replicas
92    }
93
94    /// Get the current rank
95    pub fn rank(&self) -> usize {
96        self.rank
97    }
98
99    /// Check if shuffling is enabled
100    pub fn shuffle(&self) -> bool {
101        self.shuffle
102    }
103
104    /// Get the generator seed if set
105    pub fn generator(&self) -> Option<u64> {
106        self.generator
107    }
108
109    /// Set the current epoch, so the next shuffle draws a fresh permutation
110    /// derived from `(seed, epoch)` instead of repeating the same order every
111    /// epoch (mirrors `torch.utils.data.distributed.DistributedSampler.set_epoch`).
112    pub fn set_epoch(&mut self, epoch: usize) {
113        self.epoch = epoch;
114    }
115
116    /// Get the current epoch
117    pub fn epoch(&self) -> usize {
118        self.epoch
119    }
120
121    /// Effective seed for the current epoch. At epoch 0 this reproduces the
122    /// exact seed used before per-epoch reseeding existed, so existing callers
123    /// that never call `set_epoch` see no behavior change.
124    fn seed_for_epoch(&self) -> u64 {
125        self.generator.unwrap_or(42).wrapping_add(self.epoch as u64)
126    }
127
128    /// Get a reference to the underlying sampler
129    pub fn sampler(&self) -> &S {
130        &self.sampler
131    }
132
133    /// Get the underlying sampler by value
134    pub fn into_sampler(self) -> S {
135        self.sampler
136    }
137
138    /// Calculate the number of samples this replica will receive
139    fn calculate_num_samples(&self) -> usize {
140        let total_samples = self.sampler.len();
141        // Each replica gets roughly equal number of samples
142        // If total doesn't divide evenly, some replicas get one extra sample
143        let base_samples = total_samples / self.num_replicas;
144        let extra_samples = total_samples % self.num_replicas;
145
146        if self.rank < extra_samples {
147            base_samples + 1
148        } else {
149            base_samples
150        }
151    }
152}
153
154impl<S: Sampler> Sampler for DistributedWrapper<S> {
155    type Iter = SamplerIterator;
156
157    fn iter(&self) -> Self::Iter {
158        // Get all indices from the underlying sampler
159        let mut all_indices: Vec<usize> = self.sampler.iter().collect();
160
161        // Shuffle if enabled
162        if self.shuffle {
163            // ✅ SciRS2 Policy Compliant - Using scirs2_core for random operations
164            let mut rng = Random::seed(self.seed_for_epoch());
165
166            // Fisher-Yates shuffle
167            for i in (1..all_indices.len()).rev() {
168                let j = rng.gen_range(0..=i);
169                all_indices.swap(i, j);
170            }
171        }
172
173        // Distribute indices across replicas
174        let replica_indices: Vec<usize> = all_indices
175            .into_iter()
176            .enumerate()
177            .filter_map(|(i, idx)| {
178                if i % self.num_replicas == self.rank {
179                    Some(idx)
180                } else {
181                    None
182                }
183            })
184            .collect();
185
186        SamplerIterator::new(replica_indices)
187    }
188
189    fn len(&self) -> usize {
190        self.calculate_num_samples()
191    }
192}
193
194/// Distributed sampler for balanced data distribution
195///
196/// Unlike DistributedWrapper which wraps an existing sampler, DistributedSampler
197/// is a standalone sampler designed specifically for distributed training.
198/// It provides more control over the distribution strategy.
199///
200/// # Examples
201///
202/// ```rust,ignore
203/// use torsh_data::sampler::{DistributedSampler, Sampler};
204///
205/// // Process 1 of 4 processes, working with dataset of size 100
206/// let sampler = DistributedSampler::new(100, 4, 1, true).with_generator(42);
207///
208/// let indices: Vec<usize> = sampler.iter().collect();
209/// assert_eq!(indices.len(), 25); // 100 / 4 = 25 samples per process
210/// ```
211#[derive(Debug, Clone)]
212pub struct DistributedSampler {
213    dataset_size: usize,
214    num_replicas: usize,
215    rank: usize,
216    shuffle: bool,
217    generator: Option<u64>,
218    drop_last: bool,
219    epoch: usize,
220}
221
222impl DistributedSampler {
223    /// Create a new distributed sampler
224    ///
225    /// # Arguments
226    ///
227    /// * `dataset_size` - Total size of the dataset
228    /// * `num_replicas` - Total number of processes
229    /// * `rank` - Current process rank (0-based)
230    /// * `shuffle` - Whether to shuffle indices
231    ///
232    /// # Panics
233    ///
234    /// Panics if `dataset_size` is 0, `num_replicas` is 0, or `rank` >= `num_replicas`
235    pub fn new(dataset_size: usize, num_replicas: usize, rank: usize, shuffle: bool) -> Self {
236        assert!(dataset_size > 0, "Dataset size must be positive");
237        assert!(num_replicas > 0, "Number of replicas must be positive");
238        assert!(rank < num_replicas, "Rank must be less than num_replicas");
239
240        Self {
241            dataset_size,
242            num_replicas,
243            rank,
244            shuffle,
245            generator: None,
246            drop_last: false,
247            epoch: 0,
248        }
249    }
250
251    /// Set the random number generator seed
252    pub fn with_generator(mut self, seed: u64) -> Self {
253        self.generator = Some(seed);
254        self
255    }
256
257    /// Set whether to drop the last samples to make dataset evenly divisible
258    pub fn with_drop_last(mut self, drop_last: bool) -> Self {
259        self.drop_last = drop_last;
260        self
261    }
262
263    /// Get the dataset size
264    pub fn dataset_size(&self) -> usize {
265        self.dataset_size
266    }
267
268    /// Get the number of replicas
269    pub fn num_replicas(&self) -> usize {
270        self.num_replicas
271    }
272
273    /// Get the current rank
274    pub fn rank(&self) -> usize {
275        self.rank
276    }
277
278    /// Check if shuffling is enabled
279    pub fn shuffle(&self) -> bool {
280        self.shuffle
281    }
282
283    /// Check if dropping last samples
284    pub fn drop_last(&self) -> bool {
285        self.drop_last
286    }
287
288    /// Get the generator seed if set
289    pub fn generator(&self) -> Option<u64> {
290        self.generator
291    }
292
293    /// Set the current epoch, so the next shuffle draws a fresh permutation
294    /// derived from `(seed, epoch)` instead of repeating the same order (and
295    /// dropping/padding the same samples) every epoch (mirrors
296    /// `torch.utils.data.distributed.DistributedSampler.set_epoch`).
297    pub fn set_epoch(&mut self, epoch: usize) {
298        self.epoch = epoch;
299    }
300
301    /// Get the current epoch
302    pub fn epoch(&self) -> usize {
303        self.epoch
304    }
305
306    /// Effective seed for the current epoch. At epoch 0 this reproduces the
307    /// exact seed used before per-epoch reseeding existed, so existing callers
308    /// that never call `set_epoch` see no behavior change.
309    fn seed_for_epoch(&self) -> u64 {
310        self.generator.unwrap_or(42).wrapping_add(self.epoch as u64)
311    }
312
313    /// Calculate the effective dataset size after potential padding
314    fn effective_dataset_size(&self) -> usize {
315        if self.drop_last {
316            // Drop samples to make evenly divisible
317            (self.dataset_size / self.num_replicas) * self.num_replicas
318        } else {
319            // Pad with duplicates to make evenly divisible
320            let samples_per_replica =
321                (self.dataset_size + self.num_replicas - 1) / self.num_replicas;
322            samples_per_replica * self.num_replicas
323        }
324    }
325
326    /// Calculate the number of samples this replica will receive
327    fn calculate_num_samples(&self) -> usize {
328        if self.drop_last {
329            self.dataset_size / self.num_replicas
330        } else {
331            (self.dataset_size + self.num_replicas - 1) / self.num_replicas
332        }
333    }
334}
335
336impl Sampler for DistributedSampler {
337    type Iter = SamplerIterator;
338
339    fn iter(&self) -> Self::Iter {
340        let effective_size = self.effective_dataset_size();
341        let samples_per_replica = self.calculate_num_samples();
342
343        // Build the FULL index list first and shuffle it (if enabled) BEFORE
344        // truncating/padding to effective_size. Shuffling after truncation would
345        // permanently exclude the same `dataset_size % num_replicas` tail
346        // indices from every rank on every epoch, since those indices would
347        // never even enter the pool that gets shuffled. Building the full list
348        // first (matching torch.utils.data.distributed.DistributedSampler)
349        // means every index has a chance to survive truncation, and which
350        // indices get dropped/padded rotates with the epoch-derived seed.
351        let mut base: Vec<usize> = (0..self.dataset_size).collect();
352
353        if self.shuffle {
354            // ✅ SciRS2 Policy Compliant - Using scirs2_core for random operations
355            let mut rng = Random::seed(self.seed_for_epoch());
356
357            // Fisher-Yates shuffle
358            for i in (1..base.len()).rev() {
359                let j = rng.gen_range(0..=i);
360                base.swap(i, j);
361            }
362        }
363
364        let indices: Vec<usize> = if self.drop_last {
365            base.truncate(effective_size);
366            base
367        } else {
368            // Pad by wrapping around the (possibly shuffled) base list, so with
369            // shuffle=false this is exactly `i % dataset_size` as before.
370            (0..effective_size)
371                .map(|i| base[i % self.dataset_size])
372                .collect()
373        };
374
375        // Extract this replica's portion (contiguous block per rank).
376        let start_idx = self.rank * samples_per_replica;
377        let end_idx = start_idx + samples_per_replica;
378        let replica_indices = indices[start_idx..end_idx.min(indices.len())].to_vec();
379
380        SamplerIterator::new(replica_indices)
381    }
382
383    fn len(&self) -> usize {
384        self.calculate_num_samples()
385    }
386}
387
388/// Create a distributed wrapper for any sampler
389///
390/// Convenience function for creating a distributed wrapper.
391///
392/// # Arguments
393///
394/// * `sampler` - The underlying sampler
395/// * `num_replicas` - Total number of processes
396/// * `rank` - Current process rank
397pub fn distributed<S: Sampler>(
398    sampler: S,
399    num_replicas: usize,
400    rank: usize,
401) -> DistributedWrapper<S> {
402    DistributedWrapper::new(sampler, num_replicas, rank)
403}
404
405/// Create a distributed sampler
406///
407/// Convenience function for creating a distributed sampler.
408///
409/// # Arguments
410///
411/// * `dataset_size` - Total size of the dataset
412/// * `num_replicas` - Total number of processes
413/// * `rank` - Current process rank
414/// * `shuffle` - Whether to shuffle indices
415pub fn distributed_sampler(
416    dataset_size: usize,
417    num_replicas: usize,
418    rank: usize,
419    shuffle: bool,
420) -> DistributedSampler {
421    DistributedSampler::new(dataset_size, num_replicas, rank, shuffle)
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use crate::sampler::basic::SequentialSampler;
428
429    #[test]
430    fn test_distributed_wrapper_basic() {
431        let base_sampler = SequentialSampler::new(10);
432        let distributed = DistributedWrapper::new(base_sampler, 2, 0).with_shuffle(false);
433
434        assert_eq!(distributed.num_replicas(), 2);
435        assert_eq!(distributed.rank(), 0);
436        assert!(!distributed.shuffle());
437        assert_eq!(distributed.len(), 5); // 10 / 2 = 5 samples per process
438
439        let indices: Vec<usize> = distributed.iter().collect();
440        assert_eq!(indices, vec![0, 2, 4, 6, 8]); // Even indices for rank 0
441    }
442
443    #[test]
444    fn test_distributed_wrapper_rank_1() {
445        let base_sampler = SequentialSampler::new(10);
446        let distributed = DistributedWrapper::new(base_sampler, 2, 1).with_shuffle(false);
447
448        assert_eq!(distributed.rank(), 1);
449        assert_eq!(distributed.len(), 5);
450
451        let indices: Vec<usize> = distributed.iter().collect();
452        assert_eq!(indices, vec![1, 3, 5, 7, 9]); // Odd indices for rank 1
453    }
454
455    #[test]
456    fn test_distributed_wrapper_uneven_split() {
457        let base_sampler = SequentialSampler::new(7); // 7 doesn't divide evenly by 3
458
459        let dist0 = DistributedWrapper::new(base_sampler.clone(), 3, 0).with_shuffle(false);
460        let dist1 = DistributedWrapper::new(base_sampler.clone(), 3, 1).with_shuffle(false);
461        let dist2 = DistributedWrapper::new(base_sampler, 3, 2).with_shuffle(false);
462
463        // First rank gets extra sample: 7 / 3 = 2 remainder 1
464        assert_eq!(dist0.len(), 3); // 2 + 1 = 3
465        assert_eq!(dist1.len(), 2); // 2
466        assert_eq!(dist2.len(), 2); // 2
467
468        let indices0: Vec<usize> = dist0.iter().collect();
469        let indices1: Vec<usize> = dist1.iter().collect();
470        let indices2: Vec<usize> = dist2.iter().collect();
471
472        assert_eq!(indices0, vec![0, 3, 6]);
473        assert_eq!(indices1, vec![1, 4]);
474        assert_eq!(indices2, vec![2, 5]);
475
476        // Verify all indices are covered
477        let mut all_indices = indices0;
478        all_indices.extend(indices1);
479        all_indices.extend(indices2);
480        all_indices.sort();
481        assert_eq!(all_indices, vec![0, 1, 2, 3, 4, 5, 6]);
482    }
483
484    #[test]
485    fn test_distributed_wrapper_with_shuffle() {
486        let base_sampler = SequentialSampler::new(10);
487        let distributed = DistributedWrapper::new(base_sampler, 2, 0)
488            .with_shuffle(true)
489            .with_generator(42);
490
491        let indices: Vec<usize> = distributed.iter().collect();
492        assert_eq!(indices.len(), 5);
493
494        // Verify indices are from original dataset
495        for &idx in &indices {
496            assert!(idx < 10);
497        }
498
499        // Should be deterministic with same seed
500        let distributed2 = DistributedWrapper::new(SequentialSampler::new(10), 2, 0)
501            .with_shuffle(true)
502            .with_generator(42);
503        let indices2: Vec<usize> = distributed2.iter().collect();
504        assert_eq!(indices, indices2);
505    }
506
507    #[test]
508    #[should_panic(expected = "Number of replicas must be positive")]
509    fn test_distributed_wrapper_zero_replicas() {
510        let base_sampler = SequentialSampler::new(10);
511        DistributedWrapper::new(base_sampler, 0, 0);
512    }
513
514    #[test]
515    #[should_panic(expected = "Rank must be less than num_replicas")]
516    fn test_distributed_wrapper_invalid_rank() {
517        let base_sampler = SequentialSampler::new(10);
518        DistributedWrapper::new(base_sampler, 2, 2);
519    }
520
521    #[test]
522    fn test_distributed_sampler_basic() {
523        let sampler = DistributedSampler::new(12, 3, 1, false);
524
525        assert_eq!(sampler.dataset_size(), 12);
526        assert_eq!(sampler.num_replicas(), 3);
527        assert_eq!(sampler.rank(), 1);
528        assert!(!sampler.shuffle());
529        assert!(!sampler.drop_last());
530        assert_eq!(sampler.len(), 4); // 12 / 3 = 4
531
532        let indices: Vec<usize> = sampler.iter().collect();
533        assert_eq!(indices, vec![4, 5, 6, 7]); // Rank 1 gets indices 4-7
534    }
535
536    #[test]
537    fn test_distributed_sampler_with_padding() {
538        let sampler = DistributedSampler::new(10, 3, 0, false); // 10 doesn't divide by 3
539
540        // With padding, each replica gets 4 samples (total 12, padded from 10)
541        assert_eq!(sampler.len(), 4);
542
543        let indices: Vec<usize> = sampler.iter().collect();
544        assert_eq!(indices.len(), 4);
545
546        // All indices should be valid (0-9, with possible duplicates due to padding)
547        for &idx in &indices {
548            assert!(idx < 10);
549        }
550    }
551
552    #[test]
553    fn test_distributed_sampler_drop_last() {
554        let sampler = DistributedSampler::new(10, 3, 0, false).with_drop_last(true);
555
556        // With drop_last, 10 / 3 = 3 samples per replica (drops 1 sample)
557        assert_eq!(sampler.len(), 3);
558
559        let indices: Vec<usize> = sampler.iter().collect();
560        assert_eq!(indices, vec![0, 1, 2]);
561    }
562
563    #[test]
564    fn test_distributed_sampler_shuffle() {
565        let sampler = DistributedSampler::new(12, 3, 0, true).with_generator(42);
566
567        let indices: Vec<usize> = sampler.iter().collect();
568        assert_eq!(indices.len(), 4);
569
570        // Should be deterministic with same seed
571        let sampler2 = DistributedSampler::new(12, 3, 0, true).with_generator(42);
572        let indices2: Vec<usize> = sampler2.iter().collect();
573        assert_eq!(indices, indices2);
574    }
575
576    #[test]
577    fn test_convenience_functions() {
578        let base_sampler = SequentialSampler::new(8);
579        let dist_wrapper = distributed(base_sampler, 2, 0);
580        assert_eq!(dist_wrapper.len(), 4);
581
582        let dist_sampler = distributed_sampler(8, 2, 1, false);
583        assert_eq!(dist_sampler.len(), 4);
584    }
585
586    #[test]
587    fn test_distributed_sampler_edge_cases() {
588        // Single replica (should get all data)
589        let sampler = DistributedSampler::new(10, 1, 0, false);
590        assert_eq!(sampler.len(), 10);
591
592        let indices: Vec<usize> = sampler.iter().collect();
593        assert_eq!(indices, (0..10).collect::<Vec<_>>());
594
595        // More replicas than data points
596        let sampler = DistributedSampler::new(2, 5, 3, false);
597        assert_eq!(sampler.len(), 1);
598
599        let indices: Vec<usize> = sampler.iter().collect();
600        assert_eq!(indices.len(), 1);
601        assert!(indices[0] < 2);
602    }
603
604    #[test]
605    fn test_into_sampler() {
606        let base_sampler = SequentialSampler::new(5);
607        let distributed = DistributedWrapper::new(base_sampler, 2, 0);
608
609        let recovered = distributed.into_sampler();
610        assert_eq!(recovered.len(), 5);
611    }
612}