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 # ! declip2只加入了region loss,没有加入sd smoothing class DeCLIP2: 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 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 = prepare_inputs(batch, args.device, input_dtype) loss_ensemble = self.intra_image_distill(student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, 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}) return losses, len(images) def intra_image_distill(self, student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image,args): 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) 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) # bs,768, h,w 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) student_intra_corr = compute_student_intra_image_similarity(images.shape[0], context, args) loss_context = context_loss(student_intra_corr, intra_vfm_corr) # loss_content = 1.0 - (student_roi_features * teacher_crop_features).sum(-1).mean() loss_content = soft_content_distill_loss(student_roi_features,teacher_crop_features) loss_region= region_scd_loss(student_roi_features,vfm_roi_features) 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 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() # bs, L, C 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() # FIXME: do not change the value in normed_boxes! 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 = 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) return images, normed_boxes, image_crops, vfm_image 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