(self, args)
| 65 | self.scheduler = scheduler |
| 66 | |
| 67 | def train(self, args): |
| 68 | |
| 69 | ngpus_per_node = torch.cuda.device_count() |
| 70 | |
| 71 | # lb: labeled, ulb: unlabeled |
| 72 | self.model.train() |
| 73 | self.ema = EMA(self.model, self.ema_m) |
| 74 | self.ema.register() |
| 75 | if args.resume == True: |
| 76 | self.ema.load(self.ema_model) |
| 77 | |
| 78 | # for gpu profiling |
| 79 | start_batch = torch.cuda.Event(enable_timing=True) |
| 80 | end_batch = torch.cuda.Event(enable_timing=True) |
| 81 | start_run = torch.cuda.Event(enable_timing=True) |
| 82 | end_run = torch.cuda.Event(enable_timing=True) |
| 83 | |
| 84 | start_batch.record() |
| 85 | best_eval_acc, best_it = 0.0, 0 |
| 86 | |
| 87 | scaler = GradScaler() |
| 88 | amp_cm = autocast if args.amp else contextlib.nullcontext |
| 89 | |
| 90 | # eval for once to verify if the checkpoint is loaded correctly |
| 91 | if args.resume == True: |
| 92 | eval_dict = self.evaluate(args=args) |
| 93 | print(eval_dict) |
| 94 | |
| 95 | for (_, x_lb, y_lb), (_, x_ulb_w1, x_ulb_w2) in zip(self.loader_dict['train_lb'], |
| 96 | 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_w1, x_ulb_w2 = x_lb.cuda(args.gpu), x_ulb_w1.cuda(args.gpu), x_ulb_w2.cuda(args.gpu) |
| 108 | y_lb = y_lb.cuda(args.gpu) |
| 109 | |
| 110 | num_lb = x_lb.shape[0] |
| 111 | |
| 112 | # inference and calculate sup/unsup losses |
| 113 | with amp_cm(): |
| 114 | |
| 115 | logits_x_lb = self.model(x_lb) |
| 116 | |
| 117 | # calculate BN only for the first batch |
| 118 | self.bn_controller.freeze_bn(self.model) |
| 119 | logits_x_ulb_w1 = self.model(x_ulb_w1) |
| 120 | logits_x_ulb_w2 = self.model(x_ulb_w2) |
| 121 | |
| 122 | self.bn_controller.unfreeze_bn(self.model) |
| 123 | |
| 124 | sup_loss = ce_loss(logits_x_lb, y_lb, reduction='mean') |
no test coverage detected