| """ |
| CKA 对比分析:EVA-CLIP 预训练 vs DeCLIP+ 训练后 |
| |
| 目标:验证解耦蒸馏是否使 Q 和 K 特征变得更加不同 |
| - 如果 CKA(Q,K) 在 DeCLIP+ 训练后降低,说明特征成功解耦 |
| - 如果 CKA(Q,K) 保持不变或升高,说明特征没有解耦 |
| |
| 使用方法: |
| cd DeCLIP_private |
| python decoupling_analysis/run_cka_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 |
| from PIL import Image |
| from torchvision import transforms |
| import numpy as np |
| import json |
| from typing import List, Tuple, Dict |
| from collections import defaultdict |
|
|
| |
| from cka_analysis import cka, CKAAnalyzer |
|
|
|
|
| def download_checkpoint_if_needed(target_path: str, repo_id: str = "xiaomoguhzz/xiaomogu_pami", filename: str = "declip_plus_seg/epoch_6.pt"): |
| """ |
| 如果权重文件不存在,自动从 HuggingFace 下载 |
| """ |
| if os.path.exists(target_path): |
| print(f"Checkpoint already 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 |
|
|
|
|
| def load_eva_clip_model(checkpoint_path: str = None, device: str = "cuda"): |
| """ |
| 加载 EVA-CLIP 模型 |
| |
| Args: |
| checkpoint_path: 如果为 None,使用预训练权重;否则加载指定 checkpoint |
| device: 计算设备 |
| """ |
| from open_clip import create_model |
| |
| |
| model = create_model("EVA02-CLIP-B-16", pretrained="eva", device=device) |
| |
| if checkpoint_path is not None: |
| print(f"Loading checkpoint from {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_state_dict = {} |
| for k, v in state_dict.items(): |
| if k.startswith("visual."): |
| visual_state_dict[k.replace("visual.", "")] = v |
| |
| if visual_state_dict: |
| |
| missing, unexpected = model.visual.load_state_dict(visual_state_dict, strict=False) |
| print(f"Loaded visual encoder weights. Missing: {len(missing)}, Unexpected: {len(unexpected)}") |
| if missing: |
| print(f" Missing keys (first 5): {missing[:5]}") |
| if unexpected: |
| print(f" Unexpected keys (first 5): {unexpected[:5]}") |
| else: |
| |
| missing, unexpected = model.load_state_dict(state_dict, strict=False) |
| print(f"Loaded full model weights. Missing: {len(missing)}, Unexpected: {len(unexpected)}") |
| |
| model.eval() |
| return model |
|
|
|
|
| def extract_qv_features( |
| model: torch.nn.Module, |
| images: List[torch.Tensor], |
| ) -> Tuple[torch.Tensor, torch.Tensor]: |
| """ |
| 提取 Q 和 V 特征 |
| |
| DeCLIP 设计: |
| - Q 特征 → content loss(细粒度特征) |
| - V 特征 → context loss(语义特征) |
| |
| Args: |
| model: CLIP 模型 |
| images: 图像 tensor 列表,每个为 (1, 3, H, W) |
| |
| Returns: |
| Q_all, V_all: 聚合后的 Q 和 V 特征 |
| """ |
| model.eval() |
| all_q = [] |
| all_v = [] |
| |
| with torch.no_grad(): |
| for image in images: |
| |
| |
| output_q = model.visual.encode_dense(image, keep_shape=True, mode="qq_vfm_distill") |
| if isinstance(output_q, tuple) and len(output_q) == 2: |
| _, q = output_q |
| q_flat = q.flatten() |
| all_q.append(q_flat) |
| |
| |
| output_v = model.visual.encode_dense(image, keep_shape=True, mode="vv_vfm_distill") |
| if isinstance(output_v, tuple) and len(output_v) == 2: |
| _, v = output_v |
| v_flat = v.flatten() |
| all_v.append(v_flat) |
| |
| if not all_q or not all_v: |
| print("Warning: No Q/V features extracted!") |
| return None, None |
| |
| |
| |
| Q_all = torch.stack(all_q, dim=0) |
| V_all = torch.stack(all_v, dim=0) |
| |
| print(f"Extracted features: Q shape = {Q_all.shape}, V shape = {V_all.shape}") |
| |
| return Q_all, V_all |
|
|
|
|
| def run_comparison( |
| pretrained_path: str = None, |
| declip_checkpoint: str = None, |
| image_dir: str = None, |
| num_images: int = 50, |
| save_dir: str = "cka_analysis_results", |
| device: str = "cuda" |
| ): |
| """ |
| 运行 CKA 对比分析 |
| |
| Args: |
| pretrained_path: 预训练模型路径(None 使用默认) |
| declip_checkpoint: DeCLIP+ 训练后的 checkpoint 路径 |
| image_dir: 测试图像目录 |
| num_images: 使用的图像数量 |
| save_dir: 结果保存目录 |
| device: 计算设备 |
| """ |
| os.makedirs(save_dir, exist_ok=True) |
| |
| |
| transform = transforms.Compose([ |
| transforms.Resize((560, 560)), |
| transforms.ToTensor(), |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| ]) |
| |
| |
| print(f"\n{'='*60}") |
| print("Loading test images...") |
| print(f"{'='*60}") |
| |
| image_paths = [] |
| for root, dirs, files in os.walk(image_dir): |
| for f in files: |
| if f.endswith(('.png', '.jpg', '.jpeg')): |
| image_paths.append(os.path.join(root, f)) |
| if len(image_paths) >= num_images: |
| break |
| if len(image_paths) >= num_images: |
| break |
| |
| print(f"Found {len(image_paths)} images") |
| |
| |
| images = [] |
| for path in image_paths: |
| try: |
| img = Image.open(path).convert("RGB") |
| img_tensor = transform(img).unsqueeze(0).to(device) |
| images.append(img_tensor) |
| except Exception as e: |
| print(f"Failed to load {path}: {e}") |
| |
| print(f"Successfully loaded {len(images)} images") |
| |
| results = {} |
| |
| |
| print(f"\n{'='*60}") |
| print("Analysis 1: Original EVA-CLIP (Pretrained)") |
| print(f"{'='*60}") |
| |
| model_pretrained = load_eva_clip_model(checkpoint_path=None, device=device) |
| Q_pre, V_pre = extract_qv_features(model_pretrained, images) |
| |
| if Q_pre is not None and V_pre is not None: |
| cka_pretrained = cka(Q_pre, V_pre, kernel="linear") |
| print(f"\n>>> CKA(Q, V) for Pretrained EVA-CLIP: {cka_pretrained:.4f}") |
| results["pretrained_qv_cka"] = cka_pretrained |
| |
| del model_pretrained |
| torch.cuda.empty_cache() |
| |
| |
| if declip_checkpoint and os.path.exists(declip_checkpoint): |
| print(f"\n{'='*60}") |
| print("Analysis 2: DeCLIP+ (After Training)") |
| print(f"{'='*60}") |
| |
| model_declip = load_eva_clip_model(checkpoint_path=declip_checkpoint, device=device) |
| Q_dec, V_dec = extract_qv_features(model_declip, images) |
| |
| if Q_dec is not None and V_dec is not None: |
| cka_declip = cka(Q_dec, V_dec, kernel="linear") |
| print(f"\n>>> CKA(Q, V) for DeCLIP+: {cka_declip:.4f}") |
| results["declip_qv_cka"] = cka_declip |
| |
| del model_declip |
| torch.cuda.empty_cache() |
| else: |
| print(f"\nWarning: DeCLIP checkpoint not found at {declip_checkpoint}") |
| |
| |
| print(f"\n{'='*60}") |
| print("SUMMARY: CKA(Q, V) Comparison Results") |
| print(f"{'='*60}") |
| print("\nDeCLIP 设计:Q 用于 content loss(细节),V 用于 context loss(语义)") |
| print("如果解耦成功,训练后 Q 和 V 应该更加不同(CKA 降低)\n") |
| |
| if "pretrained_qv_cka" in results: |
| print(f" Pretrained EVA-CLIP CKA(Q,V): {results['pretrained_qv_cka']:.4f}") |
| |
| if "declip_qv_cka" in results: |
| print(f" DeCLIP+ (trained) CKA(Q,V): {results['declip_qv_cka']:.4f}") |
| |
| if "pretrained_qv_cka" in results and "declip_qv_cka" in results: |
| diff = results["declip_qv_cka"] - results["pretrained_qv_cka"] |
| print(f"\n Δ CKA = {diff:+.4f}") |
| |
| if diff < -0.05: |
| print("\n ✓ 结论:DeCLIP+ 训练后 Q 和 V 特征更加不同(CKA 降低)") |
| print(" 这说明解耦蒸馏成功:Q 学习细节特征,V 学习语义特征。") |
| elif diff > 0.05: |
| print("\n ✗ 结论:DeCLIP+ 训练后 Q 和 V 特征更加相似(CKA 升高)") |
| print(" 这与预期不符,可能需要检查训练配置。") |
| else: |
| print("\n ~ 结论:DeCLIP+ 训练后 Q 和 V 的相似度变化不大") |
| print(" 可能需要更多样本或不同的分析方法来验证。") |
| |
| |
| results_path = os.path.join(save_dir, "cka_comparison_results.json") |
| with open(results_path, "w") as f: |
| json.dump(results, f, indent=2) |
| print(f"\nResults saved to: {results_path}") |
| |
| return results |
|
|
|
|
| if __name__ == "__main__": |
| |
| BASE_DIR = "/opt/tiger/xiaomoguhzz" |
| |
| |
| DECLIP_CHECKPOINT = os.path.join(BASE_DIR, "declip_plus_seg/epoch_6.pt") |
| |
| |
| IMAGE_DIR = os.path.join(BASE_DIR, "standard_coco/val2017") |
| |
| |
| if not os.path.exists(IMAGE_DIR): |
| IMAGE_DIR = os.path.join( |
| os.path.dirname(__file__), |
| "..", |
| "..", |
| "ReflectionBenchv2_3/images" |
| ) |
| |
| SAVE_DIR = os.path.join( |
| os.path.dirname(__file__), |
| "cka_analysis_results" |
| ) |
| |
| |
| download_checkpoint_if_needed(DECLIP_CHECKPOINT) |
| |
| |
| run_comparison( |
| pretrained_path=None, |
| declip_checkpoint=DECLIP_CHECKPOINT, |
| image_dir=IMAGE_DIR, |
| num_images=50, |
| save_dir=SAVE_DIR, |
| device="cuda" if torch.cuda.is_available() else "cpu" |
| ) |
|
|