|
| 1 | +import math |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.distributed as dist |
| 5 | + |
| 6 | + |
| 7 | +class RASampler(torch.utils.data.Sampler): |
| 8 | + """Sampler that restricts data loading to a subset of the dataset for distributed, |
| 9 | + with repeated augmentation. |
| 10 | + It ensures that different each augmented version of a sample will be visible to a |
| 11 | + different process (GPU). |
| 12 | + Heavily based on 'torch.utils.data.DistributedSampler'. |
| 13 | +
|
| 14 | + This is borrowed from the DeiT Repo: |
| 15 | + https://github.com/facebookresearch/deit/blob/main/samplers.py |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True): |
| 19 | + if num_replicas is None: |
| 20 | + if not dist.is_available(): |
| 21 | + raise RuntimeError("Requires distributed package to be available!") |
| 22 | + num_replicas = dist.get_world_size() |
| 23 | + if rank is None: |
| 24 | + if not dist.is_available(): |
| 25 | + raise RuntimeError("Requires distributed package to be available!") |
| 26 | + rank = dist.get_rank() |
| 27 | + self.dataset = dataset |
| 28 | + self.num_replicas = num_replicas |
| 29 | + self.rank = rank |
| 30 | + self.epoch = 0 |
| 31 | + self.num_samples = int(math.ceil(len(self.dataset) * 3.0 / self.num_replicas)) |
| 32 | + self.total_size = self.num_samples * self.num_replicas |
| 33 | + self.num_selected_samples = int(math.floor(len(self.dataset) // 256 * 256 / self.num_replicas)) |
| 34 | + self.shuffle = shuffle |
| 35 | + |
| 36 | + def __iter__(self): |
| 37 | + # Deterministically shuffle based on epoch |
| 38 | + g = torch.Generator() |
| 39 | + g.manual_seed(self.epoch) |
| 40 | + if self.shuffle: |
| 41 | + indices = torch.randperm(len(self.dataset), generator=g).tolist() |
| 42 | + else: |
| 43 | + indices = list(range(len(self.dataset))) |
| 44 | + |
| 45 | + # Add extra samples to make it evenly divisible |
| 46 | + indices = [ele for ele in indices for i in range(3)] |
| 47 | + indices += indices[: (self.total_size - len(indices))] |
| 48 | + assert len(indices) == self.total_size |
| 49 | + |
| 50 | + # Subsample |
| 51 | + indices = indices[self.rank : self.total_size : self.num_replicas] |
| 52 | + assert len(indices) == self.num_samples |
| 53 | + |
| 54 | + return iter(indices[: self.num_selected_samples]) |
| 55 | + |
| 56 | + def __len__(self): |
| 57 | + return self.num_selected_samples |
| 58 | + |
| 59 | + def set_epoch(self, epoch): |
| 60 | + self.epoch = epoch |
0 commit comments