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

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

Comments

Loading...