MCPcopy Create free account
hub / github.com/TorchSSL/TorchSSL / train

Method train

models/mixmatch/mixmatch.py:73–239  ·  view source on GitHub ↗
(self, args, logger=None)

Source from the content-addressed store, hash-verified

71 self.scheduler = scheduler
72
73 def train(self, args, logger=None):
74
75 ngpus_per_node = torch.cuda.device_count()
76
77 # EMA init
78 self.model.train()
79 self.ema = EMA(self.model, self.ema_m)
80 self.ema.register()
81 if args.resume == True:
82 self.ema.load(self.ema_model)
83
84 # for gpu profiling
85 start_batch = torch.cuda.Event(enable_timing=True)
86 end_batch = torch.cuda.Event(enable_timing=True)
87 start_run = torch.cuda.Event(enable_timing=True)
88 end_run = torch.cuda.Event(enable_timing=True)
89
90 start_batch.record()
91 best_eval_acc, best_it = 0.0, 0
92
93 scaler = GradScaler()
94 amp_cm = autocast if args.amp else contextlib.nullcontext
95
96 # eval once to verify if the checkpoint is loaded correctly
97 if args.resume == True:
98 eval_dict = self.evaluate(args=args)
99 print(eval_dict)
100
101 for (_, x_lb, y_lb), (_, x_ulb_w1, x_ulb_w2) in zip(self.loader_dict['train_lb'],
102 self.loader_dict['train_ulb']):
103
104 # prevent the training iterations exceed args.num_train_iter
105 if self.it > args.num_train_iter:
106 break
107
108 end_batch.record()
109 torch.cuda.synchronize()
110 start_run.record()
111
112 num_lb = x_lb.shape[0]
113 num_ulb = x_ulb_w1.shape[0]
114 assert num_ulb == x_ulb_w2.shape[0]
115
116 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)
117 y_lb = y_lb.cuda(args.gpu)
118
119 # inference and calculate sup/unsup losses
120 with amp_cm():
121 with torch.no_grad():
122 self.bn_controller.freeze_bn(self.model)
123 logits_x_ulb_w1 = self.model(x_ulb_w1)
124 logits_x_ulb_w2 = self.model(x_ulb_w2)
125 self.bn_controller.unfreeze_bn(self.model)
126 # Temperature sharpening
127 T = self.t_fn(self.it)
128 # avg
129 avg_prob_x_ulb = (torch.softmax(logits_x_ulb_w1, dim=1) + torch.softmax(logits_x_ulb_w2, dim=1)) / 2
130 avg_prob_x_ulb = (avg_prob_x_ulb / avg_prob_x_ulb.sum(dim=-1, keepdim=True))

Callers 2

evaluateMethod · 0.45
save_modelMethod · 0.45

Calls 14

evaluateMethod · 0.95
interleaveMethod · 0.95
save_modelMethod · 0.95
EMAClass · 0.90
ce_lossFunction · 0.90
registerMethod · 0.80
loadMethod · 0.80
freeze_bnMethod · 0.80
unfreeze_bnMethod · 0.80
stepMethod · 0.80
one_hotFunction · 0.70
mixup_one_targetFunction · 0.70

Tested by

no test coverage detected