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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"""
DeCLIP+ vs Integrated 特征可视化对比

通过 PCA 和 KMeans 聚类可视化来对比:
1. DeCLIP+ (解耦蒸馏) 的输出特征
2. Integrated (集成蒸馏) 的输出特征

如果 DeCLIP 避免了梯度冲突,特征质量应该更好,聚类结果更清晰。

使用方法:
    cd DeCLIP_private
    CUDA_VISIBLE_DEVICES=0 python decoupling_analysis/visualize_feature_comparison.py
"""

import sys
import os
import subprocess

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

import torch
import torch.nn.functional as F
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from torchvision.transforms import Compose, ToTensor, Normalize, Resize
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from scipy.optimize import linear_sum_assignment
import cv2


# ==================== 工具函数 ====================

def download_checkpoint_if_needed(target_path, repo_id="xiaomoguhzz/xiaomogu_pami", filename="declip_plus_seg/epoch_6.pt"):
    """如果权重文件不存在,自动从 HuggingFace 下载"""
    if os.path.exists(target_path):
        print(f"Checkpoint exists: {target_path}")
        return True
    
    print(f"Downloading checkpoint to {target_path}...")
    target_dir = os.path.dirname(target_path)
    os.makedirs(target_dir, exist_ok=True)
    
    try:
        cmd = f"huggingface-cli download {repo_id} {filename} --local-dir {target_dir}"
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            downloaded_path = os.path.join(target_dir, filename)
            if os.path.exists(downloaded_path) and downloaded_path != target_path:
                os.makedirs(os.path.dirname(target_path), exist_ok=True)
                if not os.path.exists(target_path):
                    os.rename(downloaded_path, target_path)
            print(f"Download complete: {target_path}")
            return True
        else:
            print(f"Download failed: {result.stderr}")
            return False
    except Exception as e:
        print(f"Download error: {e}")
        return False


class UnNormalize:
    """反归一化"""
    def __init__(self, mean, std):
        self.mean = torch.tensor(mean).view(3, 1, 1)
        self.std = torch.tensor(std).view(3, 1, 1)
    
    def __call__(self, tensor):
        return tensor * self.std.to(tensor.device) + self.mean.to(tensor.device)


def match_clusters(ref_map, pred_map, num_segments):
    """使用匈牙利算法对齐聚类标签"""
    cost_matrix = np.zeros((num_segments, num_segments), dtype=np.int32)
    for i in range(num_segments):
        for j in range(num_segments):
            cost_matrix[i, j] = -np.sum((ref_map == i) & (pred_map == j))
    row_ind, col_ind = linear_sum_assignment(cost_matrix)
    mapping = {j: i for i, j in zip(row_ind, col_ind)}
    matched_pred = np.copy(pred_map)
    for src, tgt in mapping.items():
        matched_pred[pred_map == src] = tgt
    return matched_pred


def calc_all_cosine(tokens):
    """计算 token 之间的余弦相似度矩阵"""
    if tokens.dim() == 3:
        tokens = tokens[0]
    tokens = F.normalize(tokens, dim=-1)
    cos_mat = torch.matmul(tokens, tokens.transpose(0, 1))
    return cos_mat.cpu().numpy()


def cluster_cosine_map(cos_map, num_segments=5):
    """对余弦相似度矩阵进行 KMeans 聚类"""
    np.random.seed(42)
    kmeans = KMeans(n_clusters=num_segments, n_init=10, random_state=42)
    clusters = kmeans.fit_predict(cos_map)
    return clusters


def get_cluster_map(tokens, orig_feature_map_size, upsampled_size, target_size, num_segments=5):
    """
    对特征进行聚类并上采样到目标尺寸
    
    Args:
        tokens: (B, N, C) 特征
        orig_feature_map_size: (H, W) 原始特征图大小
        upsampled_size: (H_up, W_up) 上采样特征大小
        target_size: (H_img, W_img) 目标图像大小
        num_segments: 聚类数
    """
    B, N, C = tokens.shape
    H, W = orig_feature_map_size
    assert N == H * W, f"tokens N={N} != H*W={H*W}"
    
    # reshape to (B, C, H, W) 并上采样
    tokens_2d = tokens.reshape(B, H, W, C).permute(0, 3, 1, 2)
    tokens_upsampled = F.interpolate(tokens_2d, size=upsampled_size, mode='bilinear', align_corners=False)
    B, C, H_up, W_up = tokens_upsampled.shape
    
    # reshape 回 (B, N', C)
    tokens_flatten = tokens_upsampled.permute(0, 2, 3, 1).reshape(B, H_up * W_up, C)
    
    # 计算余弦相似度并聚类
    cos_map_np = calc_all_cosine(tokens_flatten)
    clusters = cluster_cosine_map(cos_map_np, num_segments=num_segments)
    
    # 还原成 grid 并上采样到目标尺寸
    clusters_grid = clusters.reshape(upsampled_size)
    clusters_tensor = torch.from_numpy(clusters_grid).unsqueeze(0).unsqueeze(0).float()
    upsampled = F.interpolate(clusters_tensor, size=target_size, mode='nearest')
    clusters_upsampled = upsampled.squeeze().cpu().numpy().astype(int)
    
    return clusters_upsampled


