MCPcopy Create free account
hub / github.com/AIS-SNU/Smart-Infinity / RandomSampler

Class RandomSampler

DeepSpeedExample/megatron/data/samplers.py:22–75  ·  view source on GitHub ↗

Based off of pytorch RandomSampler and DistributedSampler. Essentially a RandomSampler, but this class lets the user set an epoch like DistributedSampler Samples elements randomly. If without replacement, then sample from a shuffled dataset. If with replacement, then user can specify

Source from the content-addressed store, hash-verified

20
21
22class RandomSampler(data.sampler.Sampler):
23 """Based off of pytorch RandomSampler and DistributedSampler. Essentially
24 a RandomSampler, but this class lets the user set an epoch like
25 DistributedSampler Samples elements randomly. If without replacement, then
26 sample from a shuffled dataset. If with replacement, then user can
27 specify ``num_samples`` to draw.
28 Arguments:
29 data_source (Dataset): dataset to sample from
30 num_samples (int): number of samples to draw, default=len(dataset)
31 replacement (bool): samples are drawn with replacement if ``True``,
32 default=False
33 """
34
35 def __init__(self, data_source, replacement=False, num_samples=None):
36 self.data_source = data_source
37 self.replacement = replacement
38 self._num_samples = num_samples
39 self.epoch = -1
40
41 if self._num_samples is not None and replacement is False:
42 raise ValueError("With replacement=False, num_samples should not "
43 "be specified, since a random permute will be "
44 "performed.")
45
46 if not isinstance(self.num_samples, int) or self.num_samples <= 0:
47 raise ValueError("num_samples should be a positive integer "
48 "value, but got num_samples={}".format(
49 self.num_samples))
50 if not isinstance(self.replacement, bool):
51 raise ValueError("replacement should be a boolean value, but got "
52 "replacement={}".format(self.replacement))
53
54 @property
55 def num_samples(self):
56 # dataset size might change at runtime
57 if self._num_samples is None:
58 return len(self.data_source)
59 return self._num_samples
60
61 def __iter__(self):
62 n = len(self.data_source)
63 g = torch.Generator()
64 if self.epoch >= 0:
65 g.manual_seed(self.epoch)
66 if self.replacement:
67 return iter(torch.randint(high=n, size=(self.num_samples,),
68 dtype=torch.int64, generator=g).tolist())
69 return iter(torch.randperm(n, generator=g).tolist())
70
71 def __len__(self):
72 return self.num_samples
73
74 def set_epoch(self, epoch):
75 self.epoch = epoch
76
77
78class DistributedBatchSampler(data.sampler.BatchSampler):

Callers 1

__init__Method · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected