-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainer.py
740 lines (642 loc) · 28.3 KB
/
trainer.py
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
import copy
import functools
import os
import blobfile as bf
import numpy as np
import torch
import torch.distributed as dist
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
from torch.optim import AdamW
from src.utils import dist_util, logger
from src.utils.fp16_util import (
make_master_params,
master_params_to_model_params,
model_grads_to_master_grads,
unflatten_master_params,
zero_grad,
)
from src.modeling.diffusion.nn import update_ema
from src.modeling.diffusion.resample import LossAwareSampler, UniformSampler
# For ImageNet experiments, this was a good default value.
# We found that the lg_loss_scale quickly climbed to
# 20-21 within the first ~1K steps of training.
INITIAL_LOG_LOSS_SCALE = 20.0
class Trainer:
def __init__(
self,
*,
model,
diffusion,
data,
batch_size,
microbatch,
lr,
ema_rate,
log_interval,
save_interval,
resume_checkpoint,
use_fp16=False,
fp16_scale_growth=1e-3,
schedule_sampler=None,
weight_decay=0.0,
lr_anneal_steps=0,
checkpoint_path='',
gradient_clipping=-1.,
eval_data=None,
eval_interval=-1,
warmup=None,
dae=False,
gamma_nll=0.01
):
self.model = model
self.diffusion = diffusion
self.data = data
self.eval_data = eval_data
self.batch_size = batch_size
self.microbatch = microbatch if microbatch > 0 else batch_size
self.lr = lr
self.gamma_nll = gamma_nll
self.dae = dae
self.ema_rate = (
[ema_rate]
if isinstance(ema_rate, float)
else [float(x) for x in ema_rate.split(",")]
)
self.log_interval = log_interval
self.eval_interval = eval_interval
self.save_interval = save_interval
self.resume_checkpoint = resume_checkpoint
self.use_fp16 = use_fp16
self.fp16_scale_growth = fp16_scale_growth
self.schedule_sampler = schedule_sampler or UniformSampler(diffusion)
self.weight_decay = weight_decay
self.lr_anneal_steps = lr_anneal_steps
self.gradient_clipping = gradient_clipping
self.warmup = warmup
self.step = 0
self.resume_step = 0
self.global_batch = self.batch_size * dist.get_world_size()
self.model_params = list(self.model.parameters())
self.master_params = self.model_params
self.state_dict = self.model.state_dict()
self.lg_loss_scale = INITIAL_LOG_LOSS_SCALE
self.sync_cuda = torch.cuda.is_available()
self.checkpoint_path = checkpoint_path # DEBUG **
self._load_and_sync_parameters()
if self.use_fp16:
self._setup_fp16()
# self.opt = AdamW(self.master_params, lr=self.lr, weight_decay=self.weight_decay)
self.opt = AdamW(filter(lambda p: p.requires_grad, self.master_params),
lr=self.lr, weight_decay=self.weight_decay)
if self.resume_step:
self._load_optimizer_state()
self.ema_params = [
self._load_ema_parameters(rate) for rate in self.ema_rate
]
else:
self.ema_params = [
copy.deepcopy(self.master_params) for _ in range(len(self.ema_rate))
]
if torch.cuda.is_available(): # DEBUG **
self.use_ddp = True
self.ddp_model = DDP(
self.model,
device_ids=[dist_util.dev()],
output_device=dist_util.dev(),
broadcast_buffers=False,
bucket_cap_mb=128,
find_unused_parameters=False,
)
else:
if dist.get_world_size() > 1:
logger.warn(
"Distributed training requires CUDA. "
"Gradients will not be synchronized properly!"
)
self.use_ddp = False
self.ddp_model = self.model
def _load_and_sync_parameters(self):
resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
if resume_checkpoint:
self.resume_step = parse_resume_step_from_filename(resume_checkpoint)
if dist.get_rank() == 0:
logger.log(f"loading model from checkpoint: {resume_checkpoint}...")
self.model.load_state_dict(
dist_util.load_state_dict(
resume_checkpoint, map_location=dist_util.dev()
)
)
dist_util.sync_params(self.model.parameters())
def _load_ema_parameters(self, rate):
ema_params = copy.deepcopy(self.master_params)
main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
ema_checkpoint = find_ema_checkpoint(main_checkpoint, self.resume_step, rate)
if ema_checkpoint:
if dist.get_rank() == 0:
logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...")
state_dict = dist_util.load_state_dict(
ema_checkpoint, map_location=dist_util.dev()
)
ema_params = self._state_dict_to_master_params(state_dict)
dist_util.sync_params(ema_params)
return ema_params
def _load_optimizer_state(self):
main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
opt_checkpoint = bf.join(
bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt"
)
if bf.exists(opt_checkpoint):
logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
state_dict = dist_util.load_state_dict(
opt_checkpoint, map_location=dist_util.dev()
)
self.opt.load_state_dict(state_dict)
def _setup_fp16(self):
self.master_params = make_master_params(self.model_params)
self.model.convert_to_fp16()
def run_loop(self):
while (
not self.lr_anneal_steps
or self.step + self.resume_step < self.lr_anneal_steps
):
batch, cond = next(self.data)
self.run_step(batch, cond)
if self.step % self.log_interval == 0:
logger.dumpkvs()
if self.eval_data is not None and self.step % self.eval_interval == 1:
batch_eval, cond_eval = next(self.eval_data)
self.forward_only(batch_eval, cond_eval)
print('diffu_eval on validation set')
logger.dumpkvs()
if self.step % self.save_interval == 0:
self.save()
if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0:
return
self.step += 1
# Save the last checkpoint if it wasn't already saved.
if (self.step - 1) % self.save_interval != 0:
self.save()
def run_step(self, batch, cond):
self.forward_backward(batch, cond)
if self.use_fp16:
self.optimize_fp16()
else:
self.optimize_normal()
self.log_step()
def forward_only(self, batch, cond):
batch_size = batch['input_ids'].shape[0]
with torch.no_grad():
zero_grad(self.model_params)
for i in range(0, batch_size, self.microbatch):
micro = {key: item[i : i + self.microbatch].to(dist_util.dev()) for key, item in batch.items()}
if cond == None:
micro_cond = None
else:
micro_cond = {
k: v[i : i + self.microbatch].to(dist_util.dev())
for k, v in cond.items()
}
last_batch = (i + self.microbatch) >= batch_size
t, weights = self.schedule_sampler.sample(micro['input_ids'].shape[0], dist_util.dev())
compute_losses = functools.partial(
self.diffusion.training_losses,
self.ddp_model,
self.step,
t,
model_kwargs=micro,
dae=self.dae
)
if last_batch or not self.use_ddp:
losses, anchor_loss = compute_losses()
else:
with self.ddp_model.no_sync():
losses, anchor_loss = compute_losses()
# log_loss_dict(
# self.diffusion, t, {f"eval_{k}": v * weights for k, v in losses.items()}
# )
logger.logkv_mean("eval_anchor_loss", anchor_loss.item())
logger.logkv_mean("eval_mse", (losses["mse"] * weights).mean().item())
logger.logkv_mean("eval_loss_sds", (losses["loss"] * weights).mean().item())
def forward_backward(self, batch, cond):
# print(batch)
batch_size = batch['input_ids'].shape[0]
zero_grad(self.model_params)
for i in range(0, batch_size, self.microbatch):
micro = {key: item[i : i + self.microbatch].to(dist_util.dev()) for key, item in batch.items()}
if cond == None:
micro_cond = None
else:
micro_cond = {
k: v[i : i + self.microbatch].to(dist_util.dev())
for k, v in cond.items()
}
last_batch = (i + self.microbatch) >= batch_size
t, weights = self.schedule_sampler.sample(micro['input_ids'].shape[0], dist_util.dev())
compute_losses = functools.partial(
self.diffusion.training_losses,
self.ddp_model,
self.step,
t,
model_kwargs=micro,
dae=self.dae
)
if last_batch or not self.use_ddp:
losses, anchor_loss = compute_losses()
else:
with self.ddp_model.no_sync():
losses, anchor_loss = compute_losses()
# if isinstance(self.schedule_sampler, LossAwareSampler):
# self.schedule_sampler.update_with_local_losses(
# t, losses["loss"].detach()
# )
# loss = (losses["loss"] * weights).mean()
if isinstance(self.schedule_sampler, LossAwareSampler):
self.schedule_sampler.update_with_local_losses(
t, losses["mse"].detach()
)
loss = (losses["mse_tT"] * weights).mean() + self.gamma_nll * anchor_loss
# log_loss_dict(
# self.diffusion, t, {k: v * weights for k, v in losses.items()}
# )
logger.logkv_mean("anchor_loss", anchor_loss.item())
logger.logkv_mean("mse", (losses["mse"] * weights).mean().item())
logger.logkv_mean("loss_sds", (losses["loss"] * weights).mean().item())
if self.use_fp16:
loss_scale = 2 ** self.lg_loss_scale
(loss * loss_scale).backward()
else:
loss.backward()
def optimize_fp16(self):
if any(not torch.isfinite(p.grad).all() for p in self.model_params):
self.lg_loss_scale -= 1
logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}")
return
model_grads_to_master_grads(self.model_params, self.master_params)
self.master_params[0].grad.mul_(1.0 / (2 ** self.lg_loss_scale))
self._log_grad_norm()
self._anneal_lr()
self.opt.step()
for rate, params in zip(self.ema_rate, self.ema_params):
update_ema(params, self.master_params, rate=rate)
master_params_to_model_params(self.model_params, self.master_params)
self.lg_loss_scale += self.fp16_scale_growth
def grad_clip(self):
# print('doing gradient clipping')
max_grad_norm=self.gradient_clipping #3.0
if hasattr(self.opt, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.opt.clip_grad_norm(max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
torch.nn.utils.clip_grad_norm_(
self.model.parameters(), #amp.master_params(self.opt) if self.use_apex else
max_grad_norm,
)
def optimize_normal(self):
if self.gradient_clipping > 0:
self.grad_clip()
self._log_grad_norm()
self._anneal_lr()
self.opt.step()
for rate, params in zip(self.ema_rate, self.ema_params):
update_ema(params, self.master_params, rate=rate)
def _log_grad_norm(self):
sqsum = 0.0
for p in self.master_params:
if p.grad is not None:
sqsum += (p.grad ** 2).sum().item()
logger.logkv_mean("grad_norm", np.sqrt(sqsum))
def _anneal_lr(self):
if not self.lr_anneal_steps:
return
if self.warmup is not None and self.warmup > 0:
warmup_frac = (self.step + self.resume_step) / self.warmup
frac_done = (self.step + self.resume_step - self.warmup) / (self.lr_anneal_steps - self.warmup)
lr = self.lr * min(1, warmup_frac) * min(1-frac_done, 1)
else:
frac_done = (self.step + self.resume_step) / self.lr_anneal_steps
lr = self.lr * (1 - frac_done)
for param_group in self.opt.param_groups:
param_group["lr"] = lr
def log_step(self):
logger.logkv("step", self.step + self.resume_step)
logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch)
if self.use_fp16:
logger.logkv("lg_loss_scale", self.lg_loss_scale)
def save(self):
def save_checkpoint(rate, params):
self._master_params_to_state_dict(params)
if dist.get_rank() == 0:
logger.log(f"saving model {rate}...")
if not rate:
filename = f"model{(self.step+self.resume_step):06d}.pt"
else:
filename = f"ema_{rate}_{(self.step+self.resume_step):06d}.pt"
print('writing to', bf.join(get_blob_logdir(), filename))
print('writing to', bf.join(self.checkpoint_path, filename))
# with bf.BlobFile(bf.join(get_blob_logdir(), filename), "wb") as f:
# torch.save(state_dict, f)
with bf.BlobFile(bf.join(self.checkpoint_path, filename), "wb") as f: # DEBUG **
torch.save(self.state_dict, f)
save_checkpoint(0, self.master_params)
for rate, params in zip(self.ema_rate, self.ema_params):
save_checkpoint(rate, params)
dist.barrier()
def _master_params_to_state_dict(self, master_params):
if self.use_fp16:
master_params = unflatten_master_params(
list(self.model.parameters()), master_params # DEBUG **
)
self.state_dict = self.model.state_dict()
for i, (name, _value) in enumerate(self.model.named_parameters()):
assert name in self.state_dict
self.state_dict[name] = master_params[i]
# return self.state_dict
def _state_dict_to_master_params(self, state_dict):
params = [state_dict[name] for name, _ in self.model.named_parameters()]
if self.use_fp16:
return make_master_params(params)
else:
return params
def parse_resume_step_from_filename(filename):
"""
Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the
checkpoint's number of steps.
"""
split = filename.split("model")
if len(split) < 2:
return 0
split1 = split[-1].split(".")[0]
try:
return int(split1)
except ValueError:
return 0
def get_blob_logdir():
return os.environ.get("DIFFUSION_BLOB_LOGDIR", logger.get_dir())
def find_resume_checkpoint():
# On your infrastructure, you may want to override this to automatically
# discover the latest checkpoint on your blob storage, etc.
return None
def find_ema_checkpoint(main_checkpoint, step, rate):
if main_checkpoint is None:
return None
filename = f"ema_{rate}_{(step):06d}.pt"
path = bf.join(bf.dirname(main_checkpoint), filename)
if bf.exists(path):
return path
return None
def log_loss_dict(diffusion, ts, losses):
for key, values in losses.items():
logger.logkv_mean(key, values.mean().item())
# Log the quantiles (four quartiles, in particular).
for sub_t, sub_loss in zip(ts.cpu().numpy(), values.detach().cpu().numpy()):
quartile = int(4 * sub_t / diffusion.num_timesteps)
logger.logkv_mean(f"{key}_q{quartile}", sub_loss)
class Trainer_PTE:
def __init__(
self,
*,
model,
data,
batch_size,
microbatch,
lr,
log_interval,
save_interval,
resume_checkpoint,
use_fp16=False,
fp16_scale_growth=1e-3,
weight_decay=0.0,
lr_anneal_steps=0,
checkpoint_path='',
gradient_clipping=-1.,
eval_data=None,
eval_interval=-1,
warmup=None,
dae=False
):
self.model = model
self.data = data
self.eval_data = eval_data
self.batch_size = batch_size
self.microbatch = microbatch if microbatch > 0 else batch_size
self.lr = lr
self.dae = dae
self.log_interval = log_interval
self.eval_interval = eval_interval
self.save_interval = save_interval
self.resume_checkpoint = resume_checkpoint
self.use_fp16 = use_fp16
self.fp16_scale_growth = fp16_scale_growth
self.weight_decay = weight_decay
self.lr_anneal_steps = lr_anneal_steps
self.gradient_clipping = gradient_clipping
self.warmup = warmup
self.step = 0
self.resume_step = 0
self.global_batch = self.batch_size * dist.get_world_size()
self.model_params = list(self.model.parameters())
self.master_params = self.model_params
self.state_dict = self.model.state_dict()
self.lg_loss_scale = INITIAL_LOG_LOSS_SCALE
self.sync_cuda = torch.cuda.is_available()
self.checkpoint_path = checkpoint_path # DEBUG **
self._load_and_sync_parameters()
if self.use_fp16:
self._setup_fp16()
self.opt = AdamW(self.master_params, lr=self.lr, weight_decay=self.weight_decay)
if self.resume_step:
self._load_optimizer_state()
if torch.cuda.is_available(): # DEBUG **
self.use_ddp = True
self.ddp_model = DDP(
self.model,
device_ids=[dist_util.dev()],
output_device=dist_util.dev(),
broadcast_buffers=False,
bucket_cap_mb=128,
find_unused_parameters=False,
)
else:
if dist.get_world_size() > 1:
logger.warn(
"Distributed training requires CUDA. "
"Gradients will not be synchronized properly!"
)
self.use_ddp = False
self.ddp_model = self.model
def _load_and_sync_parameters(self):
resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
if resume_checkpoint:
self.resume_step = parse_resume_step_from_filename(resume_checkpoint)
if dist.get_rank() == 0:
logger.log(f"loading model from checkpoint: {resume_checkpoint}...")
self.model.load_state_dict(
dist_util.load_state_dict(
resume_checkpoint, map_location=dist_util.dev()
)
)
dist_util.sync_params(self.model.parameters())
def _load_optimizer_state(self):
main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
opt_checkpoint = bf.join(
bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt"
)
if bf.exists(opt_checkpoint):
logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
state_dict = dist_util.load_state_dict(
opt_checkpoint, map_location=dist_util.dev()
)
self.opt.load_state_dict(state_dict)
def _setup_fp16(self):
self.master_params = make_master_params(self.model_params)
self.model.convert_to_fp16()
def run_loop(self):
while (
not self.lr_anneal_steps
or self.step + self.resume_step < self.lr_anneal_steps
):
batch, _ = next(self.data)
self.run_step(batch)
if self.step % self.log_interval == 0:
logger.dumpkvs()
if self.eval_data is not None and self.step % self.eval_interval == 1:
batch_eval, _ = next(self.eval_data)
self.forward_only(batch_eval)
print('diffu_eval on validation set')
logger.dumpkvs()
if self.step % self.save_interval == 0:
self.save()
if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0:
return
self.step += 1
# Save the last checkpoint if it wasn't already saved.
if (self.step - 1) % self.save_interval != 0:
self.save()
def run_step(self, batch):
self.forward_backward(batch)
if self.use_fp16:
self.optimize_fp16()
else:
self.optimize_normal()
self.log_step()
def forward_only(self, batch):
batch_size = batch['input_ids'].shape[0]
with torch.no_grad():
zero_grad(self.model_params)
for i in range(0, batch_size, self.microbatch):
micro = {key: item[i: i + self.microbatch].to(dist_util.dev()) for key, item in batch.items()}
last_batch = (i + self.microbatch) >= batch_size
if last_batch or not self.use_ddp:
loss, _ = self.ddp_model.module.forward(input_ids=micro["input_ids"],
attention_mask=micro["attention_mask"],
decoder_input_ids=micro["decoder_input_ids"],
labels=micro["labels"],
dae=self.dae)
else:
with self.ddp_model.no_sync():
loss, _ = self.ddp_model.module.forward(input_ids=micro["input_ids"],
attention_mask=micro["attention_mask"],
decoder_input_ids=micro["decoder_input_ids"],
labels=micro["labels"],
dae=self.dae)
logger.logkv_mean("loss", loss.item())
def forward_backward(self, batch):
# print(batch)
batch_size = batch['input_ids'].shape[0]
zero_grad(self.model_params)
for i in range(0, batch_size, self.microbatch):
micro = {key: item[i: i + self.microbatch].to(dist_util.dev()) for key, item in batch.items()}
last_batch = (i + self.microbatch) >= batch_size
if last_batch or not self.use_ddp:
loss, _ = self.ddp_model.module.forward(input_ids=micro["input_ids"],
attention_mask=micro["attention_mask"],
decoder_input_ids=micro["decoder_input_ids"],
labels=micro["labels"],
dae=self.dae)
else:
with self.ddp_model.no_sync():
loss, _ = self.ddp_model.module.forward(input_ids=micro["input_ids"],
attention_mask=micro["attention_mask"],
decoder_input_ids=micro["decoder_input_ids"],
labels=micro["labels"],
dae=self.dae)
logger.logkv_mean("loss", loss.item())
if self.use_fp16:
loss_scale = 2 ** self.lg_loss_scale
(loss * loss_scale).backward()
else:
loss.backward()
def optimize_fp16(self):
if any(not torch.isfinite(p.grad).all() for p in self.model_params):
self.lg_loss_scale -= 1
logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}")
return
model_grads_to_master_grads(self.model_params, self.master_params)
self.master_params[0].grad.mul_(1.0 / (2 ** self.lg_loss_scale))
self._anneal_lr()
self.opt.step()
master_params_to_model_params(self.model_params, self.master_params)
self.lg_loss_scale += self.fp16_scale_growth
def grad_clip(self):
# print('doing gradient clipping')
max_grad_norm = self.gradient_clipping # 3.0
if hasattr(self.opt, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.opt.clip_grad_norm(max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
torch.nn.utils.clip_grad_norm_(
self.model.parameters(), # amp.master_params(self.opt) if self.use_apex else
max_grad_norm,
)
def optimize_normal(self):
if self.gradient_clipping > 0:
self.grad_clip()
self._anneal_lr()
self.opt.step()
def _anneal_lr(self):
if not self.lr_anneal_steps:
return
if self.warmup is not None and self.warmup > 0:
warmup_frac = (self.step + self.resume_step) / self.warmup
frac_done = (self.step + self.resume_step - self.warmup) / (self.lr_anneal_steps - self.warmup)
lr = self.lr * min(1, warmup_frac) * min(1 - frac_done, 1)
else:
frac_done = (self.step + self.resume_step) / self.lr_anneal_steps
lr = self.lr * (1 - frac_done)
for param_group in self.opt.param_groups:
param_group["lr"] = lr
def log_step(self):
logger.logkv("step", self.step + self.resume_step)
logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch)
if self.use_fp16:
logger.logkv("lg_loss_scale", self.lg_loss_scale)
def save(self):
self._master_params_to_state_dict(self.master_params)
if dist.get_rank() == 0:
logger.log(f"saving model state dict...")
filename = f"model{(self.step + self.resume_step):06d}.pt"
with bf.BlobFile(bf.join(self.checkpoint_path, filename), "wb") as f: # DEBUG **
torch.save(self.state_dict, f)
logger.log(f"saving pretrained model...")
model_to_save = self.ddp_model.module if hasattr(self.ddp_model, "module") else self.ddp_model
dict_name = f"model{(self.step + self.resume_step):06d}"
model_to_save.embedder.save_pretrained(os.path.join(self.checkpoint_path, dict_name))
dist.barrier()
def _master_params_to_state_dict(self, master_params):
if self.use_fp16:
master_params = unflatten_master_params(
list(self.model.parameters()), master_params # DEBUG **
)
self.state_dict = self.model.state_dict()
for i, (name, _value) in enumerate(self.model.named_parameters()):
assert name in self.state_dict
self.state_dict[name] = master_params[i]
# return self.state_dict
def _state_dict_to_master_params(self, state_dict):
params = [state_dict[name] for name, _ in self.model.named_parameters()]
if self.use_fp16:
return make_master_params(params)
else:
return params