def pca_visualization(tokens, orig_feature_map_size, target_size, n_components=3):
    """
    对特征进行 PCA 可视化
    
    Args:
        tokens: (B, N, C) 特征
        orig_feature_map_size: (H, W)
        target_size: (H_img, W_img)
        n_components: PCA 成分数(3 for RGB)
    
    Returns:
        pca_rgb: (H_img, W_img, 3) RGB 图像
    """
    B, N, C = tokens.shape
    H, W = orig_feature_map_size
    
    # 展平并进行 PCA
    tokens_np = tokens[0].cpu().numpy()  # (N, C)
    pca = PCA(n_components=n_components)
    pca_result = pca.fit_transform(tokens_np)  # (N, 3)
    
    # 归一化到 [0, 1]
    pca_min = pca_result.min(axis=0)
    pca_max = pca_result.max(axis=0)
    pca_normalized = (pca_result - pca_min) / (pca_max - pca_min + 1e-8)
    
    # reshape 成图像
    pca_image = pca_normalized.reshape(H, W, n_components)
    
    # 上采样到目标尺寸
    pca_tensor = torch.from_numpy(pca_image).permute(2, 0, 1).unsqueeze(0).float()
    pca_upsampled = F.interpolate(pca_tensor, size=target_size, mode='bilinear', align_corners=False)
    pca_rgb = pca_upsampled.squeeze().permute(1, 2, 0).numpy()
    
    return pca_rgb


def pca_visualization_aligned(feat_a, feat_b, orig_feature_map_size, target_size, n_components=3):
    """
    对两个模型的特征进行对齐的 PCA 可视化
    
    方法:合并两个模型的特征一起 fit PCA,使用相同的 PCA 空间和归一化范围
    
    Args:
        feat_a: (B, N, C) 第一个模型的特征
        feat_b: (B, N, C) 第二个模型的特征
    
    Returns:
        pca_a, pca_b: 两个模型的 PCA RGB 图像
    """
    B, N, C = feat_a.shape
    H, W = orig_feature_map_size
    
    tokens_a = feat_a[0].cpu().numpy()
    tokens_b = feat_b[0].cpu().numpy()
    
    # 合并特征一起 fit PCA
    combined = np.concatenate([tokens_a, tokens_b], axis=0)
    pca = PCA(n_components=n_components)
    pca.fit(combined)
    
    # Transform 两个特征
    pca_a = pca.transform(tokens_a)
    pca_b = pca.transform(tokens_b)
    
    # 使用全局 min/max 归一化
    all_pca = np.concatenate([pca_a, pca_b], axis=0)
    global_min = all_pca.min(axis=0)
    global_max = all_pca.max(axis=0)
    
    def normalize_and_reshape(pca_result):
        pca_normalized = (pca_result - global_min) / (global_max - global_min + 1e-8)
        pca_normalized = np.clip(pca_normalized, 0, 1)
        
        pca_image = pca_normalized.reshape(H, W, n_components)
        
        pca_tensor = torch.from_numpy(pca_image).permute(2, 0, 1).unsqueeze(0).float()
        pca_upsampled = F.interpolate(pca_tensor, size=target_size, mode='bilinear', align_corners=False)
        pca_rgb = pca_upsampled.squeeze().permute(1, 2, 0).numpy()
        return pca_rgb
    
    return normalize_and_reshape(pca_a), normalize_and_reshape(pca_b)


# ==================== 模型加载 ====================

