| 62 | self.scheduler = scheduler |
| 63 | |
| 64 | def train(self, args): |
| 65 | |
| 66 | ngpus_per_node = torch.cuda.device_count() |
| 67 | |
| 68 | # lb: labeled, ulb: unlabeled |
| 69 | self.model.train() |
| 70 | self.ema = EMA(self.model, self.ema_m) |
| 71 | self.ema.register() |
| 72 | if args.resume == True: |
| 73 | self.ema.load(self.ema_model) |
| 74 | |
| 75 | # for gpu profiling |
| 76 | start_batch = torch.cuda.Event(enable_timing=True) |
| 77 | end_batch = torch.cuda.Event(enable_timing=True) |
| 78 | start_run = torch.cuda.Event(enable_timing=True) |
| 79 | end_run = torch.cuda.Event(enable_timing=True) |
| 80 | |
| 81 | start_batch.record() |
| 82 | best_eval_acc, best_it = 0.0, 0 |
| 83 | |
| 84 | scaler = GradScaler() |
| 85 | amp_cm = autocast if args.amp else contextlib.nullcontext |
| 86 | |
| 87 | # eval for once to verify if the checkpoint is loaded correctly |
| 88 | if args.resume == True: |
| 89 | eval_dict = self.evaluate(args=args) |
| 90 | print(eval_dict) |
| 91 | |
| 92 | for _, x_lb, y_lb in self.loader_dict['train_lb']: |
| 93 | |
| 94 | # prevent the training iterations exceed args.num_train_iter |
| 95 | if self.it > args.num_train_iter: |
| 96 | break |
| 97 | end_batch.record() |
| 98 | torch.cuda.synchronize() |
| 99 | start_run.record() |
| 100 | |
| 101 | x_lb = x_lb.cuda(args.gpu) |
| 102 | y_lb = y_lb.cuda(args.gpu) |
| 103 | |
| 104 | num_lb = x_lb.shape[0] |
| 105 | |
| 106 | # inference and calculate sup/unsup losses |
| 107 | with amp_cm(): |
| 108 | |
| 109 | logits_x_lb = self.model(x_lb) |
| 110 | |
| 111 | sup_loss = ce_loss(logits_x_lb, y_lb, reduction='mean') |
| 112 | |
| 113 | total_loss = sup_loss |
| 114 | |
| 115 | # parameter updates |
| 116 | if args.amp: |
| 117 | scaler.scale(total_loss).backward() |
| 118 | if (args.clip > 0): |
| 119 | scaler.unscale_(self.optimizer) |
| 120 | torch.nn.utils.clip_grad_norm_(self.model.parameters(), args.clip) |
| 121 | scaler.step(self.optimizer) |