(
args,
model,
accelerator,
optimizer,
dataloaders,
best_val_metrics,
logger
)
| 30 | |
| 31 | |
| 32 | def do_train( |
| 33 | args, |
| 34 | model, |
| 35 | accelerator, |
| 36 | optimizer, |
| 37 | dataloaders, |
| 38 | best_val_metrics, |
| 39 | logger |
| 40 | ): |
| 41 | |
| 42 | if accelerator.is_main_process: |
| 43 | logger.log_messages(f"call with args: {args}") |
| 44 | logger.log_messages(f"{model}") |
| 45 | |
| 46 | curr_iter = args.start_epoch * len(dataloaders['train']) |
| 47 | max_iters = args.max_epoch * len(dataloaders['train']) |
| 48 | |
| 49 | time_delta = SmoothedValue(window_size=10) |
| 50 | loss_avg = SmoothedValue(window_size=10) |
| 51 | loss_break_down_avg = {} |
| 52 | |
| 53 | model.train() |
| 54 | accelerator.wait_for_everyone() |
| 55 | |
| 56 | for curr_epoch in range(args.start_epoch, args.max_epoch): |
| 57 | |
| 58 | for batch_idx, batch_data_label in enumerate(dataloaders['train']): |
| 59 | |
| 60 | curr_time = time.time() |
| 61 | |
| 62 | ### core for model training |
| 63 | |
| 64 | curr_iter = curr_epoch * len(dataloaders['train']) + batch_idx |
| 65 | curr_lr = adjust_learning_rate(args, optimizer, curr_iter, max_iters) |
| 66 | |
| 67 | with accelerator.accumulate(model): |
| 68 | |
| 69 | with accelerator.autocast(): |
| 70 | outputs = model(batch_data_label) |
| 71 | loss = outputs['loss'] |
| 72 | |
| 73 | # sanity check, skip the infinite loss |
| 74 | if not math.isfinite(loss.item()): |
| 75 | logger.log_messages("Loss in not finite. Skip this iteration.") |
| 76 | model.eval() |
| 77 | model.train() |
| 78 | torch.cuda.empty_cache() |
| 79 | continue |
| 80 | |
| 81 | accelerator.backward(loss) |
| 82 | if args.clip_gradient > 0: |
| 83 | accelerator.clip_grad_norm_(model.parameters(), args.clip_gradient) |
| 84 | |
| 85 | optimizer.step() |
| 86 | optimizer.zero_grad() |
| 87 | |
| 88 | ### logging training loss status |
| 89 |
no test coverage detected