def load_model(checkpoint_path, device="cuda"):
    """加载 EVA-CLIP 模型"""
    from open_clip import create_model
    
    model = create_model("EVA02-CLIP-B-16", pretrained="eva", device=device)
    
    if checkpoint_path and os.path.exists(checkpoint_path):
        print(f"Loading checkpoint: {checkpoint_path}")
        checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
        
        if "state_dict" in checkpoint:
            state_dict = checkpoint["state_dict"]
        elif "model" in checkpoint:
            state_dict = checkpoint["model"]
        else:
            state_dict = checkpoint
        
        state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
        
        # 加载 visual encoder 权重
        visual_state_dict = {k.replace("visual.", ""): v for k, v in state_dict.items() if k.startswith("visual.")}
        if visual_state_dict:
            missing, unexpected = model.visual.load_state_dict(visual_state_dict, strict=False)
            print(f"Loaded visual weights. Missing: {len(missing)}, Unexpected: {len(unexpected)}")
        else:
            missing, unexpected = model.load_state_dict(state_dict, strict=False)
            print(f"Loaded full model. Missing: {len(missing)}, Unexpected: {len(unexpected)}")
    
    model.eval()
    return model


def extract_features(model, image, mode="vanilla"):
    """提取模型输出特征"""
    model.eval()
    with torch.no_grad():
        output = model.visual.encode_dense(image, keep_shape=True, mode=mode)
        if isinstance(output, tuple):
            output = output[0]
        # output shape: (B, C, H, W) or (B, N, C)
        if output.dim() == 4:
            B, C, H, W = output.shape
            output = output.permute(0, 2, 3, 1).reshape(B, H * W, C)
        elif output.dim() == 3:
            pass  # already (B, N, C)
        # normalize
        output = F.normalize(output, dim=-1)
        return output


# ==================== 主函数 ====================

