|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import torch |
|
|
from torch import nn |
|
|
import torch.nn.functional as F |
|
|
import torch.distributed.nn |
|
|
import torch.distributed as dist |
|
|
from torch.nn.init import trunc_normal_ |
|
|
from torch.nn.utils import weight_norm |
|
|
import models_clip |
|
|
|
|
|
|
|
|
|
|
|
class MetaArch(nn.Module): |
|
|
|
|
|
def __init__(self, cfg): |
|
|
super().__init__() |
|
|
self.cfg = cfg |
|
|
|
|
|
student_model_dict = dict() |
|
|
teacher_model_dict = dict() |
|
|
|
|
|
import_student = getattr(models_clip, cfg.target_model) |
|
|
student = import_student() |
|
|
|
|
|
embed_dim = student.embed_dim |
|
|
|
|
|
import_teacher = getattr(models_clip, cfg.teacher_model) |
|
|
teacher_backbone = import_teacher(teacher_path=cfg.teacher_path) |
|
|
teacher_backbone.eval() |
|
|
|
|
|
student_model_dict['backbone'] = student |
|
|
teacher_model_dict['backbone'] = teacher_backbone |
|
|
|
|
|
self.embed_dim = embed_dim |
|
|
|
|
|
|
|
|
self.total_n_global_crops = cfg.batch_size |
|
|
|
|
|
self.student = nn.ModuleDict(student_model_dict) |
|
|
self.teacher = nn.ModuleDict(teacher_model_dict) |
|
|
|
|
|
teacher_embed_dim = teacher_backbone.embed_dim |
|
|
|
|
|
self.token_head = nn.Sequential( |
|
|
nn.LayerNorm(embed_dim), |
|
|
nn.Linear(embed_dim, teacher_embed_dim)) |
|
|
|
|
|
self.soft_criterion = torch.nn.MSELoss() |
|
|
|
|
|
for param in self.teacher.backbone.parameters(): |
|
|
param.requires_grad = False |
|
|
|
|
|
|
|
|
def forward(self, inputs): |
|
|
global_crops = inputs["collated_global_crops"] |
|
|
|
|
|
|
|
|
|
|
|
def compute_teacher_output(): |
|
|
with torch.no_grad(): |
|
|
teacher_backbone_output_dict = self.teacher.backbone(global_crops) |
|
|
teacher_cls_tokens = teacher_backbone_output_dict["x_norm_clstoken"] |
|
|
|
|
|
return teacher_cls_tokens |
|
|
|
|
|
|
|
|
teacher_cls_tokens = compute_teacher_output() |
|
|
|
|
|
student_backbone_output_dict_unmask = self.student.backbone(global_crops) |
|
|
|
|
|
student_cls_token_unmask = student_backbone_output_dict_unmask["x_norm_clstoken"] |
|
|
|
|
|
|
|
|
student_cls_token_unmask = self.token_head(student_cls_token_unmask) |
|
|
|
|
|
|
|
|
distillation_loss_token = self.soft_criterion(student_cls_token_unmask, teacher_cls_tokens) |
|
|
|
|
|
|
|
|
token_loss = self.cfg.lambda_token * distillation_loss_token |
|
|
|
|
|
|
|
|
total_loss = token_loss |
|
|
|
|
|
|
|
|
loss_dict = {"patch_loss": torch.tensor(0.0), "fea_loss": torch.tensor(0.0), "token_loss": token_loss, "loss": total_loss} |
|
|
|
|
|
return loss_dict |