| from typing import List |
| import torch |
| import torch.nn.functional as F |
| import torch |
| from torch.cuda.amp import autocast |
| from torchvision.ops import roi_align |
| import torch.nn as nn |
|
|
| |
| class DeCLIPWithREPAProjector(nn.Module): |
| def __init__(self, declip_model, clip_dim=768, hidden_dim=1024, vfm_dim=768,args=None): |
| super().__init__() |
| self.model = declip_model |
| self.repa_layer_idx = args.repa_layer_idx |
| self.projector = nn.Sequential( |
| nn.Linear(clip_dim, hidden_dim), |
| nn.SiLU(), |
| nn.Linear(hidden_dim, hidden_dim), |
| nn.SiLU(), |
| nn.Linear(hidden_dim, vfm_dim)) |
| |
| |
| |
| self.initialize_projector_weights() |
| self.logit_scale=self.model.logit_scale |
|
|
| def initialize_projector_weights(self): |
| for module in self.projector.modules(): |
| if isinstance(module, nn.Linear): |
| nn.init.xavier_uniform_(module.weight) |
| if module.bias is not None: |
| nn.init.constant_(module.bias, 0) |
|
|
| def encode_image(self, *args, **kwargs): |
| return self.model.encode_image(*args, **kwargs) |
|
|
| def encode_text(self, *args, **kwargs): |
| return self.model.encode_text(*args, **kwargs) |
|
|
| def encode_dense(self, *args, **kwargs): |
| return self.model.encode_dense(*args, **kwargs) |
|
|
| def encode_pseudo_boxes(self, images, rois_list, normalize = False, mode="qq", size=(1, 1)): |
| student_roi_features, context, intermediate_layer_output = self.model.encode_pseudo_boxes(images, |
| rois_list, |
| normalize=normalize, |
| mode = mode, |
| size=size, |
| get_intermediate_layer=[self.repa_layer_idx]) |
| |
| alpha=0.3 |
| residual=intermediate_layer_output[0] |
| intermediate_layer_output = self.projector(intermediate_layer_output[0]) |
| intermediate_layer_output = alpha * residual + intermediate_layer_output |
| return student_roi_features, context, intermediate_layer_output |
|
|
| def encode_masks(self, *args, **kwargs): |
| return self.model.encode_masks(*args, **kwargs) |
|
|
| def train(self, mode=True): |
| self.model.train(mode) |
| self.training = self.model.training |
| return self |
|
|
| def lock_image_tower(self, *args, **kwargs): |
| return self.model.lock_image_tower(*args, **kwargs) |
|
|
| def lock_text_tower(self, *args, **kwargs): |
| return self.model.lock_text_tower(*args, **kwargs) |
|
|
| @torch.jit.ignore |
| def set_grad_checkpointing(self, enable=True): |
| self.model.set_grad_checkpointing(enable) |
|
|
| @torch.jit.ignore |
| def no_weight_decay(self): |
| return self.model.no_weight_decay() |
|
|
| class DeCLIP_PLUS: |
|
|
| def __call__(self, batch, student, teacher, vfm_model, args): |
| losses = {} |
| context_weight = args.loss_context_weight |
| content_weight = args.loss_content_weight |
| region_weight = args.loss_region_weight |
| need_repa=args.repa_layer_idx!=-1 |
| if args.distributed: |
| student = student.module |
| dtype_map = {"bf16": torch.bfloat16, "amp": torch.float16} |
| input_dtype = dtype_map.get(args.precision, torch.float32) |
| images, normed_boxes, image_crops, vfm_image,sd_attn = prepare_inputs(batch, args.device, input_dtype) |
| loss_ensemble = self.intra_image_distill(student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,sd_attn,args) |
| loss_context, loss_content,loss_region = loss_ensemble[0], loss_ensemble[1], loss_ensemble[2] |
| losses.update({"loss_context":loss_context * context_weight}) |
| losses.update({"loss_content":loss_content * content_weight}) |
| losses.update({"loss_region":loss_region * region_weight}) |
| if need_repa: |
| loss_repa=loss_ensemble[2] |
| losses.update({"loss_repa":loss_repa}) |
| return losses, len(images) |
|
|
| def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,sd_attn,args): |
| need_repa = args.repa_layer_idx!=-1 |
| roi_size=(3, 3) |
| B = images.shape[0] |
| rois_list = [] |
| crops_list = [] |
|
|
| for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): |
| valid = bboxes_per_image[:, -1] > 0.5 |
| rois_list.append(bboxes_per_image[valid, :4]) |
| crops_list.append(crops_per_image[valid]) |
|
|
| image_crops = torch.cat(crops_list) |
| if need_repa: |
| student_roi_features, context, intermediate_layer_output = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size) |
| else: |
| student_roi_features, context = student.encode_pseudo_boxes(images, rois_list, normalize=True, mode = args.mode, size=roi_size) |
|
|
| with torch.no_grad(): |
| teacher_crop_features = teacher.encode_image(image_crops, normalize=True) |
| intra_vfm_feats = extract_vfm_features(vfm_model, vfm_image,args) |
| vfm_roi_features= extract_roi_features(intra_vfm_feats,rois_list,normalize=True) |
| intra_vfm_feats = F.normalize(intra_vfm_feats,dim=1).flatten(start_dim=-2) |
| intra_vfm_corr = torch.einsum('bci,bcj->bij', intra_vfm_feats, intra_vfm_feats) |
| refined_intra_vfm_corr = refine_dino(intra_vfm_corr, sd_attn, args.sd_refine_weight) |
|
|
| student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args) |
| loss_context = context_loss(student_intra_corr, refined_intra_vfm_corr, teacher_temp=0.8) |
| |
| loss_content = soft_content_distill_loss(student_roi_features,teacher_crop_features) |
| loss_region= region_scd_loss(student_roi_features,vfm_roi_features) |
| if need_repa: |
| loss_repa = repa_loss(intermediate_layer_output, intra_vfm_feats) |
| return loss_context, loss_content, loss_repa |
| else: |
| return loss_context, loss_content,loss_region |
| |
| def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): |
| student_log_prob = F.log_softmax(student_corr / student_temp, dim=-1) |
| with torch.no_grad(): |
| teacher_prob = F.softmax(teacher_corr / teacher_temp, dim=-1) |
| kl_loss=F.kl_div(student_log_prob, teacher_prob, reduction='batchmean')* (teacher_temp*student_temp) |
| return kl_loss |
|
|
|
|
| def refine_dino(dino_corr, sd_attn, sd_refine_weight): |
| """ |
| dino_corr: (bs,hw,hw) |
| sd_attn: (bs,hw,hw) |
| """ |
| residual = dino_corr |
| dino_corr = torch.bmm(sd_attn, dino_corr) |
| |
| dino_corr_refined = dino_corr * (sd_refine_weight) + residual * (1-sd_refine_weight) |
| |
| bs, hw, _ = dino_corr_refined.shape |
| device = dino_corr_refined.device |
| eye = torch.eye(hw, dtype=dino_corr_refined.dtype, device=device).unsqueeze(0).expand(bs, -1, -1) |
| dino_corr_refined = dino_corr_refined * (1 - eye) + eye |
| return dino_corr_refined |
|
|
|
|
| def repa_loss(clip_intermediate_out, vfm_out): |
| """ |
| clip_intermediate_out: (bs, nt+1, hs), NOT L2 norm |
| vfm_out: (bs, hs, nt), ALREADY L2 norm |
| """ |
| vfm_out = vfm_out.transpose(1, 2) |
| clip_intermediate_out = clip_intermediate_out[:, 1:] |
| clip_intermediate_out = F.normalize(clip_intermediate_out, dim=-1) |
| similarity = (clip_intermediate_out * vfm_out).sum(dim=-1) |
| loss = -similarity.mean() |
| return loss |
|
|
| def soft_content_distill_loss(student_roi_features, teacher_crop_features, T=1.0): |
| sim = torch.einsum('bpc,bc->bp', student_roi_features, teacher_crop_features) |
| weights = F.softmax(sim / T, dim=1) |
| weighted_student = (student_roi_features * weights.unsqueeze(-1)).sum(dim=1) |
| weighted_student = F.normalize(weighted_student, dim=-1) |
| cosine_similarity = (weighted_student * teacher_crop_features).sum(dim=-1) |
| loss = 1.0 - cosine_similarity.mean() |
| return loss |
|
|
| def region_scd_loss(student_roi_features, intra_vfm_roi_feats, T_teacher=1.0, T_student=1.0): |
| with torch.no_grad(): |
| intra_vfm_roi_feats=intra_vfm_roi_feats.transpose(-2,-1).contiguous() |
| teacher_corr=torch.einsum('bic,bjc->bij', intra_vfm_roi_feats, intra_vfm_roi_feats) / T_teacher |
| teacher_prob = F.softmax(teacher_corr, dim=-1) |
| student_corr=torch.einsum('bic,bjc->bij', student_roi_features, student_roi_features) / T_student |
| student_log_prob = F.log_softmax(student_corr, dim=-1) |
| loss = F.kl_div(student_log_prob, teacher_prob, reduction='batchmean') * (T_teacher * T_student) |
| return loss |
|
|
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| def extract_roi_features(x, normed_boxes, size=(3,3), normalize=False): |
| """ |
| x:(bs,c,h,w) |
| """ |
| def _denormalize_boxes(normed_boxes, x): |
| h, w = x.shape[-2:] |
| denormed_boxes = [] |
| for boxes in normed_boxes: |
| new_boxes = boxes.clone() |
| new_boxes[:, [0, 2]] *= w |
| new_boxes[:, [1, 3]] *= h |
| denormed_boxes.append(new_boxes) |
| return denormed_boxes |
| if size==(1, 1): |
| roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True)[..., 0, 0] |
| else: |
| roi_feats=roi_align(x, _denormalize_boxes(normed_boxes, x), size, 1.0, -1, True).flatten(start_dim=-2) |
| if normalize: |
| roi_feats=F.normalize(roi_feats,dim=1) |
| return roi_feats |
|
|
|
|
| def prepare_inputs(batch, device, dtype): |
| """ |
| 将输入批次中的数据加载到设备,并转换为指定数据类型。 |
| """ |
| images, normed_boxes, image_crops, vfm_image, sd_attn = batch |
| images = images.to(device=device, dtype=dtype, non_blocking=True) |
| normed_boxes = normed_boxes.to(device=device, dtype=dtype, non_blocking=True) |
| image_crops = image_crops.to(device=device, dtype=dtype, non_blocking=True) |
| vfm_image = vfm_image.to(device=device, dtype=dtype, non_blocking=True) |
| sd_attn = sd_attn.to(device=device, dtype=dtype, non_blocking=True) |
| return images, normed_boxes, image_crops, vfm_image, sd_attn |
|
|
|
|
| def extract_vfm_features(vfm_model, image, args): |
| """ |
| 从 VFM 模型中提取特征,并对其进行归一化。 |
| """ |
| if "dinov2" in args.use_vfm or "sd_dino" in args.use_vfm or "sam_dino" in args.use_vfm: |
| vfm_feats = vfm_model.get_intermediate_layers(image, reshape=True)[0] |
| elif 'sam' in args.use_vfm: |
| vfm_feats = vfm_model.image_encoder(image) |
| elif 'dino' in args.use_vfm: |
| feat = vfm_model.get_intermediate_layers(image)[0] |
| nb_im = feat.shape[0] |
| patch_size = vfm_model.patch_embed.patch_size |
| I, J = image[0].shape[-2] // patch_size, image[0].shape[-2] // patch_size |
| vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) |
| else: |
| raise NotImplementedError(f"VFM mode {args.use_vfm} is not implemented.") |
| return vfm_feats |
|
|
| def compute_student_intra_image_similarity(B, context, args): |
|
|
| N, _ = context[0].shape[1:] if isinstance(context, tuple) else context.shape[1:] |
| if args.mode in ["qq_vfm_distill", "kk_vfm_distill", "vv_vfm_distill", "sanity_check"]: |
| context = context.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) |
| context = F.normalize(context, dim=-1).transpose(-2, -1) |
| student_context_similarity = torch.einsum("b c m, b c n -> b m n", context, context) |
|
|
| elif args.mode == "csa_vfm_distill": |
| q_feature, k_feature = context |
| q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) |
| k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) |
| q_feature = F.normalize(q_feature, dim=-1).transpose(-2, -1) |
| k_feature = F.normalize(k_feature, dim=-1).transpose(-2, -1) |
| student_context_similarity = (torch.einsum("b c m, b c n -> b m n", q_feature, q_feature) + |
| torch.einsum("b c m, b c n -> b m n", k_feature, k_feature)) / 2.0 |
| elif args.mode == "all_vfm_distill": |
| q_feature, k_feature, v_feature = context |
| features = [q_feature, k_feature, v_feature] |
| similarities = [] |
| for feature in features: |
| feature = feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) |
| feature = F.normalize(feature, dim=-1).transpose(-2, -1) |
| similarities.append(torch.einsum("b c m, b c n -> b m n", feature, feature)) |
| student_context_similarity = sum(similarities) / len(features) |
|
|
| else: |
| raise NotImplementedError(f"Mode '{args.mode}' is not implemented.") |
|
|
| return student_context_similarity |