(self, args)
| 66 | self.scheduler = scheduler |
| 67 | |
| 68 | def train(self, args): |
| 69 | |
| 70 | ngpus_per_node = torch.cuda.device_count() |
| 71 | |
| 72 | # EMA init |
| 73 | self.model.train() |
| 74 | self.ema = EMA(self.model, self.ema_m) |
| 75 | self.ema.register() |
| 76 | if args.resume == True: |
| 77 | self.ema.load(self.ema_model) |
| 78 | |
| 79 | # for gpu profiling |
| 80 | start_batch = torch.cuda.Event(enable_timing=True) |
| 81 | end_batch = torch.cuda.Event(enable_timing=True) |
| 82 | start_run = torch.cuda.Event(enable_timing=True) |
| 83 | end_run = torch.cuda.Event(enable_timing=True) |
| 84 | |
| 85 | start_batch.record() |
| 86 | best_eval_acc, best_it = 0.0, 0 |
| 87 | |
| 88 | scaler = GradScaler() |
| 89 | amp_cm = autocast if args.amp else contextlib.nullcontext |
| 90 | |
| 91 | # eval for once to verify if the checkpoint is loaded correctly |
| 92 | if args.resume == True: |
| 93 | eval_dict = self.evaluate(args=args) |
| 94 | print(eval_dict) |
| 95 | |
| 96 | for (_, x_lb, y_lb), (_, x_ulb_w) in zip(self.loader_dict['train_lb'], self.loader_dict['train_ulb']): |
| 97 | |
| 98 | # prevent the training iterations exceed args.num_train_iter |
| 99 | if self.it > args.num_train_iter: |
| 100 | break |
| 101 | unsup_warmup = np.clip(self.it / (args.unsup_warmup_pos * args.num_train_iter), |
| 102 | a_min=0.0, a_max=1.0) |
| 103 | end_batch.record() |
| 104 | torch.cuda.synchronize() |
| 105 | start_run.record() |
| 106 | |
| 107 | x_lb, x_ulb_w = x_lb.cuda(args.gpu), x_ulb_w.cuda(args.gpu) |
| 108 | y_lb = y_lb.cuda(args.gpu) |
| 109 | |
| 110 | num_lb = x_lb.shape[0] |
| 111 | # inference and calculate sup/unsup losses |
| 112 | with amp_cm(): |
| 113 | |
| 114 | logits_x_lb = self.model(x_lb) |
| 115 | |
| 116 | sup_loss = ce_loss(logits_x_lb, y_lb, reduction='mean') |
| 117 | self.bn_controller.freeze_bn(self.model) |
| 118 | ul_y = self.model(x_ulb_w) |
| 119 | unsup_loss = vat_loss(self.model, x_ulb_w, ul_y, eps=args.vat_eps) |
| 120 | loss_entmin = entropy_loss(ul_y) |
| 121 | self.bn_controller.unfreeze_bn(self.model) |
| 122 | total_loss = sup_loss + self.lambda_u * unsup_loss * unsup_warmup + args.entmin_weight * loss_entmin |
| 123 | |
| 124 | # parameter updates |
| 125 | if args.amp: |
no test coverage detected