|
| 1 | +import logging |
| 2 | +import torch |
| 3 | +import torch.nn as nn |
| 4 | +import torchvision.transforms as T |
| 5 | +from timm.models import create_model |
| 6 | + |
| 7 | +_logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | +class build_kd_model(nn.Module): |
| 10 | + def __init__(self, args): |
| 11 | + super(build_kd_model, self).__init__() |
| 12 | + |
| 13 | + _logger.info(f"Creating KD model: from '{args.kd_model_name}'") |
| 14 | + in_chans = 3 |
| 15 | + if args.in_chans is not None: |
| 16 | + in_chans = args.in_chans |
| 17 | + model_kd = create_model( |
| 18 | + model_name=args.kd_model_name, |
| 19 | + num_classes=args.num_classes, |
| 20 | + pretrained=True, |
| 21 | + in_chans=in_chans) |
| 22 | + |
| 23 | + # compile model |
| 24 | + model_kd.cpu().eval() |
| 25 | + try: |
| 26 | + model_kd = torch.compile(model_kd) |
| 27 | + _logger.info(f"torch.compile applied successfully to KD model") |
| 28 | + except Exception as e: |
| 29 | + _logger.warning(f"torch.compile failed with error {e}, continuing KD model without torch compilation") |
| 30 | + |
| 31 | + self.model = model_kd.cuda() |
| 32 | + self.mean_model_kd = model_kd.default_cfg['mean'] |
| 33 | + self.std_model_kd = model_kd.default_cfg['std'] |
| 34 | + |
| 35 | + # handling different normalization of teacher and student |
| 36 | + def normalize_input(self, input, student_model): |
| 37 | + if hasattr(student_model, 'module'): |
| 38 | + model_s = student_model.module |
| 39 | + else: |
| 40 | + model_s = student_model |
| 41 | + |
| 42 | + mean_student = model_s.default_cfg['mean'] |
| 43 | + std_student = model_s.default_cfg['std'] |
| 44 | + |
| 45 | + input_kd = input |
| 46 | + if mean_student != self.mean_model_kd or std_student != self.std_model_kd: |
| 47 | + std = (self.std_model_kd[0] / std_student[0], self.std_model_kd[1] / std_student[1], |
| 48 | + self.std_model_kd[2] / std_student[2]) |
| 49 | + transform_std = T.Normalize(mean=(0, 0, 0), std=std) |
| 50 | + |
| 51 | + mean = (self.mean_model_kd[0] - mean_student[0], self.mean_model_kd[1] - mean_student[1], |
| 52 | + self.mean_model_kd[2] - mean_student[2]) |
| 53 | + transform_mean = T.Normalize(mean=mean, std=(1, 1, 1)) |
| 54 | + |
| 55 | + input_kd = transform_mean(transform_std(input)) |
| 56 | + |
| 57 | + return input_kd |
| 58 | + |
| 59 | + |
| 60 | +def add_kd_loss(_loss, output, input, model, model_kd, args): |
| 61 | + # student probability calculation |
| 62 | + prob_s = torch.nn.functional.log_softmax(output, dim=-1) |
| 63 | + |
| 64 | + # teacher probability calculation |
| 65 | + with torch.no_grad(): |
| 66 | + input_kd = model_kd.normalize_input(input, model) |
| 67 | + out_t = model_kd.model(input_kd.detach()) |
| 68 | + prob_t = torch.nn.functional.softmax(out_t, dim=-1) |
| 69 | + |
| 70 | + # adding KL loss |
| 71 | + if not args.use_kd_only_loss: |
| 72 | + _loss += args.alpha_kd * torch.nn.functional.kl_div(prob_s, prob_t, reduction='batchmean') |
| 73 | + else: # only kd |
| 74 | + _loss = args.alpha_kd * torch.nn.functional.kl_div(prob_s, prob_t, reduction='batchmean') |
| 75 | + |
| 76 | + return _loss |
| 77 | + |
0 commit comments