MCPcopy Create free account
hub / github.com/NVIDIA/semantic-segmentation / DistributedSampler

Class DistributedSampler

datasets/sampler.py:43–110  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

41from torch.utils.data import Sampler
42
43class DistributedSampler(Sampler):
44 """Sampler that restricts data loading to a subset of the dataset.
45
46 It is especially useful in conjunction with
47 :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
48 process can pass a DistributedSampler instance as a DataLoader sampler,
49 and load a subset of the original dataset that is exclusive to it.
50
51 .. note::
52 Dataset is assumed to be of constant size.
53
54 Arguments:
55 dataset: Dataset used for sampling.
56 num_replicas (optional): Number of processes participating in
57 distributed training.
58 rank (optional): Rank of the current process within num_replicas.
59 """
60
61 def __init__(self, dataset, pad=False, consecutive_sample=False, permutation=False, num_replicas=None, rank=None):
62 if num_replicas is None:
63 num_replicas = get_world_size()
64 if rank is None:
65 rank = get_rank()
66 self.dataset = dataset
67 self.num_replicas = num_replicas
68 self.rank = rank
69 self.epoch = 0
70 self.consecutive_sample = consecutive_sample
71 self.permutation = permutation
72 if pad:
73 self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas))
74 else:
75 self.num_samples = int(math.floor(len(self.dataset) * 1.0 / self.num_replicas))
76 self.total_size = self.num_samples * self.num_replicas
77
78 def __iter__(self):
79 # deterministically shuffle based on epoch
80 g = torch.Generator()
81 g.manual_seed(self.epoch)
82
83 if self.permutation:
84 indices = list(torch.randperm(len(self.dataset), generator=g))
85 else:
86 indices = list([x for x in range(len(self.dataset))])
87
88 # add extra samples to make it evenly divisible
89 if self.total_size > len(indices):
90 indices += indices[:(self.total_size - len(indices))]
91
92 # subsample
93 if self.consecutive_sample:
94 offset = self.num_samples * self.rank
95 indices = indices[offset:offset + self.num_samples]
96 else:
97 indices = indices[self.rank:self.total_size:self.num_replicas]
98 assert len(indices) == self.num_samples
99
100 return iter(indices)

Callers 1

setup_loadersFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected