""" SAM-GSC 消融实验训练代码 使用 SAM image encoder 的 self-attention 代替 SD attention 来 refine DINO 相似度矩阵。 实时计算 SAM attention(不预提取)。 """ from typing import List, Tuple import torch import torch.nn.functional as F import torch.nn as nn from torchvision.ops import roi_align from src.segment_anything import sam_model_registry from src.segment_anything.modeling.image_encoder import Attention as SAMAttention # ============ SAM Attention 提取模块 ============ class SAMAttentionExtractor(nn.Module): """ 从 SAM image encoder 提取 global attention layers 的 attention map """ def __init__(self, sam_checkpoint: str, model_type: str = "vit_l", attention_layer_indices: List[int] = None, device: str = "cuda"): super().__init__() # 加载 SAM 模型 sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) self.image_encoder = sam.image_encoder.to(device).half().eval() # 冻结所有参数 for p in self.image_encoder.parameters(): p.requires_grad = False # 找出 global attention 层(window_size == 0 的层) self.global_attn_layer_indices = [] for i, blk in enumerate(self.image_encoder.blocks): if blk.window_size == 0: self.global_attn_layer_indices.append(i) # 默认使用最后两个 global attention 层 if attention_layer_indices is None: self.attention_layers = self.global_attn_layer_indices[-2:] else: self.attention_layers = [self.global_attn_layer_indices[i] for i in attention_layer_indices] # 修改需要提取 attention 的层 self._patch_attention_modules() def _patch_attention_modules(self): """Patch attention modules to return attention weights""" for layer_idx in self.attention_layers: block = self.image_encoder.blocks[layer_idx] original_attn = block.attn block.attn = SAMAttentionWithOutput(original_attn) @torch.no_grad() def forward(self, x: torch.Tensor) -> torch.Tensor: """ 提取 SAM attention map Args: x: 输入图像 (B, 3, H, W),已经过预处理 Returns: attention: 聚合的 attention map (B, HW, HW) """ # Patch embedding x = self.image_encoder.patch_embed(x) _, h, w, _ = x.shape # Position embedding if self.image_encoder.pos_embed is not None: if (h, w) == self.image_encoder.grid_size: x = x + self.image_encoder.pos_embed else: x = x + self.image_encoder.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) # 收集 attention attentions = [] for i, blk in enumerate(self.image_encoder.blocks): if i in self.attention_layers: # 这些层返回 attention shortcut = x x_normed = blk.norm1(x) x_attn, attn = blk.attn(x_normed, return_attention=True) x = shortcut + x_attn x = x + blk.mlp(blk.norm2(x)) attentions.append(attn) else: x = blk(x) # 聚合多层 attention: (L, B, nHead, HW, HW) -> (B, HW, HW) if len(attentions) > 0: attn_stack = torch.stack(attentions, dim=0) attn_aggregated = attn_stack.mean(dim=(0, 2)) # 平均所有层和所有 head else: B = x.shape[0] HW = h * w attn_aggregated = torch.eye(HW, device=x.device, dtype=x.dtype).unsqueeze(0).expand(B, -1, -1) return attn_aggregated class SAMAttentionWithOutput(nn.Module): """修改 SAM Attention 模块以返回 attention weights""" def __init__(self, original_attn: SAMAttention): super().__init__() self.num_heads = original_attn.num_heads self.scale = original_attn.scale self.qkv = original_attn.qkv self.proj = original_attn.proj self.use_rel_pos = original_attn.use_rel_pos if self.use_rel_pos: self.rel_pos_h = original_attn.rel_pos_h self.rel_pos_w = original_attn.rel_pos_w def forward(self, x: torch.Tensor, return_attention: bool = False): B, H, W, _ = x.shape qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) attn = (q * self.scale) @ k.transpose(-2, -1) if self.use_rel_pos: from src.segment_anything.modeling.image_encoder import add_decomposed_rel_pos attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) attn = attn.softmax(dim=-1) x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) x = self.proj(x) if return_attention: # (B*nHead, HW, HW) -> (B, nHead, HW, HW) attn_output = attn.view(B, self.num_heads, H * W, H * W) return x, attn_output return x # ============ SAM-GSC 训练模块 ============ class DeCLIPWithREPAProjector(nn.Module): """与 declip_plus.py 保持一致的模型包装器""" 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_SAM_GSC: """ SAM-GSC 消融实验:使用 SAM attention 代替 SD attention """ def __init__(self, sam_extractor: SAMAttentionExtractor): self.sam_extractor = sam_extractor 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) # SAM 版本的数据只有 4 个元素(没有预缓存的 attention) images, normed_boxes, image_crops, vfm_image, sam_image = prepare_inputs_sam(batch, args.device, input_dtype) # 实时计算 SAM attention with torch.no_grad(): sam_attn = self.sam_extractor(sam_image) loss_ensemble = self.intra_image_distill( student, teacher, vfm_model, images, normed_boxes, image_crops, vfm_image, sam_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, sam_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) # 使用 SAM attention refine DINO 相似度 refined_intra_vfm_corr = refine_dino_with_sam(intra_vfm_corr, sam_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 refine_dino_with_sam(dino_corr: torch.Tensor, sam_attn: torch.Tensor, refine_weight: float) -> torch.Tensor: """使用 SAM attention refine DINO 相似度矩阵""" # 调整 SAM attention 尺寸以匹配 DINO B_dino, HW_dino, _ = dino_corr.shape B_sam, HW_sam, _ = sam_attn.shape if HW_dino != HW_sam: sam_attn = resize_attention(sam_attn, int(HW_dino ** 0.5)) residual = dino_corr dino_corr_propagated = torch.bmm(sam_attn, dino_corr) dino_corr_refined = dino_corr_propagated * refine_weight + residual * (1 - refine_weight) # 强制对角线为 1 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 resize_attention(attn: torch.Tensor, target_size: int) -> torch.Tensor: """调整 attention 矩阵尺寸""" B, N, _ = attn.shape current_size = int(N ** 0.5) if current_size == target_size: return attn # (B, N, N) -> (B, 1, h, w, h, w) -> interpolate attn = attn.view(B, current_size, current_size, current_size, current_size) attn = attn.permute(0, 1, 3, 2, 4).contiguous() # (B, h, h, w, w) attn = attn.view(B, current_size * current_size, current_size, current_size) attn = F.interpolate(attn, size=(target_size, target_size), mode='bilinear', align_corners=False) attn = attn.view(B, current_size, current_size, target_size * target_size) attn = attn.permute(0, 3, 1, 2).contiguous() attn = F.interpolate(attn, size=(target_size, target_size), mode='bilinear', align_corners=False) attn = attn.view(B, target_size * target_size, target_size * target_size) attn = F.softmax(attn, dim=-1) return attn def prepare_inputs_sam(batch, device, dtype): """准备 SAM-GSC 的输入(包含 SAM 图像)""" images, normed_boxes, image_crops, vfm_image, sam_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) sam_image = sam_image.to(device=device, dtype=dtype, non_blocking=True) return images, normed_boxes, image_crops, vfm_image, sam_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 extract_roi_features(x, normed_boxes, size=(3, 3), normalize=False): """提取 ROI 特征""" 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 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 def context_loss(student_corr, teacher_corr, teacher_temp=1.0, student_temp=1.0): """Context distillation loss""" 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): """Content distillation loss""" 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): """Region correlation loss""" 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 repa_loss(clip_intermediate_out, vfm_out): """REPA loss""" 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 build_sam_attention_extractor(args): """构建 SAM attention 提取器""" sam_ckpts = { "sam-B": "/opt/tiger/xiaomoguhzz/sam_vit_b_01ec64.pth", "sam-L": "/opt/tiger/xiaomoguhzz/sam_vit_l_0b3195.pth", } # 默认使用 SAM-L sam_type = getattr(args, 'sam_type', 'sam-L') checkpoint = sam_ckpts.get(sam_type, sam_ckpts['sam-L']) model_type = "vit_l" if "L" in sam_type else "vit_b" extractor = SAMAttentionExtractor( sam_checkpoint=checkpoint, model_type=model_type, device=args.device ) return extractor