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

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

Comments

Loading...