def run_comparison(
    declip_checkpoint,
    integrated_checkpoint,
    image_paths,
    output_dir,
    target_size=(336, 336),
    num_segments=5,
    device="cuda"
):
    """
    运行 DeCLIP+ vs Integrated 特征可视化对比
    """
    os.makedirs(output_dir, exist_ok=True)
    
    # 图像预处理
    mean = [0.48145466, 0.4578275, 0.40821073]
    std = [0.26862954, 0.26130258, 0.27577711]
    normalize = Normalize(mean=mean, std=std)
    unnorm = UnNormalize(mean, std)
    
    transform = Compose([
        Resize(target_size),
        ToTensor(),
        normalize
    ])
    
    feature_map_size = (target_size[0] // 16, target_size[1] // 16)
    upsampled_size = (64, 64)
    
    # 加载模型
    print("\n" + "=" * 60)
    print("Loading models...")
    print("=" * 60)
    
    model_declip = load_model(declip_checkpoint, device)
    model_integrated = load_model(integrated_checkpoint, device)
    
    # 处理每张图像
    for img_idx, img_path in enumerate(image_paths):
        print(f"\nProcessing image {img_idx + 1}/{len(image_paths)}: {os.path.basename(img_path)}")
        
        # 加载图像
        raw_img = Image.open(img_path).convert('RGB')
        img = transform(raw_img).to(device).unsqueeze(0)
        
        # 反归一化用于可视化
        img_unnorm = unnorm(img.squeeze(0)).permute(1, 2, 0).cpu().numpy()
        img_unnorm = np.clip(img_unnorm, 0, 1)
        
        # 提取特征
        with torch.no_grad():
            feat_declip = extract_features(model_declip, img, mode="vanilla")
            feat_integrated = extract_features(model_integrated, img, mode="vanilla")
        
        # ==================== KMeans 聚类可视化 ====================
        print("  Computing KMeans clustering...")
        
        clusters_declip = get_cluster_map(
            feat_declip, feature_map_size, upsampled_size, target_size, num_segments
        )
        clusters_integrated = get_cluster_map(
            feat_integrated, feature_map_size, upsampled_size, target_size, num_segments
        )
        
        # 对齐聚类标签
        clusters_integrated = match_clusters(clusters_declip, clusters_integrated, num_segments)
        
        # ==================== PCA 可视化(对齐颜色)====================
        print("  Computing aligned PCA visualization...")
        
        pca_declip, pca_integrated = pca_visualization_aligned(
            feat_declip, feat_integrated, feature_map_size, target_size
        )
        
        # ==================== 绘制对比图 ====================
        fig, axs = plt.subplots(2, 3, figsize=(15, 10))
        
        # 第一行:KMeans 聚类
        axs[0, 0].imshow(img_unnorm)
        axs[0, 0].set_title("Original Image", fontsize=14)
        axs[0, 0].axis('off')
        
        axs[0, 1].imshow(img_unnorm)
        axs[0, 1].imshow(clusters_declip, cmap='tab10', alpha=0.6, interpolation='nearest')
        axs[0, 1].set_title("DeCLIP+ (Decoupled)", fontsize=14)
        axs[0, 1].axis('off')
        
        axs[0, 2].imshow(img_unnorm)
        axs[0, 2].imshow(clusters_integrated, cmap='tab10', alpha=0.6, interpolation='nearest')
        axs[0, 2].set_title("Integrated", fontsize=14)
        axs[0, 2].axis('off')
        
        # 第二行:PCA 可视化
        axs[1, 0].imshow(img_unnorm)
        axs[1, 0].set_title("Original Image", fontsize=14)
        axs[1, 0].axis('off')
        
        axs[1, 1].imshow(pca_declip)
        axs[1, 1].set_title("DeCLIP+ PCA Features", fontsize=14)
        axs[1, 1].axis('off')
        
        axs[1, 2].imshow(pca_integrated)
        axs[1, 2].set_title("Integrated PCA Features", fontsize=14)
        axs[1, 2].axis('off')
        
        plt.suptitle("DeCLIP+ (Decoupled Distillation) vs Integrated Distillation", fontsize=16, y=1.02)
        plt.tight_layout()
        
        # 保存
        img_name = os.path.splitext(os.path.basename(img_path))[0]
        save_path = os.path.join(output_dir, f"compare_{img_name}.png")
        plt.savefig(save_path, bbox_inches='tight', dpi=150)
        plt.close()
        print(f"  Saved: {save_path}")
    
    print("\n" + "=" * 60)
    print(f"All results saved to: {output_dir}")
    print("=" * 60)


if __name__ == "__main__":
    # ==================== 配置 ====================
    BASE_DIR = "/opt/tiger/xiaomoguhzz"
    
    # DeCLIP+ 权重
    DECLIP_CHECKPOINT = os.path.join(BASE_DIR, "declip_plus_seg/epoch_6.pt")
    
    # Integrated 权重(使用 epoch_5,因为 epoch_6 evaluation 失败了)
    INTEGRATED_CHECKPOINT = os.path.join(
        BASE_DIR, "..", 
        "mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/Integrated_EVA-B_DINOv2-B_560/checkpoints/epoch_5.pt"
    )
    # 尝试更直接的路径
    if not os.path.exists(INTEGRATED_CHECKPOINT):
        INTEGRATED_CHECKPOINT = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/Integrated_EVA-B_DINOv2-B_560/checkpoints/epoch_5.pt"
    
    # 测试图像
    IMAGE_DIR = os.path.join(BASE_DIR, "standard_coco/val2017")
    if not os.path.exists(IMAGE_DIR):
        IMAGE_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/ReflectionBenchv2_3/images"
    
    # 输出目录
    OUTPUT_DIR = os.path.join(
        os.path.dirname(__file__),
        "results", "feature_comparison"
    )
    
    # 自动下载 DeCLIP+ 权重
    download_checkpoint_if_needed(DECLIP_CHECKPOINT)
    
    # 收集测试图像(取前 5 张)
    image_paths = []
    if os.path.exists(IMAGE_DIR):
        for root, dirs, files in os.walk(IMAGE_DIR):
            for f in files:
                if f.endswith(('.jpg', '.png', '.jpeg')):
                    image_paths.append(os.path.join(root, f))
                    if len(image_paths) >= 5:
                        break
            if len(image_paths) >= 5:
                break
    
    if not image_paths:
        print("No images found!")
        sys.exit(1)
    
    print(f"Found {len(image_paths)} images")
    print(f"DeCLIP+ checkpoint: {DECLIP_CHECKPOINT}")
    print(f"Integrated checkpoint: {INTEGRATED_CHECKPOINT}")
    
    # 运行对比
    run_comparison(
        declip_checkpoint=DECLIP_CHECKPOINT,
        integrated_checkpoint=INTEGRATED_CHECKPOINT,
        image_paths=image_paths,
        output_dir=OUTPUT_DIR,
        target_size=(336, 336),
        num_segments=5,
        device="cuda" if torch.cuda.is_available() else "cpu"
    )