distributed.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import math
  2. from typing import TypeVar, Optional, Iterator
  3. import torch
  4. from . import Sampler, Dataset
  5. import torch.distributed as dist
  6. __all__ = ["DistributedSampler", ]
  7. T_co = TypeVar('T_co', covariant=True)
  8. class DistributedSampler(Sampler[T_co]):
  9. r"""Sampler that restricts data loading to a subset of the dataset.
  10. It is especially useful in conjunction with
  11. :class:`torch.nn.parallel.DistributedDataParallel`. In such a case, each
  12. process can pass a :class:`~torch.utils.data.DistributedSampler` instance as a
  13. :class:`~torch.utils.data.DataLoader` sampler, and load a subset of the
  14. original dataset that is exclusive to it.
  15. .. note::
  16. Dataset is assumed to be of constant size and that any instance of it always
  17. returns the same elements in the same order.
  18. Args:
  19. dataset: Dataset used for sampling.
  20. num_replicas (int, optional): Number of processes participating in
  21. distributed training. By default, :attr:`world_size` is retrieved from the
  22. current distributed group.
  23. rank (int, optional): Rank of the current process within :attr:`num_replicas`.
  24. By default, :attr:`rank` is retrieved from the current distributed
  25. group.
  26. shuffle (bool, optional): If ``True`` (default), sampler will shuffle the
  27. indices.
  28. seed (int, optional): random seed used to shuffle the sampler if
  29. :attr:`shuffle=True`. This number should be identical across all
  30. processes in the distributed group. Default: ``0``.
  31. drop_last (bool, optional): if ``True``, then the sampler will drop the
  32. tail of the data to make it evenly divisible across the number of
  33. replicas. If ``False``, the sampler will add extra indices to make
  34. the data evenly divisible across the replicas. Default: ``False``.
  35. .. warning::
  36. In distributed mode, calling the :meth:`set_epoch` method at
  37. the beginning of each epoch **before** creating the :class:`DataLoader` iterator
  38. is necessary to make shuffling work properly across multiple epochs. Otherwise,
  39. the same ordering will be always used.
  40. Example::
  41. >>> # xdoctest: +SKIP
  42. >>> sampler = DistributedSampler(dataset) if is_distributed else None
  43. >>> loader = DataLoader(dataset, shuffle=(sampler is None),
  44. ... sampler=sampler)
  45. >>> for epoch in range(start_epoch, n_epochs):
  46. ... if is_distributed:
  47. ... sampler.set_epoch(epoch)
  48. ... train(loader)
  49. """
  50. def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None,
  51. rank: Optional[int] = None, shuffle: bool = True,
  52. seed: int = 0, drop_last: bool = False) -> None:
  53. if num_replicas is None:
  54. if not dist.is_available():
  55. raise RuntimeError("Requires distributed package to be available")
  56. num_replicas = dist.get_world_size()
  57. if rank is None:
  58. if not dist.is_available():
  59. raise RuntimeError("Requires distributed package to be available")
  60. rank = dist.get_rank()
  61. if rank >= num_replicas or rank < 0:
  62. raise ValueError(
  63. "Invalid rank {}, rank should be in the interval"
  64. " [0, {}]".format(rank, num_replicas - 1))
  65. self.dataset = dataset
  66. self.num_replicas = num_replicas
  67. self.rank = rank
  68. self.epoch = 0
  69. self.drop_last = drop_last
  70. # If the dataset length is evenly divisible by # of replicas, then there
  71. # is no need to drop any data, since the dataset will be split equally.
  72. if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type]
  73. # Split to nearest available length that is evenly divisible.
  74. # This is to ensure each rank receives the same amount of data when
  75. # using this Sampler.
  76. self.num_samples = math.ceil(
  77. (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore[arg-type]
  78. )
  79. else:
  80. self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore[arg-type]
  81. self.total_size = self.num_samples * self.num_replicas
  82. self.shuffle = shuffle
  83. self.seed = seed
  84. def __iter__(self) -> Iterator[T_co]:
  85. if self.shuffle:
  86. # deterministically shuffle based on epoch and seed
  87. g = torch.Generator()
  88. g.manual_seed(self.seed + self.epoch)
  89. indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type]
  90. else:
  91. indices = list(range(len(self.dataset))) # type: ignore[arg-type]
  92. if not self.drop_last:
  93. # add extra samples to make it evenly divisible
  94. padding_size = self.total_size - len(indices)
  95. if padding_size <= len(indices):
  96. indices += indices[:padding_size]
  97. else:
  98. indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]
  99. else:
  100. # remove tail of data to make it evenly divisible.
  101. indices = indices[:self.total_size]
  102. assert len(indices) == self.total_size
  103. # subsample
  104. indices = indices[self.rank:self.total_size:self.num_replicas]
  105. assert len(indices) == self.num_samples
  106. return iter(indices)
  107. def __len__(self) -> int:
  108. return self.num_samples
  109. def set_epoch(self, epoch: int) -> None:
  110. r"""
  111. Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas
  112. use a different random ordering for each epoch. Otherwise, the next iteration of this
  113. sampler will yield the same ordering.
  114. Args:
  115. epoch (int): Epoch number.
  116. """
  117. self.epoch = epoch