(self, args)
| 69 | self.scheduler = scheduler |
| 70 | |
| 71 | def train(self, args): |
| 72 | |
| 73 | ngpus_per_node = torch.cuda.device_count() |
| 74 | |
| 75 | # EMA init |
| 76 | self.model.train() |
| 77 | self.ema = EMA(self.model, self.ema_m) |
| 78 | self.ema.register() |
| 79 | if args.resume == True: |
| 80 | self.ema.load(self.ema_model) |
| 81 | |
| 82 | # for gpu profiling |
| 83 | start_batch = torch.cuda.Event(enable_timing=True) |
| 84 | end_batch = torch.cuda.Event(enable_timing=True) |
| 85 | start_run = torch.cuda.Event(enable_timing=True) |
| 86 | end_run = torch.cuda.Event(enable_timing=True) |
| 87 | |
| 88 | start_batch.record() |
| 89 | best_eval_acc, best_it = 0.0, 0 |
| 90 | |
| 91 | scaler = GradScaler() |
| 92 | amp_cm = autocast if args.amp else contextlib.nullcontext |
| 93 | |
| 94 | # eval for once to verify if the checkpoint is loaded correctly |
| 95 | if args.resume == True: |
| 96 | eval_dict = self.evaluate(args=args) |
| 97 | print(eval_dict) |
| 98 | |
| 99 | selected_label = torch.ones((len(self.ulb_dset),), dtype=torch.long, ) * -1 |
| 100 | selected_label = selected_label.cuda(args.gpu) |
| 101 | classwise_acc = torch.zeros((args.num_classes,)).cuda(args.gpu) |
| 102 | |
| 103 | for (_, x_lb, y_lb), (x_ulb_idx, x_ulb_w) in zip(self.loader_dict['train_lb'], self.loader_dict['train_ulb']): |
| 104 | |
| 105 | # prevent the training iterations exceed args.num_train_iter |
| 106 | if self.it > args.num_train_iter: |
| 107 | break |
| 108 | unsup_warmup = np.clip(self.it / (args.unsup_warmup_pos * args.num_train_iter), |
| 109 | a_min=0.0, a_max=1.0) |
| 110 | end_batch.record() |
| 111 | torch.cuda.synchronize() |
| 112 | start_run.record() |
| 113 | |
| 114 | x_lb, x_ulb_w = x_lb.cuda(args.gpu), x_ulb_w.cuda(args.gpu) |
| 115 | x_ulb_idx = x_ulb_idx.cuda(args.gpu) |
| 116 | y_lb = y_lb.cuda(args.gpu) |
| 117 | |
| 118 | num_lb = x_lb.shape[0] |
| 119 | if args.use_flex: |
| 120 | pseudo_counter = Counter(selected_label.tolist()) |
| 121 | if max(pseudo_counter.values()) < len(self.ulb_dset): # not all(5w) -1 |
| 122 | for i in range(args.num_classes): |
| 123 | classwise_acc[i] = pseudo_counter[i] / max(pseudo_counter.values()) |
| 124 | |
| 125 | # inference and calculate sup/unsup losses |
| 126 | with amp_cm(): |
| 127 | |
| 128 | logits_x_lb = self.model(x_lb) |
no test coverage detected