File size: 8,317 Bytes
c9aee57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
可视化消融实验:比较 SD-GSC, SAM-GSC, JEPA-GSC 的效果

类似于 vis_sd_featsv5.2.py,但同时展示三种方法的结果
"""

import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os
import sys
from typing import Tuple

# 添加项目路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from refine_functions import (
    refine_dino_with_sd,
    refine_dino_with_sam,
    refine_dino_with_ijepa,
    compute_dino_correlation,
    resize_attention
)

# 图像预处理
class ImagePreprocessor:
    def __init__(self, size: int = 224):
        self.size = size
        self.mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
        self.std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
    
    def __call__(self, img: Image.Image) -> torch.Tensor:
        img = img.convert("RGB")
        img = img.resize((self.size, self.size), Image.BILINEAR)
        img = torch.from_numpy(np.array(img)).float() / 255.0
        img = img.permute(2, 0, 1)  # HWC -> CHW
        img = (img - self.mean) / self.std
        return img.unsqueeze(0)


def build_dinov2(device: str = "cuda"):
    """构建 DINOv2 模型"""
    hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main'
    model = torch.hub.load(hub_path, 'dinov2_vitb14_reg', source='local').half()
    model = model.to(device).eval()
    for p in model.parameters():
        p.requires_grad = False
    return model


def extract_dino_features(model, image: torch.Tensor) -> torch.Tensor:
    """提取 DINO 特征"""
    with torch.no_grad():
        features = model.get_intermediate_layers(image, reshape=True)[0]
    return features


def visualize_similarity_comparison(
    image_path: str,
    dino_model,
    sd_attn: torch.Tensor,
    sam_attn: torch.Tensor,
    ijepa_attn: torch.Tensor,
    query_point: Tuple[int, int],
    refine_weight: float = 0.3,
    save_path: str = None,
    device: str = "cuda"
):
    """
    可视化比较三种方法的相似度图
    
    Args:
        image_path: 输入图像路径
        dino_model: DINOv2 模型
        sd_attn: SD attention (B, HW, HW)
        sam_attn: SAM attention (B, HW, HW)
        ijepa_attn: I-JEPA attention (B, HW, HW)
        query_point: 查询点位置 (y, x) in patch coordinates
        refine_weight: refine 权重
        save_path: 保存路径
        device: 设备
    """
    # 加载和预处理图像
    preprocess = ImagePreprocessor(size=224)
    image = Image.open(image_path)
    image_tensor = preprocess(image).to(device).half()
    
    # 提取 DINO 特征
    dino_feats = extract_dino_features(dino_model, image_tensor)  # (B, C, H, W)
    B, C, H, W = dino_feats.shape
    
    # 计算 DINO 相似度
    dino_corr = compute_dino_correlation(dino_feats)  # (B, HW, HW)
    
    # 调整 attention 尺寸以匹配 DINO
    target_size = H  # 通常是 16 for 224x224 input with patch_size=14
    
    if sd_attn is not None:
        sd_attn_resized = resize_attention(sd_attn, target_size)
    else:
        sd_attn_resized = None
    
    if sam_attn is not None:
        sam_attn_resized = resize_attention(sam_attn, target_size)
    else:
        sam_attn_resized = None
        
    if ijepa_attn is not None:
        ijepa_attn_resized = resize_attention(ijepa_attn, target_size)
    else:
        ijepa_attn_resized = None
    
    # Refine DINO 相似度
    methods = {
        "Original DINO": dino_corr,
    }
    
    if sd_attn_resized is not None:
        methods["SD-GSC (Ours)"] = refine_dino_with_sd(dino_corr, sd_attn_resized, refine_weight)
    
    if sam_attn_resized is not None:
        methods["SAM-GSC"] = refine_dino_with_sam(dino_corr, sam_attn_resized, refine_weight)
    
    if ijepa_attn_resized is not None:
        methods["JEPA-GSC"] = refine_dino_with_ijepa(dino_corr, ijepa_attn_resized, refine_weight)
    
    # 获取查询点的相似度图
    query_idx = query_point[0] * W + query_point[1]
    
    similarity_maps = {}
    for name, corr in methods.items():
        sim_map = corr[0, query_idx].view(H, W).cpu().numpy()
        similarity_maps[name] = sim_map
    
    # 可视化
    n_methods = len(similarity_maps)
    fig, axes = plt.subplots(1, n_methods + 1, figsize=(4 * (n_methods + 1), 4))
    
    # 显示原图
    axes[0].imshow(image.resize((224, 224)))
    axes[0].scatter([query_point[1] * (224 // W)], [query_point[0] * (224 // H)], 
                    c='red', s=100, marker='x')
    axes[0].set_title("Input Image")
    axes[0].axis('off')
    
    # 显示各方法的相似度图
    for i, (name, sim_map) in enumerate(similarity_maps.items()):
        im = axes[i + 1].imshow(sim_map, cmap='hot', vmin=0, vmax=1)
        axes[i + 1].scatter([query_point[1]], [query_point[0]], c='cyan', s=50, marker='x')
        axes[i + 1].set_title(name)
        axes[i + 1].axis('off')
    
    plt.colorbar(im, ax=axes[-1], fraction=0.046, pad=0.04)
    plt.tight_layout()
    
    if save_path:
        plt.savefig(save_path, dpi=150, bbox_inches='tight')
        print(f"Saved visualization to {save_path}")
    
    plt.show()
    plt.close()


def visualize_attention_comparison(
    sd_attn: torch.Tensor,
    sam_attn: torch.Tensor,
    ijepa_attn: torch.Tensor,
    query_point: Tuple[int, int],
    save_path: str = None
):
    """
    直接可视化三种方法的 attention map(不经过 DINO)
    """
    H = W = int(sd_attn.shape[1] ** 0.5) if sd_attn is not None else int(sam_attn.shape[1] ** 0.5)
    query_idx = query_point[0] * W + query_point[1]
    
    attentions = {}
    if sd_attn is not None:
        attentions["SD Attention"] = sd_attn[0, query_idx].view(H, W).cpu().numpy()
    if sam_attn is not None:
        attentions["SAM Attention"] = sam_attn[0, query_idx].view(H, W).cpu().numpy()
    if ijepa_attn is not None:
        attentions["I-JEPA Attention"] = ijepa_attn[0, query_idx].view(H, W).cpu().numpy()
    
    n_attns = len(attentions)
    fig, axes = plt.subplots(1, n_attns, figsize=(4 * n_attns, 4))
    
    if n_attns == 1:
        axes = [axes]
    
    for i, (name, attn_map) in enumerate(attentions.items()):
        im = axes[i].imshow(attn_map, cmap='viridis')
        axes[i].scatter([query_point[1]], [query_point[0]], c='red', s=50, marker='x')
        axes[i].set_title(name)
        axes[i].axis('off')
        plt.colorbar(im, ax=axes[i], fraction=0.046, pad=0.04)
    
    plt.tight_layout()
    
    if save_path:
        plt.savefig(save_path, dpi=150, bbox_inches='tight')
        print(f"Saved attention comparison to {save_path}")
    
    plt.show()
    plt.close()


# ============ 主函数 ============
if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--image", type=str, required=True, help="Input image path")
    parser.add_argument("--query_y", type=int, default=8, help="Query point y (in patch coords)")
    parser.add_argument("--query_x", type=int, default=8, help="Query point x (in patch coords)")
    parser.add_argument("--refine_weight", type=float, default=0.3)
    parser.add_argument("--save_dir", type=str, default="./ablation_results")
    args = parser.parse_args()
    
    os.makedirs(args.save_dir, exist_ok=True)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    
    print("Building DINOv2 model...")
    dino_model = build_dinov2(device)
    
    # TODO: 加载预提取的 attention 或实时提取
    # 这里用随机 attention 作为示例
    print("Using dummy attention for demonstration...")
    HW = 256  # 16x16 patches
    sd_attn = F.softmax(torch.randn(1, HW, HW, device=device), dim=-1)
    sam_attn = F.softmax(torch.randn(1, HW, HW, device=device), dim=-1)
    ijepa_attn = F.softmax(torch.randn(1, HW, HW, device=device), dim=-1)
    
    query_point = (args.query_y, args.query_x)
    
    print("Visualizing similarity comparison...")
    save_path = os.path.join(args.save_dir, "similarity_comparison.png")
    visualize_similarity_comparison(
        args.image,
        dino_model,
        sd_attn,
        sam_attn,
        ijepa_attn,
        query_point,
        args.refine_weight,
        save_path,
        device
    )
    
    print("Done!")