MCPcopy Create free account
hub / github.com/RingBDStack/GDAP / make_dynamic_sampler

Method make_dynamic_sampler

seq2seq/utils.py:172–195  ·  view source on GitHub ↗
(self, max_tokens_per_batch=1024, **kwargs)

Source from the content-addressed store, hash-verified

170 return SortishSampler(self.src_lens, batch_size, shuffle=shuffle)
171
172 def make_dynamic_sampler(self, max_tokens_per_batch=1024, **kwargs):
173 assert FAIRSEQ_AVAILABLE, "Dynamic batch size requires `pip install fairseq`"
174 assert not self.used_char_len, "You must call python make_len_file.py before calling make_dynamic_sampler"
175 sorted_indices = list(self.make_sortish_sampler(1024, shuffle=False))
176
177 def num_tokens_in_example(i):
178 return min(self.src_lens[i], self.max_target_length)
179
180 # call fairseq cython function
181 batch_sampler: List[List[int]] = batch_by_size(
182 sorted_indices,
183 num_tokens_fn=num_tokens_in_example,
184 max_tokens=max_tokens_per_batch,
185 required_batch_size_multiple=64,
186 )
187 shuffled_batches = [batch_sampler[i] for i in np.random.permutation(range(len(batch_sampler)))]
188 # move the largest batch to the front to OOM quickly (uses an approximation for padding)
189 approximate_toks_per_batch = [max(self.src_lens[i] for i in batch) * len(batch) for batch in shuffled_batches]
190 largest_batch_idx = np.argmax(approximate_toks_per_batch)
191 shuffled_batches[0], shuffled_batches[largest_batch_idx] = (
192 shuffled_batches[largest_batch_idx],
193 shuffled_batches[0],
194 )
195 return shuffled_batches
196
197 def __getitem__(self, item):
198 raise NotImplementedError("You must implement this")

Callers

nothing calls this directly

Calls 1

make_sortish_samplerMethod · 0.95

Tested by

no test coverage detected