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

train.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
  1. #!/usr/bin/env python3 -u
  2. # Copyright (c) 2017-present, Facebook, Inc.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the license found in the LICENSE file in
  6. # the root directory of this source tree. An additional grant of patent rights
  7. # can be found in the PATENTS file in the same directory.
  8. """
  9. Train a new model on one or across multiple GPUs.
  10. """
  11. import collections
  12. import itertools
  13. import os
  14. import math
  15. import random
  16. import torch
  17. from fairseq import distributed_utils, options, progress_bar, tasks, utils
  18. from fairseq.data import iterators
  19. from fairseq.trainer import Trainer
  20. from fairseq.meters import AverageMeter, StopwatchMeter
  21. from fairseq.utils import import_user_module, save_json_metric
  22. def main(args, init_distributed=False):
  23. import_user_module(args)
  24. if args.max_tokens is None:
  25. args.max_tokens = 6000
  26. print(args)
  27. if torch.cuda.is_available() and not args.cpu:
  28. torch.cuda.set_device(args.device_id)
  29. torch.manual_seed(args.seed)
  30. # Setup task, e.g., translation, language modeling, etc.
  31. task = tasks.setup_task(args)
  32. # Load dataset splits
  33. load_dataset_splits(task, ['train', 'valid'])
  34. # Initialize distributed training (after data loading)
  35. if init_distributed:
  36. import socket
  37. args.distributed_rank = distributed_utils.distributed_init(args)
  38. print('| initialized host {} as rank {}'.format(socket.gethostname(), args.distributed_rank))
  39. # Build model and criterion
  40. model = task.build_model(args)
  41. criterion = task.build_criterion(args)
  42. print(model)
  43. print('| model {}, criterion {}'.format(args.arch, criterion.__class__.__name__))
  44. print('| num. model params: {} (num. trained: {})'.format(
  45. sum(p.numel() for p in model.parameters()),
  46. sum(p.numel() for p in model.parameters() if p.requires_grad),
  47. ))
  48. # Make a dummy batch to (i) warm the caching allocator and (ii) as a
  49. # placeholder DistributedDataParallel when there's an uneven number of
  50. # batches per worker.
  51. max_positions = utils.resolve_max_positions(
  52. task.max_positions(),
  53. model.max_positions(),
  54. )
  55. dummy_batch = task.dataset('train').get_dummy_batch(args.max_tokens, max_positions)
  56. oom_batch = task.dataset('train').get_dummy_batch(1, max_positions)
  57. # Build trainer
  58. trainer = Trainer(args, task, model, criterion, dummy_batch, oom_batch)
  59. print('| training on {} GPUs'.format(args.distributed_world_size))
  60. print('| max tokens per GPU = {} and max sentences per GPU = {}'.format(
  61. args.max_tokens,
  62. args.max_sentences,
  63. ))
  64. # Initialize dataloader
  65. epoch_itr = task.get_batch_iterator(
  66. dataset=task.dataset(args.train_subset),
  67. max_tokens=args.max_tokens,
  68. max_sentences=args.max_sentences,
  69. max_positions=max_positions,
  70. ignore_invalid_inputs=True,
  71. required_batch_size_multiple=8,
  72. seed=args.seed,
  73. num_shards=args.distributed_world_size,
  74. shard_id=args.distributed_rank,
  75. num_workers=args.num_workers,
  76. )
  77. # Load the latest checkpoint if one is available
  78. if not load_checkpoint(args, trainer, epoch_itr):
  79. trainer.dummy_train_step([dummy_batch])
  80. # Train until the learning rate gets too small
  81. max_epoch = args.max_epoch or math.inf
  82. max_update = args.max_update or math.inf
  83. lr = trainer.get_lr()
  84. train_meter = StopwatchMeter()
  85. train_meter.start()
  86. valid_losses = [None]
  87. valid_subsets = args.valid_subset.split(',')
  88. while True:
  89. if lr <= args.min_lr:
  90. print("Stopping due to LR: {} <= {}".format(lr, args.min_lr))
  91. break
  92. if epoch_itr.epoch >= max_epoch:
  93. print("Stopping due to Epoch: {} <= {}".format(epoch_itr.epoch, max_epoch))
  94. break
  95. if trainer.get_num_updates() >= max_update:
  96. print("Stopping due to Train update: {} <= {}".format(trainer.get_num_updates(), max_update))
  97. break
  98. # train for one epoch
  99. train(args, trainer, task, epoch_itr)
  100. if args.validate_interval > 0 and epoch_itr.epoch % args.validate_interval == 0:
  101. valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets)
  102. # only use first validation loss to update the learning rate
  103. lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])
  104. # save checkpoint
  105. if args.save_interval > 0 and epoch_itr.epoch % args.save_interval == 0:
  106. save_checkpoint(args, trainer, epoch_itr, valid_losses[0])
  107. train_meter.stop()
  108. print('| done training in {:.1f} seconds'.format(train_meter.sum))
  109. def train(args, trainer, task, epoch_itr):
  110. """Train the model for one epoch."""
  111. # Update parameters every N batches
  112. if epoch_itr.epoch <= len(args.update_freq):
  113. update_freq = args.update_freq[epoch_itr.epoch - 1]
  114. else:
  115. update_freq = args.update_freq[-1]
  116. # Initialize data iterator
  117. itr = epoch_itr.next_epoch_itr(fix_batches_to_gpus=args.fix_batches_to_gpus)
  118. itr = iterators.GroupedIterator(itr, update_freq)
  119. progress = progress_bar.build_progress_bar(
  120. args, itr, epoch_itr.epoch, no_progress_bar='simple',
  121. )
  122. extra_meters = collections.defaultdict(lambda: AverageMeter())
  123. first_valid = args.valid_subset.split(',')[0]
  124. max_update = args.max_update or math.inf
  125. for i, samples in enumerate(progress, start=epoch_itr.iterations_in_epoch):
  126. log_output = trainer.train_step(samples)
  127. if log_output is None:
  128. continue
  129. # log mid-epoch stats
  130. stats = get_training_stats(trainer)
  131. for k, v in log_output.items():
  132. if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size']:
  133. continue # these are already logged above
  134. if 'loss' in k:
  135. extra_meters[k].update(v, log_output['sample_size'])
  136. else:
  137. extra_meters[k].update(v)
  138. stats[k] = extra_meters[k].avg
  139. progress.log(stats)
  140. # ignore the first mini-batch in words-per-second calculation
  141. if i == 0:
  142. trainer.get_meter('wps').reset()
  143. num_updates = trainer.get_num_updates()
  144. if args.save_interval_updates > 0 and num_updates % args.save_interval_updates == 0 and num_updates > 0:
  145. valid_losses = validate(args, trainer, task, epoch_itr, [first_valid])
  146. # Update LR in the middle of the epoch, since epochs are probably too long if we're saving checkpoints in the middle of them.
  147. trainer.lr_step(epoch_itr.epoch, valid_losses[0])
  148. save_checkpoint(args, trainer, epoch_itr, valid_losses[0])
  149. if num_updates >= max_update:
  150. break
  151. # log end-of-epoch stats
  152. stats = get_training_stats(trainer)
  153. for k, meter in extra_meters.items():
  154. stats[k] = meter.avg
  155. progress.print(stats)
  156. # reset training meters
  157. for k in [
  158. 'train_loss', 'train_nll_loss', 'wps', 'ups', 'wpb', 'bsz', 'gnorm', 'clip',
  159. ]:
  160. meter = trainer.get_meter(k)
  161. if meter is not None:
  162. meter.reset()
  163. def get_training_stats(trainer):
  164. stats = collections.OrderedDict()
  165. stats['loss'] = '{:.3f}'.format(trainer.get_meter('train_loss').avg)
  166. if trainer.get_meter('train_nll_loss').count > 0:
  167. nll_loss = trainer.get_meter('train_nll_loss').avg
  168. stats['nll_loss'] = '{:.3f}'.format(nll_loss)
  169. else:
  170. nll_loss = trainer.get_meter('train_loss').avg
  171. stats['ppl'] = get_perplexity(nll_loss)
  172. stats['wps'] = round(trainer.get_meter('wps').avg)
  173. stats['ups'] = '{:.1f}'.format(trainer.get_meter('ups').avg)
  174. stats['wpb'] = round(trainer.get_meter('wpb').avg)
  175. stats['bsz'] = round(trainer.get_meter('bsz').avg)
  176. stats['num_updates'] = trainer.get_num_updates()
  177. stats['lr'] = trainer.get_lr()
  178. stats['gnorm'] = '{:.3f}'.format(trainer.get_meter('gnorm').avg)
  179. stats['clip'] = '{:.0%}'.format(trainer.get_meter('clip').avg)
  180. stats['oom'] = trainer.get_meter('oom').avg
  181. if trainer.get_meter('loss_scale') is not None:
  182. stats['loss_scale'] = '{:.3f}'.format(trainer.get_meter('loss_scale').avg)
  183. stats['wall'] = round(trainer.get_meter('wall').elapsed_time)
  184. stats['train_wall'] = round(trainer.get_meter('train_wall').sum)
  185. return stats
  186. def validate(args, trainer, task, epoch_itr, subsets):
  187. """Evaluate the model on the validation set(s) and return the losses."""
  188. valid_losses = []
  189. for subset in subsets:
  190. # Initialize data iterator
  191. itr = task.get_batch_iterator(
  192. dataset=task.dataset(subset),
  193. max_tokens=args.max_tokens,
  194. max_sentences=args.max_sentences_valid,
  195. max_positions=utils.resolve_max_positions(
  196. task.max_positions(),
  197. trainer.get_model().max_positions(),
  198. ),
  199. ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,
  200. required_batch_size_multiple=8,
  201. seed=args.seed,
  202. num_shards=args.distributed_world_size,
  203. shard_id=args.distributed_rank,
  204. num_workers=args.num_workers,
  205. ).next_epoch_itr(shuffle=False)
  206. progress = progress_bar.build_progress_bar(
  207. args, itr, epoch_itr.epoch,
  208. prefix='valid on \'{}\' subset'.format(subset),
  209. no_progress_bar='simple'
  210. )
  211. # reset validation loss meters
  212. for k in ['valid_loss', 'valid_nll_loss']:
  213. meter = trainer.get_meter(k)
  214. if meter is not None:
  215. meter.reset()
  216. extra_meters = collections.defaultdict(lambda: AverageMeter())
  217. for sample in progress:
  218. log_output = trainer.valid_step(sample)
  219. for k, v in log_output.items():
  220. if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size']:
  221. continue
  222. extra_meters[k].update(v)
  223. # log validation stats
  224. stats = get_valid_stats(trainer)
  225. for k, meter in extra_meters.items():
  226. stats[k] = meter.avg
  227. progress.print(stats)
  228. valid_losses.append(stats['valid_loss'])
  229. trainer.meters['valid_losses'].update(valid_losses)
  230. return valid_losses
  231. def get_valid_stats(trainer):
  232. stats = collections.OrderedDict()
  233. stats['valid_loss'] = trainer.get_meter('valid_loss').avg
  234. if trainer.get_meter('valid_nll_loss').count > 0:
  235. nll_loss = trainer.get_meter('valid_nll_loss').avg
  236. stats['valid_nll_loss'] = nll_loss
  237. else:
  238. nll_loss = trainer.get_meter('valid_loss').avg
  239. stats['valid_ppl'] = get_perplexity(nll_loss)
  240. stats['num_updates'] = trainer.get_num_updates()
  241. if hasattr(save_checkpoint, 'best'):
  242. stats['best'] = min(save_checkpoint.best, stats['valid_loss'])
  243. return stats
  244. def get_perplexity(loss):
  245. try:
  246. return '{:.2f}'.format(math.pow(2, loss))
  247. except OverflowError:
  248. return float('inf')
  249. def save_checkpoint(args, trainer, epoch_itr, val_loss):
  250. if args.no_save or not distributed_utils.is_master(args):
  251. return
  252. epoch = epoch_itr.epoch
  253. end_of_epoch = epoch_itr.end_of_epoch()
  254. updates = trainer.get_num_updates()
  255. checkpoint_conds = collections.OrderedDict()
  256. checkpoint_conds['checkpoint{}.pt'.format(epoch)] = (
  257. end_of_epoch and not args.no_epoch_checkpoints and
  258. epoch % args.save_interval == 0
  259. )
  260. checkpoint_conds['checkpoint_{}_{}.pt'.format(epoch, updates)] = (
  261. not end_of_epoch and args.save_interval_updates > 0 and
  262. updates % args.save_interval_updates == 0
  263. )
  264. checkpoint_conds['checkpoint_best.pt'] = (
  265. val_loss is not None and
  266. (not hasattr(save_checkpoint, 'best') or val_loss < save_checkpoint.best)
  267. )
  268. checkpoint_conds['checkpoint_last.pt'] = True # keep this last so that it's a symlink
  269. prev_best = getattr(save_checkpoint, 'best', val_loss)
  270. if val_loss is not None:
  271. save_checkpoint.best = min(val_loss, prev_best)
  272. extra_state = {
  273. 'train_iterator': epoch_itr.state_dict(),
  274. 'val_loss': val_loss,
  275. }
  276. if hasattr(save_checkpoint, 'best'):
  277. extra_state.update({'best': save_checkpoint.best})
  278. # TODO: Set directory?
  279. save_json_metric('./metrics', extra_state['val_loss'], 'val_loss')
  280. save_json_metric('./metrics', extra_state['best'], 'best')
  281. checkpoints = [os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond]
  282. if len(checkpoints) > 0:
  283. for cp in checkpoints:
  284. trainer.save_checkpoint(cp, extra_state)
  285. if not end_of_epoch and args.keep_interval_updates > 0:
  286. # remove old checkpoints; checkpoints are sorted in descending order
  287. checkpoints = utils.checkpoint_paths(args.save_dir, pattern=r'checkpoint_\d+_(\d+)\.pt')
  288. for old_chk in checkpoints[args.keep_interval_updates:]:
  289. if os.path.lexists(old_chk):
  290. os.remove(old_chk)
  291. if args.keep_last_epochs > 0:
  292. # remove old epoch checkpoints; checkpoints are sorted in descending order
  293. checkpoints = utils.checkpoint_paths(args.save_dir, pattern=r'checkpoint\d+\.pt')
  294. for old_chk in checkpoints[args.keep_last_epochs:]:
  295. if os.path.lexists(old_chk):
  296. os.remove(old_chk)
  297. def load_checkpoint(args, trainer, epoch_itr):
  298. """Load a checkpoint and replay dataloader to match."""
  299. os.makedirs(args.save_dir, exist_ok=True)
  300. if os.path.isabs(args.restore_file):
  301. checkpoint_path = args.restore_file
  302. else:
  303. checkpoint_path = os.path.join(args.save_dir, args.restore_file)
  304. if os.path.isfile(checkpoint_path):
  305. extra_state = trainer.load_checkpoint(checkpoint_path, args.reset_optimizer, args.reset_lr_scheduler,
  306. eval(args.optimizer_overrides))
  307. if extra_state is not None:
  308. # replay train iterator to match checkpoint
  309. epoch_itr.load_state_dict(extra_state['train_iterator'])
  310. print('| loaded checkpoint {} (epoch {} @ {} updates)'.format(
  311. checkpoint_path, epoch_itr.epoch, trainer.get_num_updates()))
  312. trainer.lr_step(epoch_itr.epoch)
  313. trainer.lr_step_update(trainer.get_num_updates())
  314. if 'best' in extra_state:
  315. save_checkpoint.best = extra_state['best']
  316. return True
  317. else:
  318. print('| no existing checkpoint found {}'.format(checkpoint_path))
  319. return False
  320. def load_dataset_splits(task, splits):
  321. for split in splits:
  322. if split == 'train':
  323. task.load_dataset(split, combine=True)
  324. else:
  325. for k in itertools.count():
  326. split_k = split + (str(k) if k > 0 else '')
  327. try:
  328. task.load_dataset(split_k, combine=False)
  329. except FileNotFoundError as e:
  330. if k > 0:
  331. break
  332. raise e
  333. def distributed_main(i, args):
  334. args.device_id = i
  335. if args.distributed_rank is None: # torch.multiprocessing.spawn
  336. args.distributed_rank = i
  337. main(args, init_distributed=True)
  338. def cli_main():
  339. parser = options.get_training_parser()
  340. args = options.parse_args_and_arch(parser)
  341. if args.distributed_init_method is None:
  342. distributed_utils.infer_init_method(args)
  343. if args.distributed_init_method is not None:
  344. # distributed training
  345. distributed_main(args.device_id, args)
  346. elif args.distributed_world_size > 1:
  347. # fallback for single node with multiple GPUs
  348. port = random.randint(10000, 20000)
  349. args.distributed_init_method = 'tcp://localhost:{port}'.format(port=port)
  350. args.distributed_rank = None # set based on device id
  351. print(
  352. '''| NOTE: you may get better performance with:
  353. python -m torch.distributed.launch --nproc_per_node {ngpu} train.py {no_c10d}(...)
  354. '''.format(
  355. ngpu=args.distributed_world_size,
  356. no_c10d=(
  357. '--ddp-backend=no_c10d ' if max(args.update_freq) > 1 and args.ddp_backend != 'no_c10d'
  358. else ''
  359. ),
  360. )
  361. )
  362. torch.multiprocessing.spawn(
  363. fn=distributed_main,
  364. args=(args, ),
  365. nprocs=args.distributed_world_size,
  366. )
  367. else:
  368. # single GPU training
  369. main(args)
  370. if __name__ == '__main__':
  371. cli_main()
Tip!

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

Comments

Loading...