distributed_sampler.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import math
  2. import torch
  3. from torch.utils.data import Sampler
  4. import torch.distributed as dist
  5. class OrderedDistributedSampler(Sampler):
  6. """Sampler that restricts data loading to a subset of the dataset.
  7. It is especially useful in conjunction with
  8. :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
  9. process can pass a DistributedSampler instance as a DataLoader sampler,
  10. and load a subset of the original dataset that is exclusive to it.
  11. .. note::
  12. Dataset is assumed to be of constant size.
  13. Arguments:
  14. dataset: Dataset used for sampling.
  15. num_replicas (optional): Number of processes participating in
  16. distributed training.
  17. rank (optional): Rank of the current process within num_replicas.
  18. """
  19. def __init__(self, dataset, num_replicas=None, rank=None):
  20. if num_replicas is None:
  21. if not dist.is_available():
  22. raise RuntimeError("Requires distributed package to be available")
  23. num_replicas = dist.get_world_size()
  24. if rank is None:
  25. if not dist.is_available():
  26. raise RuntimeError("Requires distributed package to be available")
  27. rank = dist.get_rank()
  28. self.dataset = dataset
  29. self.num_replicas = num_replicas
  30. self.rank = rank
  31. self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas))
  32. self.total_size = self.num_samples * self.num_replicas
  33. def __iter__(self):
  34. indices = list(range(len(self.dataset)))
  35. # add extra samples to make it evenly divisible
  36. indices += indices[:(self.total_size - len(indices))]
  37. assert len(indices) == self.total_size
  38. # subsample
  39. indices = indices[self.rank:self.total_size:self.num_replicas]
  40. assert len(indices) == self.num_samples
  41. return iter(indices)
  42. def __len__(self):
  43. return self.num_samples
  44. class RepeatAugSampler(Sampler):
  45. """Sampler that restricts data loading to a subset of the dataset for distributed,
  46. with repeated augmentation.
  47. It ensures that different each augmented version of a sample will be visible to a
  48. different process (GPU). Heavily based on torch.utils.data.DistributedSampler
  49. This sampler was taken from https://github.com/facebookresearch/deit/blob/0c4b8f60/samplers.py
  50. Used in
  51. Copyright (c) 2015-present, Facebook, Inc.
  52. """
  53. def __init__(
  54. self,
  55. dataset,
  56. num_replicas=None,
  57. rank=None,
  58. shuffle=True,
  59. num_repeats=3,
  60. selected_round=256,
  61. selected_ratio=0,
  62. ):
  63. if num_replicas is None:
  64. if not dist.is_available():
  65. raise RuntimeError("Requires distributed package to be available")
  66. num_replicas = dist.get_world_size()
  67. if rank is None:
  68. if not dist.is_available():
  69. raise RuntimeError("Requires distributed package to be available")
  70. rank = dist.get_rank()
  71. self.dataset = dataset
  72. self.num_replicas = num_replicas
  73. self.rank = rank
  74. self.shuffle = shuffle
  75. self.num_repeats = num_repeats
  76. self.epoch = 0
  77. self.num_samples = int(math.ceil(len(self.dataset) * num_repeats / self.num_replicas))
  78. self.total_size = self.num_samples * self.num_replicas
  79. # Determine the number of samples to select per epoch for each rank.
  80. # num_selected logic defaults to be the same as original RASampler impl, but this one can be tweaked
  81. # via selected_ratio and selected_round args.
  82. selected_ratio = selected_ratio or num_replicas # ratio to reduce selected samples by, num_replicas if 0
  83. if selected_round:
  84. self.num_selected_samples = int(math.floor(
  85. len(self.dataset) // selected_round * selected_round / selected_ratio))
  86. else:
  87. self.num_selected_samples = int(math.ceil(len(self.dataset) / selected_ratio))
  88. def __iter__(self):
  89. # deterministically shuffle based on epoch
  90. g = torch.Generator()
  91. g.manual_seed(self.epoch)
  92. if self.shuffle:
  93. indices = torch.randperm(len(self.dataset), generator=g)
  94. else:
  95. indices = torch.arange(start=0, end=len(self.dataset))
  96. # produce repeats e.g. [0, 0, 0, 1, 1, 1, 2, 2, 2....]
  97. if isinstance(self.num_repeats, float) and not self.num_repeats.is_integer():
  98. # resample for repeats w/ non-integer ratio
  99. repeat_size = math.ceil(self.num_repeats * len(self.dataset))
  100. indices = indices[torch.tensor([int(i // self.num_repeats) for i in range(repeat_size)])]
  101. else:
  102. indices = torch.repeat_interleave(indices, repeats=int(self.num_repeats), dim=0)
  103. indices = indices.tolist() # leaving as tensor thrashes dataloader memory
  104. # add extra samples to make it evenly divisible
  105. padding_size = self.total_size - len(indices)
  106. if padding_size > 0:
  107. indices += indices[:padding_size]
  108. assert len(indices) == self.total_size
  109. # subsample per rank
  110. indices = indices[self.rank:self.total_size:self.num_replicas]
  111. assert len(indices) == self.num_samples
  112. # return up to num selected samples
  113. return iter(indices[:self.num_selected_samples])
  114. def __len__(self):
  115. return self.num_selected_samples
  116. def set_epoch(self, epoch):
  117. self.epoch = epoch