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

utils.py 16 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
  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 importlib.util
  8. import json
  9. import logging
  10. import os
  11. import re
  12. import sys
  13. import traceback
  14. from collections import defaultdict, OrderedDict
  15. import torch
  16. from torch.serialization import default_restore_location
  17. def torch_persistent_save(*args, **kwargs):
  18. for i in range(3):
  19. try:
  20. return torch.save(*args, **kwargs)
  21. except Exception:
  22. if i == 2:
  23. logging.error(traceback.format_exc())
  24. def convert_state_dict_type(state_dict, ttype=torch.FloatTensor):
  25. if isinstance(state_dict, dict):
  26. cpu_dict = OrderedDict()
  27. for k, v in state_dict.items():
  28. cpu_dict[k] = convert_state_dict_type(v)
  29. return cpu_dict
  30. elif isinstance(state_dict, list):
  31. return [convert_state_dict_type(v) for v in state_dict]
  32. elif torch.is_tensor(state_dict):
  33. return state_dict.type(ttype)
  34. else:
  35. return state_dict
  36. def save_state(filename, args, model_state_dict, criterion, optimizer, lr_scheduler,
  37. num_updates, optim_history=None, extra_state=None):
  38. if optim_history is None:
  39. optim_history = []
  40. if extra_state is None:
  41. extra_state = {}
  42. state_dict = {
  43. 'args': args,
  44. 'model': model_state_dict if model_state_dict else {},
  45. 'optimizer_history': optim_history + [
  46. {
  47. 'criterion_name': criterion.__class__.__name__,
  48. 'optimizer_name': optimizer.__class__.__name__,
  49. 'lr_scheduler_state': lr_scheduler.state_dict(),
  50. 'num_updates': num_updates,
  51. }
  52. ],
  53. 'last_optimizer_state': convert_state_dict_type(optimizer.state_dict()),
  54. 'extra_state': extra_state,
  55. }
  56. torch_persistent_save(state_dict, filename)
  57. def load_model_state(filename, model):
  58. if not os.path.exists(filename):
  59. return None, [], None
  60. state = torch.load(filename, map_location=lambda s, l: default_restore_location(s, 'cpu'))
  61. state = _upgrade_state_dict(state)
  62. model.upgrade_state_dict(state['model'])
  63. # load model parameters
  64. try:
  65. model.load_state_dict(state['model'], strict=True)
  66. except Exception:
  67. raise Exception('Cannot load model parameters from checkpoint, '
  68. 'please ensure that the architectures match')
  69. return state['extra_state'], state['optimizer_history'], state['last_optimizer_state']
  70. def _upgrade_state_dict(state):
  71. """Helper for upgrading old model checkpoints."""
  72. # add optimizer_history
  73. if 'optimizer_history' not in state:
  74. state['optimizer_history'] = [
  75. {
  76. 'criterion_name': 'CrossEntropyCriterion',
  77. 'best_loss': state['best_loss'],
  78. },
  79. ]
  80. state['last_optimizer_state'] = state['optimizer']
  81. del state['optimizer']
  82. del state['best_loss']
  83. # move extra_state into sub-dictionary
  84. if 'epoch' in state and 'extra_state' not in state:
  85. state['extra_state'] = {
  86. 'epoch': state['epoch'],
  87. 'batch_offset': state['batch_offset'],
  88. 'val_loss': state['val_loss'],
  89. }
  90. del state['epoch']
  91. del state['batch_offset']
  92. del state['val_loss']
  93. # reduce optimizer history's memory usage (only keep the last state)
  94. if 'optimizer' in state['optimizer_history'][-1]:
  95. state['last_optimizer_state'] = state['optimizer_history'][-1]['optimizer']
  96. for optim_hist in state['optimizer_history']:
  97. del optim_hist['optimizer']
  98. # record the optimizer class name
  99. if 'optimizer_name' not in state['optimizer_history'][-1]:
  100. state['optimizer_history'][-1]['optimizer_name'] = 'FairseqNAG'
  101. # move best_loss into lr_scheduler_state
  102. if 'lr_scheduler_state' not in state['optimizer_history'][-1]:
  103. state['optimizer_history'][-1]['lr_scheduler_state'] = {
  104. 'best': state['optimizer_history'][-1]['best_loss'],
  105. }
  106. del state['optimizer_history'][-1]['best_loss']
  107. # keep track of number of updates
  108. if 'num_updates' not in state['optimizer_history'][-1]:
  109. state['optimizer_history'][-1]['num_updates'] = 0
  110. # old model checkpoints may not have separate source/target positions
  111. if hasattr(state['args'], 'max_positions') and not hasattr(state['args'], 'max_source_positions'):
  112. state['args'].max_source_positions = state['args'].max_positions
  113. state['args'].max_target_positions = state['args'].max_positions
  114. # use stateful training data iterator
  115. if 'train_iterator' not in state['extra_state']:
  116. state['extra_state']['train_iterator'] = {
  117. 'epoch': state['extra_state']['epoch'],
  118. 'iterations_in_epoch': state['extra_state'].get('batch_offset', 0),
  119. }
  120. return state
  121. def load_checkpoint_to_cpu(path):
  122. state = torch.load(path, map_location=lambda s, l: default_restore_location(s, 'cpu'))
  123. state = _upgrade_state_dict(state)
  124. return state
  125. def load_ensemble_for_inference(filenames, task, model_arg_overrides=None):
  126. """Load an ensemble of models for inference.
  127. model_arg_overrides allows you to pass a dictionary model_arg_overrides --
  128. {'arg_name': arg} -- to override model args that were used during model
  129. training
  130. """
  131. # load model architectures and weights
  132. states = []
  133. for filename in filenames:
  134. if not os.path.exists(filename):
  135. raise IOError('Model file not found: {}'.format(filename))
  136. state = load_checkpoint_to_cpu(filename)
  137. states.append(state)
  138. ensemble = []
  139. for state in states:
  140. args = state['args']
  141. if model_arg_overrides is not None:
  142. args = override_model_args(args, model_arg_overrides)
  143. # build model for ensemble
  144. model = task.build_model(args)
  145. model.upgrade_state_dict(state['model'])
  146. model.load_state_dict(state['model'], strict=True)
  147. ensemble.append(model)
  148. # some args (e.g., tokens_per_sample) might have been updated while building the model
  149. if model_arg_overrides is not None:
  150. args = override_model_args(args, model_arg_overrides)
  151. return ensemble, args
  152. def override_model_args(args, model_arg_overrides):
  153. # Uses model_arg_overrides {'arg_name': arg} to override model args
  154. for arg_name, arg_val in model_arg_overrides.items():
  155. setattr(args, arg_name, arg_val)
  156. return args
  157. def move_to_cuda(sample):
  158. if len(sample) == 0:
  159. return {}
  160. def _move_to_cuda(maybe_tensor):
  161. if torch.is_tensor(maybe_tensor):
  162. return maybe_tensor.cuda()
  163. elif isinstance(maybe_tensor, dict):
  164. return {
  165. key: _move_to_cuda(value)
  166. for key, value in maybe_tensor.items()
  167. }
  168. elif isinstance(maybe_tensor, list):
  169. return [_move_to_cuda(x) for x in maybe_tensor]
  170. else:
  171. return maybe_tensor
  172. return _move_to_cuda(sample)
  173. INCREMENTAL_STATE_INSTANCE_ID = defaultdict(lambda: 0)
  174. def _get_full_incremental_state_key(module_instance, key):
  175. module_name = module_instance.__class__.__name__
  176. # assign a unique ID to each module instance, so that incremental state is
  177. # not shared across module instances
  178. if not hasattr(module_instance, '_fairseq_instance_id'):
  179. INCREMENTAL_STATE_INSTANCE_ID[module_name] += 1
  180. module_instance._fairseq_instance_id = INCREMENTAL_STATE_INSTANCE_ID[module_name]
  181. return '{}.{}.{}'.format(module_name, module_instance._fairseq_instance_id, key)
  182. def get_incremental_state(module, incremental_state, key):
  183. """Helper for getting incremental state for an nn.Module."""
  184. full_key = _get_full_incremental_state_key(module, key)
  185. if incremental_state is None or full_key not in incremental_state:
  186. return None
  187. return incremental_state[full_key]
  188. def set_incremental_state(module, incremental_state, key, value):
  189. """Helper for setting incremental state for an nn.Module."""
  190. if incremental_state is not None:
  191. full_key = _get_full_incremental_state_key(module, key)
  192. incremental_state[full_key] = value
  193. def load_align_dict(replace_unk):
  194. if replace_unk is None:
  195. align_dict = None
  196. elif isinstance(replace_unk, str):
  197. # Load alignment dictionary for unknown word replacement if it was passed as an argument.
  198. align_dict = {}
  199. with open(replace_unk, 'r') as f:
  200. for line in f:
  201. cols = line.split()
  202. align_dict[cols[0]] = cols[1]
  203. else:
  204. # No alignment dictionary provided but we still want to perform unknown word replacement by copying the
  205. # original source word.
  206. align_dict = {}
  207. return align_dict
  208. def print_embed_overlap(embed_dict, vocab_dict):
  209. embed_keys = set(embed_dict.keys())
  210. vocab_keys = set(vocab_dict.symbols)
  211. overlap = len(embed_keys & vocab_keys)
  212. print("| Found {}/{} types in embedding file.".format(overlap, len(vocab_dict)))
  213. def parse_embedding(embed_path):
  214. """Parse embedding text file into a dictionary of word and embedding tensors.
  215. The first line can have vocabulary size and dimension. The following lines
  216. should contain word and embedding separated by spaces.
  217. Example:
  218. 2 5
  219. the -0.0230 -0.0264 0.0287 0.0171 0.1403
  220. at -0.0395 -0.1286 0.0275 0.0254 -0.0932
  221. """
  222. embed_dict = {}
  223. with open(embed_path) as f_embed:
  224. next(f_embed) # skip header
  225. for line in f_embed:
  226. pieces = line.rstrip().split(" ")
  227. embed_dict[pieces[0]] = torch.Tensor([float(weight) for weight in pieces[1:]])
  228. return embed_dict
  229. def load_embedding(embed_dict, vocab, embedding):
  230. for idx in range(len(vocab)):
  231. token = vocab[idx]
  232. if token in embed_dict:
  233. embedding.weight.data[idx] = embed_dict[token]
  234. return embedding
  235. def replace_unk(hypo_str, src_str, alignment, align_dict, unk):
  236. from fairseq import tokenizer
  237. # Tokens are strings here
  238. hypo_tokens = tokenizer.tokenize_line(hypo_str)
  239. # TODO: Very rare cases where the replacement is '<eos>' should be handled gracefully
  240. src_tokens = tokenizer.tokenize_line(src_str) + ['<eos>']
  241. for i, ht in enumerate(hypo_tokens):
  242. if ht == unk:
  243. src_token = src_tokens[alignment[i]]
  244. # Either take the corresponding value in the aligned dictionary or just copy the original value.
  245. hypo_tokens[i] = align_dict.get(src_token, src_token)
  246. return ' '.join(hypo_tokens)
  247. def post_process_prediction(hypo_tokens, src_str, alignment, align_dict, tgt_dict, remove_bpe):
  248. from fairseq import tokenizer
  249. hypo_str = tgt_dict.string(hypo_tokens, remove_bpe)
  250. if align_dict is not None:
  251. hypo_str = replace_unk(hypo_str, src_str, alignment, align_dict, tgt_dict.unk_string())
  252. if align_dict is not None or remove_bpe is not None:
  253. # Convert back to tokens for evaluating with unk replacement or without BPE
  254. # Note that the dictionary can be modified inside the method.
  255. hypo_tokens = tokenizer.Tokenizer.tokenize(hypo_str, tgt_dict, add_if_not_exist=True)
  256. return hypo_tokens, hypo_str, alignment
  257. def make_positions(tensor, padding_idx, left_pad, onnx_trace=False):
  258. """Replace non-padding symbols with their position numbers.
  259. Position numbers begin at padding_idx+1.
  260. Padding symbols are ignored, but it is necessary to specify whether padding
  261. is added on the left side (left_pad=True) or right side (left_pad=False).
  262. """
  263. if onnx_trace:
  264. range_buf = torch._dim_arange(like=tensor, dim=1) + padding_idx + 1
  265. mask = tensor.ne(padding_idx)
  266. positions = range_buf.expand_as(tensor)
  267. if left_pad:
  268. positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1)
  269. return positions * mask.long() + padding_idx * (1 - mask.long())
  270. max_pos = padding_idx + 1 + tensor.size(1)
  271. if not hasattr(make_positions, 'range_buf'):
  272. make_positions.range_buf = tensor.new()
  273. make_positions.range_buf = make_positions.range_buf.type_as(tensor)
  274. if make_positions.range_buf.numel() < max_pos:
  275. torch.arange(padding_idx + 1, max_pos, out=make_positions.range_buf)
  276. mask = tensor.ne(padding_idx)
  277. positions = make_positions.range_buf[:tensor.size(1)].expand_as(tensor)
  278. if left_pad:
  279. positions = positions - mask.size(1) + mask.long().sum(dim=1).unsqueeze(1)
  280. return tensor.clone().masked_scatter_(mask, positions[mask])
  281. def strip_pad(tensor, pad):
  282. return tensor[tensor.ne(pad)]
  283. def buffered_arange(max):
  284. if not hasattr(buffered_arange, 'buf'):
  285. buffered_arange.buf = torch.LongTensor()
  286. if max > buffered_arange.buf.numel():
  287. torch.arange(max, out=buffered_arange.buf)
  288. return buffered_arange.buf[:max]
  289. def convert_padding_direction(src_tokens, padding_idx, right_to_left=False, left_to_right=False):
  290. assert right_to_left ^ left_to_right
  291. pad_mask = src_tokens.eq(padding_idx)
  292. if not pad_mask.any():
  293. # no padding, return early
  294. return src_tokens
  295. if left_to_right and not pad_mask[:, 0].any():
  296. # already right padded
  297. return src_tokens
  298. if right_to_left and not pad_mask[:, -1].any():
  299. # already left padded
  300. return src_tokens
  301. max_len = src_tokens.size(1)
  302. range = buffered_arange(max_len).type_as(src_tokens).expand_as(src_tokens)
  303. num_pads = pad_mask.long().sum(dim=1, keepdim=True)
  304. if right_to_left:
  305. index = torch.remainder(range - num_pads, max_len)
  306. else:
  307. index = torch.remainder(range + num_pads, max_len)
  308. return src_tokens.gather(1, index)
  309. def item(tensor):
  310. if hasattr(tensor, 'item'):
  311. return tensor.item()
  312. if hasattr(tensor, '__getitem__'):
  313. return tensor[0]
  314. return tensor
  315. def clip_grad_norm_(tensor, max_norm):
  316. grad_norm = item(torch.norm(tensor))
  317. if grad_norm > max_norm > 0:
  318. clip_coef = max_norm / (grad_norm + 1e-6)
  319. tensor.mul_(clip_coef)
  320. return grad_norm
  321. def fill_with_neg_inf(t):
  322. """FP16-compatible function that fills a tensor with -inf."""
  323. return t.float().fill_(float('-inf')).type_as(t)
  324. def checkpoint_paths(path, pattern=r'checkpoint(\d+)\.pt'):
  325. """Retrieves all checkpoints found in `path` directory.
  326. Checkpoints are identified by matching filename to the specified pattern. If
  327. the pattern contains groups, the result will be sorted by the first group in
  328. descending order.
  329. """
  330. pt_regexp = re.compile(pattern)
  331. files = os.listdir(path)
  332. entries = []
  333. for i, f in enumerate(files):
  334. m = pt_regexp.fullmatch(f)
  335. if m is not None:
  336. idx = int(m.group(1)) if len(m.groups()) > 0 else i
  337. entries.append((idx, m.group(0)))
  338. return [os.path.join(path, x[1]) for x in sorted(entries, reverse=True)]
  339. def resolve_max_positions(*args):
  340. """Resolve max position constraints from multiple sources."""
  341. def nullsafe_min(l):
  342. minim = None
  343. for item in l:
  344. if minim is None:
  345. minim = item
  346. elif item is not None and item < minim:
  347. minim = item
  348. return minim
  349. max_positions = None
  350. for arg in args:
  351. if max_positions is None:
  352. max_positions = arg
  353. elif arg is not None:
  354. if isinstance(arg, float) or isinstance(arg, int):
  355. max_positions = min(max_positions, arg)
  356. else:
  357. max_positions = tuple(
  358. map(nullsafe_min, zip(max_positions, arg))
  359. )
  360. return max_positions
  361. def import_user_module(args):
  362. module_path = getattr(args, 'user_dir', None)
  363. if module_path is not None:
  364. module_path = os.path.abspath(args.user_dir)
  365. module_parent, module_name = os.path.split(module_path)
  366. if module_name not in sys.modules:
  367. sys.path.insert(0, module_parent)
  368. importlib.import_module(module_name)
  369. sys.path.pop(0)
  370. def save_json_metric(save_dir, metric, metric_name):
  371. with open(os.path.join(save_dir, f'{metric_name}.json'), 'w') as f:
  372. json.dump({metric_name: metric}, f)
Tip!

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

Comments

Loading...