MCPcopy Create free account
hub / github.com/CHENGY12/PLOT / PLOT

Class PLOT

plot-coop/trainers/plot.py:286–405  ·  view source on GitHub ↗

It is based on CoOp.

Source from the content-addressed store, hash-verified

284
285@TRAINER_REGISTRY.register()
286class PLOT(TrainerX):
287 """
288 It is based on CoOp.
289 """
290
291 def check_cfg(self, cfg):
292 assert cfg.TRAINER.PLOT.PREC in ["fp16", "fp32", "amp"]
293
294 def build_model(self):
295 cfg = self.cfg
296 classnames = self.dm.dataset.classnames
297
298 print(f"Loading CLIP (backbone: {cfg.MODEL.BACKBONE.NAME})")
299 clip_model = load_clip_to_cpu(cfg)
300
301 if cfg.TRAINER.PLOT.PREC == "fp32" or cfg.TRAINER.PLOT.PREC == "amp":
302 # CLIP's default precision is fp16
303 clip_model.float()
304
305 print("Building custom CLIP")
306 self.model = CustomCLIP(cfg, classnames, clip_model)
307
308 print("Turning off gradients in both the image and the text encoder")
309 for name, param in self.model.named_parameters():
310 if "prompt_learner" not in name:
311 param.requires_grad_(False)
312
313 if cfg.MODEL.INIT_WEIGHTS:
314 load_pretrained_weights(self.model.prompt_learner, cfg.MODEL.INIT_WEIGHTS)
315
316 if cfg.DATASET.NAME== "ImageNet":
317 self.device = torch.device("cuda:0")
318 # device0 = torch.device("cuda:0")
319 device1 = torch.device("cuda")
320 self.model.to(self.device)
321 self.model.text_encoder.to(device1)
322 self.model.text_encoder=nn.DataParallel(self.model.text_encoder)
323 else:
324 self.model.to(self.device)
325
326 # NOTE: only give prompt_learner to the optimizer
327 self.optim = build_optimizer(self.model.prompt_learner, cfg.OPTIM)
328 self.sched = build_lr_scheduler(self.optim, cfg.OPTIM)
329 self.register_model("prompt_learner", self.model.prompt_learner, self.optim, self.sched)
330
331 self.scaler = GradScaler() if cfg.TRAINER.PLOT.PREC == "amp" else None
332
333 # Note that multi-gpu training could be slow because CLIP's size is
334 # big, which slows down the copy operation in DataParallel
335 # device_count = torch.cuda.device_count()
336 # if device_count > 1:
337 # print(f"Multiple GPUs detected (n_gpus={device_count}), use all of them!")
338 # self.model = nn.DataParallel(self.model)
339
340 def forward_backward(self, batch):
341 image, label = self.parse_batch_train(batch)
342
343 prec = self.cfg.TRAINER.PLOT.PREC

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected