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
  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
  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 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 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. save_checkpoint(args, trainer, epoch_itr, valid_losses[0])
  147. if num_updates >= max_update:
  148. break
  149. # log end-of-epoch stats
  150. stats = get_training_stats(trainer)
  151. for k, meter in extra_meters.items():
  152. stats[k] = meter.avg
  153. progress.print(stats)
  154. # reset training meters
  155. for k in [
  156. 'train_loss', 'train_nll_loss', 'wps', 'ups', 'wpb', 'bsz', 'gnorm', 'clip',
  157. ]:
  158. meter = trainer.get_meter(k)
  159. if meter is not None:
  160. meter.reset()
  161. def get_training_stats(trainer):
  162. stats = collections.OrderedDict()
  163. stats['loss'] = '{:.3f}'.format(trainer.get_meter('train_loss').avg)
  164. if trainer.get_meter('train_nll_loss').count > 0:
  165. nll_loss = trainer.get_meter('train_nll_loss').avg
  166. stats['nll_loss'] = '{:.3f}'.format(nll_loss)
  167. else:
  168. nll_loss = trainer.get_meter('train_loss').avg
  169. stats['ppl'] = get_perplexity(nll_loss)
  170. stats['wps'] = round(trainer.get_meter('wps').avg)
  171. stats['ups'] = '{:.1f}'.format(trainer.get_meter('ups').avg)
  172. stats['wpb'] = round(trainer.get_meter('wpb').avg)
  173. stats['bsz'] = round(trainer.get_meter('bsz').avg)
  174. stats['num_updates'] = trainer.get_num_updates()
  175. stats['lr'] = trainer.get_lr()
  176. stats['gnorm'] = '{:.3f}'.format(trainer.get_meter('gnorm').avg)
  177. stats['clip'] = '{:.0%}'.format(trainer.get_meter('clip').avg)
  178. stats['oom'] = trainer.get_meter('oom').avg
  179. if trainer.get_meter('loss_scale') is not None:
  180. stats['loss_scale'] = '{:.3f}'.format(trainer.get_meter('loss_scale').avg)
  181. stats['wall'] = round(trainer.get_meter('wall').elapsed_time)
  182. stats['train_wall'] = round(trainer.get_meter('train_wall').sum)
  183. return stats
  184. def validate(args, trainer, task, epoch_itr, subsets):
  185. """Evaluate the model on the validation set(s) and return the losses."""
  186. valid_losses = []
  187. for subset in subsets:
  188. # Initialize data iterator
  189. itr = task.get_batch_iterator(
  190. dataset=task.dataset(subset),
  191. max_tokens=args.max_tokens,
  192. max_sentences=args.max_sentences_valid,
  193. max_positions=utils.resolve_max_positions(
  194. task.max_positions(),
  195. trainer.get_model().max_positions(),
  196. ),
  197. ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,
  198. required_batch_size_multiple=8,
  199. seed=args.seed,
  200. num_shards=args.distributed_world_size,
  201. shard_id=args.distributed_rank,
  202. num_workers=args.num_workers,
  203. ).next_epoch_itr(shuffle=False)
  204. progress = progress_bar.build_progress_bar(
  205. args, itr, epoch_itr.epoch,
  206. prefix='valid on \'{}\' subset'.format(subset),
  207. no_progress_bar='simple'
  208. )
  209. # reset validation loss meters
  210. for k in ['valid_loss', 'valid_nll_loss']:
  211. meter = trainer.get_meter(k)
  212. if meter is not None:
  213. meter.reset()
  214. extra_meters = collections.defaultdict(lambda: AverageMeter())
  215. for sample in progress:
  216. log_output = trainer.valid_step(sample)
  217. for k, v in log_output.items():
  218. if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size']:
  219. continue
  220. extra_meters[k].update(v)
  221. # log validation stats
  222. stats = get_valid_stats(trainer)
  223. for k, meter in extra_meters.items():
  224. stats[k] = meter.avg
  225. progress.print(stats)
  226. valid_losses.append(stats['valid_loss'])
  227. return valid_losses
  228. def get_valid_stats(trainer):
  229. stats = collections.OrderedDict()
  230. stats['valid_loss'] = trainer.get_meter('valid_loss').avg
  231. if trainer.get_meter('valid_nll_loss').count > 0:
  232. nll_loss = trainer.get_meter('valid_nll_loss').avg
  233. stats['valid_nll_loss'] = nll_loss
  234. else:
  235. nll_loss = trainer.get_meter('valid_loss').avg
  236. stats['valid_ppl'] = get_perplexity(nll_loss)
  237. stats['num_updates'] = trainer.get_num_updates()
  238. if hasattr(save_checkpoint, 'best'):
  239. stats['best'] = min(save_checkpoint.best, stats['valid_loss'])
  240. return stats
  241. def get_perplexity(loss):
  242. try:
  243. return '{:.2f}'.format(math.pow(2, loss))
  244. except OverflowError:
  245. return float('inf')
  246. def save_checkpoint(args, trainer, epoch_itr, val_loss):
  247. if args.no_save or not distributed_utils.is_master(args):
  248. return
  249. epoch = epoch_itr.epoch
  250. end_of_epoch = epoch_itr.end_of_epoch()
  251. updates = trainer.get_num_updates()
  252. checkpoint_conds = collections.OrderedDict()
  253. checkpoint_conds['checkpoint{}.pt'.format(epoch)] = (
  254. end_of_epoch and not args.no_epoch_checkpoints and
  255. epoch % args.save_interval == 0
  256. )
  257. checkpoint_conds['checkpoint_{}_{}.pt'.format(epoch, updates)] = (
  258. not end_of_epoch and args.save_interval_updates > 0 and
  259. updates % args.save_interval_updates == 0
  260. )
  261. checkpoint_conds['checkpoint_best.pt'] = (
  262. val_loss is not None and
  263. (not hasattr(save_checkpoint, 'best') or val_loss < save_checkpoint.best)
  264. )
  265. checkpoint_conds['checkpoint_last.pt'] = True # keep this last so that it's a symlink
  266. prev_best = getattr(save_checkpoint, 'best', val_loss)
  267. if val_loss is not None:
  268. save_checkpoint.best = min(val_loss, prev_best)
  269. extra_state = {
  270. 'train_iterator': epoch_itr.state_dict(),
  271. 'val_loss': val_loss,
  272. }
  273. if hasattr(save_checkpoint, 'best'):
  274. extra_state.update({'best': save_checkpoint.best})
  275. checkpoints = [os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond]
  276. if len(checkpoints) > 0:
  277. for cp in checkpoints:
  278. trainer.save_checkpoint(cp, extra_state)
  279. if not end_of_epoch and args.keep_interval_updates > 0:
  280. # remove old checkpoints; checkpoints are sorted in descending order
  281. checkpoints = utils.checkpoint_paths(args.save_dir, pattern=r'checkpoint_\d+_(\d+)\.pt')
  282. for old_chk in checkpoints[args.keep_interval_updates:]:
  283. if os.path.lexists(old_chk):
  284. os.remove(old_chk)
  285. if args.keep_last_epochs > 0:
  286. # remove old epoch checkpoints; checkpoints are sorted in descending order
  287. checkpoints = utils.checkpoint_paths(args.save_dir, pattern=r'checkpoint\d+\.pt')
  288. for old_chk in checkpoints[args.keep_last_epochs:]:
  289. if os.path.lexists(old_chk):
  290. os.remove(old_chk)
  291. def load_checkpoint(args, trainer, epoch_itr):
  292. """Load a checkpoint and replay dataloader to match."""
  293. os.makedirs(args.save_dir, exist_ok=True)
  294. if os.path.isabs(args.restore_file):
  295. checkpoint_path = args.restore_file
  296. else:
  297. checkpoint_path = os.path.join(args.save_dir, args.restore_file)
  298. if os.path.isfile(checkpoint_path):
  299. extra_state = trainer.load_checkpoint(checkpoint_path, args.reset_optimizer, args.reset_lr_scheduler,
  300. eval(args.optimizer_overrides))
  301. if extra_state is not None:
  302. # replay train iterator to match checkpoint
  303. epoch_itr.load_state_dict(extra_state['train_iterator'])
  304. print('| loaded checkpoint {} (epoch {} @ {} updates)'.format(
  305. checkpoint_path, epoch_itr.epoch, trainer.get_num_updates()))
  306. trainer.lr_step(epoch_itr.epoch)
  307. trainer.lr_step_update(trainer.get_num_updates())
  308. if 'best' in extra_state:
  309. save_checkpoint.best = extra_state['best']
  310. return True
  311. else:
  312. print('| no existing checkpoint found {}'.format(checkpoint_path))
  313. return False
  314. def load_dataset_splits(task, splits):
  315. for split in splits:
  316. if split == 'train':
  317. task.load_dataset(split, combine=True)
  318. else:
  319. for k in itertools.count():
  320. split_k = split + (str(k) if k > 0 else '')
  321. try:
  322. task.load_dataset(split_k, combine=False)
  323. except FileNotFoundError as e:
  324. if k > 0:
  325. break
  326. raise e
  327. def distributed_main(i, args):
  328. args.device_id = i
  329. if args.distributed_rank is None: # torch.multiprocessing.spawn
  330. args.distributed_rank = i
  331. main(args, init_distributed=True)
  332. def cli_main():
  333. parser = options.get_training_parser()
  334. args = options.parse_args_and_arch(parser)
  335. if args.distributed_init_method is None:
  336. distributed_utils.infer_init_method(args)
  337. if args.distributed_init_method is not None:
  338. # distributed training
  339. distributed_main(args.device_id, args)
  340. elif args.distributed_world_size > 1:
  341. # fallback for single node with multiple GPUs
  342. port = random.randint(10000, 20000)
  343. args.distributed_init_method = 'tcp://localhost:{port}'.format(port=port)
  344. args.distributed_rank = None # set based on device id
  345. print(
  346. '''| NOTE: you may get better performance with:
  347. python -m torch.distributed.launch --nproc_per_node {ngpu} train.py {no_c10d}(...)
  348. '''.format(
  349. ngpu=args.distributed_world_size,
  350. no_c10d=(
  351. '--ddp-backend=no_c10d ' if max(args.update_freq) > 1 and args.ddp_backend != 'no_c10d'
  352. else ''
  353. ),
  354. )
  355. )
  356. torch.multiprocessing.spawn(
  357. fn=distributed_main,
  358. args=(args, ),
  359. nprocs=args.distributed_world_size,
  360. )
  361. else:
  362. # single GPU training
  363. main(args)
  364. if __name__ == '__main__':
  365. cli_main()
Tip!

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

Comments

Loading...