Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

data.py 17 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. import contextlib
  8. import itertools
  9. import glob
  10. import math
  11. import numbers
  12. import numpy as np
  13. import os
  14. import torch
  15. from torch.autograd import Variable
  16. import torch.utils.data
  17. from fairseq.dictionary import Dictionary
  18. from fairseq.indexed_dataset import IndexedDataset, IndexedInMemoryDataset, IndexedRawTextDataset
  19. def has_binary_files(data_dir, splits):
  20. for split in splits:
  21. if len(glob.glob(os.path.join(data_dir, '{}.*-*.*.bin'.format(split)))) < 2:
  22. return False
  23. return True
  24. def infer_language_pair(path, splits):
  25. """Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx"""
  26. src, dst = None, None
  27. for filename in os.listdir(path):
  28. parts = filename.split('.')
  29. for split in splits:
  30. if parts[0] == split and parts[-1] == 'idx':
  31. src, dst = parts[1].split('-')
  32. break
  33. return src, dst
  34. def load_dictionaries(path, src_lang, dst_lang):
  35. """Load dictionaries for a given language pair."""
  36. src_dict = Dictionary.load(os.path.join(path, 'dict.{}.txt'.format(src_lang)))
  37. dst_dict = Dictionary.load(os.path.join(path, 'dict.{}.txt'.format(dst_lang)))
  38. return src_dict, dst_dict
  39. def load_dataset(path, load_splits, src=None, dst=None):
  40. """Loads specified data splits (e.g., test, train or valid) from the
  41. specified folder and check that files exist."""
  42. if src is None and dst is None:
  43. # find language pair automatically
  44. src, dst = infer_language_pair(path, load_splits)
  45. assert src is not None and dst is not None, 'Source and target languages should be provided'
  46. src_dict, dst_dict = load_dictionaries(path, src, dst)
  47. dataset = LanguageDatasets(src, dst, src_dict, dst_dict)
  48. # Load dataset from binary files
  49. def all_splits_exist(src, dst, lang):
  50. for split in load_splits:
  51. filename = '{0}.{1}-{2}.{3}.idx'.format(split, src, dst, lang)
  52. if not os.path.exists(os.path.join(path, filename)):
  53. return False
  54. return True
  55. # infer langcode
  56. if all_splits_exist(src, dst, src):
  57. langcode = '{}-{}'.format(src, dst)
  58. elif all_splits_exist(dst, src, src):
  59. langcode = '{}-{}'.format(dst, src)
  60. else:
  61. raise Exception('Dataset cannot be loaded from path: ' + path)
  62. def fmt_path(fmt, *args):
  63. return os.path.join(path, fmt.format(*args))
  64. for split in load_splits:
  65. for k in itertools.count():
  66. prefix = "{}{}".format(split, k if k > 0 else '')
  67. src_path = fmt_path('{}.{}.{}', prefix, langcode, src)
  68. dst_path = fmt_path('{}.{}.{}', prefix, langcode, dst)
  69. if not IndexedInMemoryDataset.exists(src_path):
  70. break
  71. target_dataset = None
  72. if IndexedInMemoryDataset.exists(dst_path):
  73. target_dataset = IndexedInMemoryDataset(dst_path)
  74. dataset.splits[prefix] = LanguagePairDataset(
  75. IndexedInMemoryDataset(src_path),
  76. target_dataset,
  77. pad_idx=dataset.src_dict.pad(),
  78. eos_idx=dataset.src_dict.eos(),
  79. )
  80. return dataset
  81. def load_raw_text_dataset(path, load_splits, src=None, dst=None):
  82. """Loads specified data splits (e.g., test, train or valid) from raw text
  83. files in the specified folder."""
  84. if src is None and dst is None:
  85. # find language pair automatically
  86. src, dst = infer_language_pair(path, load_splits)
  87. assert src is not None and dst is not None, 'Source and target languages should be provided'
  88. src_dict, dst_dict = load_dictionaries(path, src, dst)
  89. dataset = LanguageDatasets(src, dst, src_dict, dst_dict)
  90. # Load dataset from raw text files
  91. for split in load_splits:
  92. src_path = os.path.join(path, '{}.{}'.format(split, src))
  93. dst_path = os.path.join(path, '{}.{}'.format(split, dst))
  94. dataset.splits[split] = LanguagePairDataset(
  95. IndexedRawTextDataset(src_path, src_dict),
  96. IndexedRawTextDataset(dst_path, dst_dict),
  97. pad_idx=dataset.src_dict.pad(),
  98. eos_idx=dataset.src_dict.eos(),
  99. )
  100. return dataset
  101. class LanguageDatasets(object):
  102. def __init__(self, src, dst, src_dict, dst_dict):
  103. self.src = src
  104. self.dst = dst
  105. self.src_dict = src_dict
  106. self.dst_dict = dst_dict
  107. self.splits = {}
  108. assert self.src_dict.pad() == self.dst_dict.pad()
  109. assert self.src_dict.eos() == self.dst_dict.eos()
  110. assert self.src_dict.unk() == self.dst_dict.unk()
  111. def train_dataloader_generator(
  112. self, split, max_tokens=None, max_sentences=None,
  113. max_positions=(1024, 1024), seed=None, sample_without_replacement=0,
  114. shard_id=0, num_shards=1
  115. ):
  116. dataset = self.splits[split]
  117. with numpy_seed(seed):
  118. batches = uneven_batches_by_size(
  119. dataset.src, dataset.dst, max_tokens=max_tokens,
  120. max_sentences=max_sentences, max_positions=max_positions,
  121. # FP16: during training keep the batch size a multiple of 8
  122. required_batch_size_multiple=8,
  123. )
  124. frozen_batches = tuple(batches) # freeze
  125. def dataloader(b):
  126. b = mask_batches(b, shard_id=shard_id, num_shards=num_shards) # shard dataset
  127. return torch.utils.data.DataLoader(dataset, collate_fn=dataset.collater, batch_sampler=b)
  128. for epoch in itertools.count(1):
  129. # set seed based on the seed and epoch number so that we get
  130. # reproducible results when resuming from checkpoints
  131. with numpy_seed(seed + epoch):
  132. batches = list(frozen_batches) # copy
  133. np.random.shuffle(batches)
  134. if sample_without_replacement > 0:
  135. # emit sub-epoch dataloaders
  136. while len(batches) >= sample_without_replacement:
  137. sampled_batches = batches[:sample_without_replacement]
  138. remaining_batches = batches[sample_without_replacement:]
  139. yield dataloader(sampled_batches)
  140. batches = remaining_batches
  141. if len(batches) > 0:
  142. yield dataloader(batches)
  143. else:
  144. # emit full dataloader
  145. yield dataloader(batches)
  146. def eval_dataloader(self, split, num_workers=0, max_tokens=None,
  147. max_sentences=None, max_positions=(1024, 1024),
  148. skip_invalid_size_inputs_valid_test=False,
  149. descending=False, shard_id=0, num_shards=1):
  150. dataset = self.splits[split]
  151. batch_sampler = batches_by_size(
  152. dataset.src, dataset.dst, max_tokens, max_sentences,
  153. max_positions=max_positions,
  154. ignore_invalid_inputs=skip_invalid_size_inputs_valid_test,
  155. descending=descending,
  156. allow_different_src_lens=True)
  157. batch_sampler = mask_batches(batch_sampler, shard_id=shard_id, num_shards=num_shards)
  158. return torch.utils.data.DataLoader(
  159. dataset, num_workers=num_workers, collate_fn=dataset.collater,
  160. batch_sampler=batch_sampler)
  161. class sharded_iterator(object):
  162. def __init__(self, itr, num_shards, shard_id):
  163. assert shard_id >= 0 and shard_id < num_shards
  164. self.itr = itr
  165. self.num_shards = num_shards
  166. self.shard_id = shard_id
  167. def __len__(self):
  168. return len(self.itr)
  169. def __iter__(self):
  170. for i, v in enumerate(self.itr):
  171. if i % self.num_shards == self.shard_id:
  172. yield v
  173. class LanguagePairDataset(torch.utils.data.Dataset):
  174. # padding constants
  175. LEFT_PAD_SOURCE = True
  176. LEFT_PAD_TARGET = False
  177. def __init__(self, src, dst, pad_idx, eos_idx):
  178. self.src = src
  179. self.dst = dst
  180. self.pad_idx = pad_idx
  181. self.eos_idx = eos_idx
  182. def __getitem__(self, i):
  183. # subtract 1 for 0-based indexing
  184. source = self.src[i].long() - 1
  185. res = {'id': i, 'source': source}
  186. if self.dst:
  187. res['target'] = self.dst[i].long() - 1
  188. return res
  189. def __len__(self):
  190. return len(self.src)
  191. def collater(self, samples):
  192. return LanguagePairDataset.collate(samples, self.pad_idx, self.eos_idx, self.dst is not None)
  193. @staticmethod
  194. def collate(samples, pad_idx, eos_idx, has_target=True):
  195. if len(samples) == 0:
  196. return {}
  197. def merge(key, left_pad, move_eos_to_beginning=False):
  198. return LanguagePairDataset.collate_tokens(
  199. [s[key] for s in samples],
  200. pad_idx, eos_idx, left_pad, move_eos_to_beginning,
  201. )
  202. id = torch.LongTensor([s['id'] for s in samples])
  203. src_tokens = merge('source', left_pad=LanguagePairDataset.LEFT_PAD_SOURCE)
  204. # sort by descending source length
  205. src_lengths = torch.LongTensor([s['source'].numel() for s in samples])
  206. src_lengths, sort_order = src_lengths.sort(descending=True)
  207. id = id.index_select(0, sort_order)
  208. src_tokens = src_tokens.index_select(0, sort_order)
  209. prev_output_tokens = None
  210. target = None
  211. ntokens = None
  212. if has_target:
  213. target = merge('target', left_pad=LanguagePairDataset.LEFT_PAD_TARGET)
  214. # we create a shifted version of targets for feeding the
  215. # previous output token(s) into the next decoder step
  216. prev_output_tokens = merge(
  217. 'target',
  218. left_pad=LanguagePairDataset.LEFT_PAD_TARGET,
  219. move_eos_to_beginning=True,
  220. )
  221. prev_output_tokens = prev_output_tokens.index_select(0, sort_order)
  222. target = target.index_select(0, sort_order)
  223. ntokens = sum(len(s['target']) for s in samples)
  224. return {
  225. 'id': id,
  226. 'ntokens': ntokens,
  227. 'net_input': {
  228. 'src_tokens': src_tokens,
  229. 'src_lengths': src_lengths,
  230. 'prev_output_tokens': prev_output_tokens,
  231. },
  232. 'target': target,
  233. }
  234. @staticmethod
  235. def collate_tokens(values, pad_idx, eos_idx, left_pad, move_eos_to_beginning=False):
  236. size = max(v.size(0) for v in values)
  237. res = values[0].new(len(values), size).fill_(pad_idx)
  238. def copy_tensor(src, dst):
  239. assert dst.numel() == src.numel()
  240. if move_eos_to_beginning:
  241. assert src[-1] == eos_idx
  242. dst[0] = eos_idx
  243. dst[1:] = src[:-1]
  244. else:
  245. dst.copy_(src)
  246. for i, v in enumerate(values):
  247. if left_pad:
  248. copy_tensor(v, res[i][size-len(v):])
  249. else:
  250. copy_tensor(v, res[i][:len(v)])
  251. return res
  252. def _valid_size(src_size, dst_size, max_positions):
  253. if isinstance(max_positions, numbers.Number):
  254. max_src_positions, max_dst_positions = max_positions, max_positions
  255. else:
  256. max_src_positions, max_dst_positions = max_positions
  257. if src_size < 1 or src_size > max_src_positions:
  258. return False
  259. if dst_size is not None and (dst_size < 1 or dst_size > max_dst_positions):
  260. return False
  261. return True
  262. def _make_batches(src, dst, indices, max_tokens, max_sentences, max_positions,
  263. ignore_invalid_inputs=False, allow_different_src_lens=False,
  264. required_batch_size_multiple=1):
  265. batch = []
  266. mult = required_batch_size_multiple
  267. def yield_batch(next_idx, num_tokens):
  268. if len(batch) == 0:
  269. return False
  270. if len(batch) == max_sentences:
  271. return True
  272. if num_tokens > max_tokens:
  273. return True
  274. if not allow_different_src_lens and \
  275. (src.sizes[batch[0]] != src.sizes[next_idx]):
  276. return True
  277. return False
  278. sample_len = 0
  279. sample_lens = []
  280. ignored = []
  281. for idx in map(int, indices):
  282. src_size = src.sizes[idx]
  283. dst_size = dst.sizes[idx] if dst else src_size
  284. if not _valid_size(src_size, dst_size, max_positions):
  285. if ignore_invalid_inputs:
  286. ignored.append(idx)
  287. continue
  288. raise Exception((
  289. "Sample #{} has size (src={}, dst={}) but max size is {}."
  290. " Skip this example with --skip-invalid-size-inputs-valid-test"
  291. ).format(idx, src_size, dst_size, max_positions))
  292. sample_lens.append(max(src_size, dst_size))
  293. sample_len = max(sample_len, sample_lens[-1])
  294. num_tokens = (len(batch) + 1) * sample_len
  295. if yield_batch(idx, num_tokens):
  296. mod8_len = max(mult * (len(batch) // mult), len(batch) % mult)
  297. yield batch[:mod8_len]
  298. batch = batch[mod8_len:]
  299. sample_lens = sample_lens[mod8_len:]
  300. sample_len = max(sample_lens) if len(sample_lens) > 0 else 0
  301. batch.append(idx)
  302. if len(batch) > 0:
  303. yield batch
  304. if len(ignored) > 0:
  305. print("Warning! {} samples are either too short or too long "
  306. "and will be ignored, first few sample ids={}".format(len(ignored), ignored[:10]))
  307. def batches_by_size(src, dst, max_tokens=None, max_sentences=None,
  308. max_positions=(1024, 1024), ignore_invalid_inputs=False,
  309. descending=False, required_batch_size_multiple=1, allow_different_src_lens=False):
  310. """Returns batches of indices sorted by size. Sequences with different
  311. source lengths are not allowed in the same batch."""
  312. assert isinstance(src, IndexedDataset) and (dst is None or isinstance(dst, IndexedDataset))
  313. if max_tokens is None:
  314. max_tokens = float('Inf')
  315. if max_sentences is None:
  316. max_sentences = float('Inf')
  317. indices = np.argsort(src.sizes, kind='mergesort')
  318. if descending:
  319. indices = np.flip(indices, 0)
  320. return list(_make_batches(
  321. src, dst, indices, max_tokens, max_sentences, max_positions,
  322. ignore_invalid_inputs, allow_different_src_lens=allow_different_src_lens,
  323. required_batch_size_multiple=required_batch_size_multiple,
  324. ))
  325. def uneven_batches_by_size(src, dst, max_tokens=None, max_sentences=None,
  326. max_positions=(1024, 1024),
  327. required_batch_size_multiple=1):
  328. """Returns batches of indices bucketed by size. Batches may contain
  329. sequences of different lengths."""
  330. assert isinstance(src, IndexedDataset) and isinstance(dst, IndexedDataset)
  331. if max_tokens is None:
  332. max_tokens = float('Inf')
  333. if max_sentences is None:
  334. max_sentences = float('Inf')
  335. indices = np.random.permutation(len(src))
  336. # sort by sizes
  337. indices = indices[np.argsort(dst.sizes[indices], kind='mergesort')]
  338. indices = indices[np.argsort(src.sizes[indices], kind='mergesort')]
  339. batches = list(_make_batches(
  340. src, dst, indices, max_tokens, max_sentences, max_positions,
  341. ignore_invalid_inputs=True, allow_different_src_lens=True,
  342. required_batch_size_multiple=required_batch_size_multiple,
  343. ))
  344. return batches
  345. def mask_batches(batch_sampler, shard_id, num_shards):
  346. if num_shards == 1:
  347. return batch_sampler
  348. res = [
  349. batch
  350. for i, batch in enumerate(batch_sampler)
  351. if i % num_shards == shard_id
  352. ]
  353. expected_length = int(math.ceil(len(batch_sampler) / num_shards))
  354. return res + [[]] * (expected_length - len(res))
  355. @contextlib.contextmanager
  356. def numpy_seed(seed):
  357. """Context manager which seeds the NumPy PRNG with the specified seed and
  358. restores the state afterward"""
  359. if seed is None:
  360. yield
  361. return
  362. state = np.random.get_state()
  363. np.random.seed(seed)
  364. try:
  365. yield
  366. finally:
  367. np.random.set_state(state)
  368. def get_dummy_batch(ntokens, src_dict, dst_dict, src_len=128, tgt_len=128):
  369. bsz = int(ntokens / max(src_len, tgt_len))
  370. bsz = math.ceil(bsz / 8) * 8
  371. assert src_dict.pad() == dst_dict.pad()
  372. pad_idx = src_dict.pad()
  373. src_vocab, dst_vocab = len(src_dict), len(dst_dict)
  374. dummy_batch = {}
  375. dummy_batch['id'] = Variable(torch.arange(bsz).long().cuda())
  376. dummy_batch['ntokens'] = tgt_len * bsz
  377. dummy_batch['target'] = Variable(torch.Tensor(bsz, tgt_len).uniform_(pad_idx + 1, dst_vocab - 1).long().cuda())
  378. input = {}
  379. input['prev_output_tokens'] = Variable(dummy_batch['target'].data.clone())
  380. input['src_lengths'] = Variable(torch.LongTensor(bsz).fill_(src_len).cuda())
  381. input['src_tokens'] = Variable(torch.Tensor(bsz, src_len).uniform_(pad_idx + 1, src_vocab - 1).long().cuda())
  382. dummy_batch['net_input'] = input
  383. return dummy_batch
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...