In training, we only care about the "infinite stream" of training data. So this sampler produces an infinite stream of indices and all workers cooperate to correctly shuffle the indices and sample different indices. The samplers in each worker effectively produces `indices[worker_i
| 10 | |
| 11 | |
| 12 | class TrainingSampler(Sampler): |
| 13 | """ |
| 14 | In training, we only care about the "infinite stream" of training data. |
| 15 | So this sampler produces an infinite stream of indices and |
| 16 | all workers cooperate to correctly shuffle the indices and sample different indices. |
| 17 | |
| 18 | The samplers in each worker effectively produces `indices[worker_id::num_workers]` |
| 19 | where `indices` is an infinite stream of indices consisting of |
| 20 | `shuffle(range(size)) + shuffle(range(size)) + ...` (if shuffle is True) |
| 21 | or `range(size) + range(size) + ...` (if shuffle is False) |
| 22 | """ |
| 23 | |
| 24 | def __init__(self, size: int, shuffle: bool = True, seed: Optional[int] = None): |
| 25 | """ |
| 26 | Args: |
| 27 | size (int): the total number of data of the underlying dataset to sample from |
| 28 | shuffle (bool): whether to shuffle the indices or not |
| 29 | seed (int): the initial seed of the shuffle. Must be the same |
| 30 | across all workers. If None, will use a random seed shared |
| 31 | among workers (require synchronization among all workers). |
| 32 | """ |
| 33 | self._size = size |
| 34 | assert size > 0 |
| 35 | self._shuffle = shuffle |
| 36 | if seed is None: |
| 37 | seed = comm.shared_random_seed() |
| 38 | self._seed = int(seed) |
| 39 | |
| 40 | self._rank = comm.get_rank() |
| 41 | self._world_size = comm.get_world_size() |
| 42 | |
| 43 | def __iter__(self): |
| 44 | start = self._rank |
| 45 | yield from itertools.islice(self._infinite_indices(), start, None, self._world_size) |
| 46 | |
| 47 | def _infinite_indices(self): |
| 48 | g = torch.Generator() |
| 49 | g.manual_seed(self._seed) |
| 50 | while True: |
| 51 | if self._shuffle: |
| 52 | yield from torch.randperm(self._size, generator=g) |
| 53 | else: |
| 54 | yield from torch.arange(self._size) |
| 55 | |
| 56 | |
| 57 | class RepeatFactorTrainingSampler(Sampler): |
no outgoing calls
no test coverage detected