Sampler that restricts data loading to a subset of the dataset. It is especially useful in conjunction with :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each process can pass a DistributedSampler instance as a DataLoader sampler, and load a subset of the origina
| 5 | |
| 6 | |
| 7 | class DistributedSampler(Sampler): |
| 8 | """Sampler that restricts data loading to a subset of the dataset. |
| 9 | |
| 10 | It is especially useful in conjunction with |
| 11 | :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each |
| 12 | process can pass a DistributedSampler instance as a DataLoader sampler, |
| 13 | and load a subset of the original dataset that is exclusive to it. |
| 14 | |
| 15 | .. note:: |
| 16 | Dataset is assumed to be of constant size. |
| 17 | |
| 18 | Arguments: |
| 19 | dataset: Dataset used for sampling. |
| 20 | num_replicas (optional): Number of processes participating in |
| 21 | distributed training. |
| 22 | rank (optional): Rank of the current process within num_replicas. |
| 23 | """ |
| 24 | |
| 25 | def __init__(self, dataset, num_replicas=None, rank=None): |
| 26 | if num_replicas is None: |
| 27 | num_replicas = get_world_size() |
| 28 | if rank is None: |
| 29 | rank = get_rank() |
| 30 | self.dataset = dataset |
| 31 | self.num_replicas = num_replicas |
| 32 | self.rank = rank |
| 33 | self.epoch = 0 |
| 34 | self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas)) |
| 35 | self.total_size = self.num_samples * self.num_replicas |
| 36 | |
| 37 | def __iter__(self): |
| 38 | # deterministically shuffle based on epoch |
| 39 | g = torch.Generator() |
| 40 | g.manual_seed(self.epoch) |
| 41 | indices = list(torch.randperm(len(self.dataset), generator=g)) |
| 42 | |
| 43 | # add extra samples to make it evenly divisible |
| 44 | indices += indices[:(self.total_size - len(indices))] |
| 45 | assert len(indices) == self.total_size |
| 46 | |
| 47 | # subsample |
| 48 | offset = self.num_samples * self.rank |
| 49 | indices = indices[offset:offset + self.num_samples] |
| 50 | assert len(indices) == self.num_samples |
| 51 | |
| 52 | return iter(indices) |
| 53 | |
| 54 | def __len__(self): |
| 55 | return self.num_samples |
| 56 | |
| 57 | def set_epoch(self, epoch): |
| 58 | self.epoch = epoch |
nothing calls this directly
no outgoing calls
no test coverage detected