""" 统一的 DINO 相似度矩阵 Refine 函数 所有方法共享相同的 refine 框架: refined_dino_corr = refine_fn(dino_corr, external_attn, refine_weight) 区别仅在于 external_attn 的来源: - SD-GSC: Stable Diffusion self-attention - SAM-GSC: SAM image encoder self-attention - JEPA-GSC: I-JEPA encoder self-attention """ import torch import torch.nn.functional as F def refine_dino_with_attn(dino_corr: torch.Tensor, external_attn: torch.Tensor, refine_weight: float = 0.3) -> torch.Tensor: """ 使用外部 attention 来 refine DINO 相似度矩阵 这是 SD-GSC 的核心操作,也适用于 SAM-GSC 和 JEPA-GSC Args: dino_corr: DINO 特征的相似度矩阵 (B, HW, HW) external_attn: 外部模型的 attention map (B, HW, HW) refine_weight: refine 权重,控制外部 attention 的影响程度 Returns: refined_corr: 精炼后的相似度矩阵 (B, HW, HW) """ residual = dino_corr # 核心操作:使用 external attention 作为传播矩阵 # 这相当于让 DINO 的相似度沿着 external attention 定义的路径传播 dino_corr_propagated = torch.bmm(external_attn, dino_corr) # 残差连接 dino_corr_refined = dino_corr_propagated * refine_weight + residual * (1 - refine_weight) # 强制对角线为 1(自己和自己的相似度应该是 1) B, HW, _ = dino_corr_refined.shape device = dino_corr_refined.device eye = torch.eye(HW, dtype=dino_corr_refined.dtype, device=device).unsqueeze(0).expand(B, -1, -1) dino_corr_refined = dino_corr_refined * (1 - eye) + eye return dino_corr_refined def refine_dino_with_sd(dino_corr: torch.Tensor, sd_attn: torch.Tensor, refine_weight: float = 0.3) -> torch.Tensor: """ SD-GSC: 使用 Stable Diffusion self-attention refine DINO 这是原始方法,直接调用通用函数 """ return refine_dino_with_attn(dino_corr, sd_attn, refine_weight) def refine_dino_with_sam(dino_corr: torch.Tensor, sam_attn: torch.Tensor, refine_weight: float = 0.3) -> torch.Tensor: """ SAM-GSC: 使用 SAM image encoder self-attention refine DINO SAM 的特点: - 训练于大规模分割数据,对边界敏感 - 使用相对位置编码,空间感知能力强 """ return refine_dino_with_attn(dino_corr, sam_attn, refine_weight) def refine_dino_with_ijepa(dino_corr: torch.Tensor, ijepa_attn: torch.Tensor, refine_weight: float = 0.3) -> torch.Tensor: """ JEPA-GSC: 使用 I-JEPA encoder self-attention refine DINO I-JEPA 的特点: - 训练于 feature-level prediction 任务 - 学习到语义上一致的空间关系 """ return refine_dino_with_attn(dino_corr, ijepa_attn, refine_weight) def compute_dino_correlation(dino_feats: torch.Tensor) -> torch.Tensor: """ 计算 DINO 特征的相似度矩阵 Args: dino_feats: DINO 特征 (B, C, H, W) 或 (B, HW, C) Returns: dino_corr: 相似度矩阵 (B, HW, HW) """ if dino_feats.dim() == 4: # (B, C, H, W) -> (B, C, HW) B, C, H, W = dino_feats.shape dino_feats = dino_feats.flatten(start_dim=-2) # (B, C, HW) elif dino_feats.dim() == 3: # (B, HW, C) -> (B, C, HW) dino_feats = dino_feats.transpose(1, 2) # L2 归一化 dino_feats = F.normalize(dino_feats, dim=1) # 计算相似度矩阵 dino_corr = torch.einsum('bci,bcj->bij', dino_feats, dino_feats) return dino_corr def resize_attention(attn: torch.Tensor, target_size: int) -> torch.Tensor: """ 调整 attention 矩阵的空间尺寸以匹配目标大小 Args: attn: attention 矩阵 (B, N, N) 其中 N = H * W target_size: 目标空间尺寸 (target_size^2 = N') Returns: resized_attn: (B, N', N') """ B, N, _ = attn.shape current_size = int(N ** 0.5) if current_size == target_size: return attn # 重塑为 4D 进行插值 # (B, N, N) -> (B, h, w, h, w) attn_4d = attn.view(B, current_size, current_size, current_size, current_size) # 分别对两个空间维度进行插值 # 首先处理 query 维度 attn_4d = attn_4d.permute(0, 3, 4, 1, 2).contiguous() # (B, h_k, w_k, h_q, w_q) attn_4d = attn_4d.view(B * current_size * current_size, current_size, current_size) attn_4d = attn_4d.unsqueeze(1) # (B*N, 1, h_q, w_q) attn_4d = F.interpolate(attn_4d, size=(target_size, target_size), mode='bilinear', align_corners=False) attn_4d = attn_4d.squeeze(1).view(B, current_size, current_size, target_size, target_size) # 然后处理 key 维度 attn_4d = attn_4d.permute(0, 3, 4, 1, 2).contiguous() # (B, h_q', w_q', h_k, w_k) attn_4d = attn_4d.view(B * target_size * target_size, current_size, current_size) attn_4d = attn_4d.unsqueeze(1) attn_4d = F.interpolate(attn_4d, size=(target_size, target_size), mode='bilinear', align_corners=False) attn_4d = attn_4d.squeeze(1).view(B, target_size, target_size, target_size, target_size) # 重塑回 3D attn_resized = attn_4d.view(B, target_size * target_size, target_size * target_size) # 重新归一化 attn_resized = F.softmax(attn_resized, dim=-1) return attn_resized # ============ 测试代码 ============ if __name__ == "__main__": print("Testing refine functions...") B, HW = 2, 256 # 16x16 patches device = "cuda" if torch.cuda.is_available() else "cpu" # 模拟 DINO 相似度矩阵 dino_corr = torch.randn(B, HW, HW, device=device) dino_corr = F.softmax(dino_corr, dim=-1) # 模拟外部 attention external_attn = torch.randn(B, HW, HW, device=device) external_attn = F.softmax(external_attn, dim=-1) # 测试 refine 函数 refined_sd = refine_dino_with_sd(dino_corr, external_attn, 0.3) refined_sam = refine_dino_with_sam(dino_corr, external_attn, 0.3) refined_ijepa = refine_dino_with_ijepa(dino_corr, external_attn, 0.3) print(f"Input dino_corr shape: {dino_corr.shape}") print(f"Refined (SD) shape: {refined_sd.shape}") print(f"Refined (SAM) shape: {refined_sam.shape}") print(f"Refined (I-JEPA) shape: {refined_ijepa.shape}") # 验证对角线为 1 diag_values = torch.diagonal(refined_sd, dim1=1, dim2=2) print(f"Diagonal values (should be 1): {diag_values[0, :5]}") # 测试 resize attn_64 = torch.randn(B, 64, 64, device=device) attn_64 = F.softmax(attn_64, dim=-1) attn_resized = resize_attention(attn_64, target_size=16) print(f"Resized attention: {attn_64.shape} -> {attn_resized.shape}") print("All tests passed!")