DeCLIP-TPAMI / analysis /decoupling_analysis /feature_visualization /visualize_feature_comparison.py
xiaomoguhzz's picture
Add files using upload-large-folder tool
a831c4c verified
"""
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"
)