File size: 12,250 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
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
"""
CKA 分析 - Centered Kernel Alignment

用于分析特征相似性:
1. DeCLIP 的 Q 特征 vs V 特征
2. Integrated 输出特征 vs DeCLIP Q 特征
3. Integrated 输出特征 vs DeCLIP V 特征

CKA 是一种测量神经网络表示相似性的方法,值在 [0, 1] 之间,1 表示完全相似
"""

import torch
import torch.nn.functional as F
import numpy as np
from typing import Dict, List, Tuple, Optional
import matplotlib.pyplot as plt
import seaborn as sns
import os


def centering_matrix(n: int, device: str = "cpu") -> torch.Tensor:
    """创建中心化矩阵 H = I - 1/n * ones"""
    I = torch.eye(n, device=device)
    ones = torch.ones(n, n, device=device) / n
    return I - ones


def linear_kernel(X: torch.Tensor) -> torch.Tensor:
    """线性核 K = X @ X.T"""
    return X @ X.T


def rbf_kernel(X: torch.Tensor, sigma: float = 1.0) -> torch.Tensor:
    """RBF 核"""
    sq_dists = torch.cdist(X, X, p=2) ** 2
    return torch.exp(-sq_dists / (2 * sigma ** 2))


def hsic(K: torch.Tensor, L: torch.Tensor, H: torch.Tensor) -> torch.Tensor:
    """
    Hilbert-Schmidt Independence Criterion
    HSIC(K, L) = trace(KHLH) / (n-1)^2
    """
    n = K.shape[0]
    KHLH = K @ H @ L @ H
    return torch.trace(KHLH) / ((n - 1) ** 2)


def cka(X: torch.Tensor, Y: torch.Tensor, kernel: str = "linear") -> float:
    """
    Centered Kernel Alignment
    
    CKA(X, Y) = HSIC(K_X, K_Y) / sqrt(HSIC(K_X, K_X) * HSIC(K_Y, K_Y))
    
    Args:
        X: 特征矩阵 (n_samples, n_features_x)
        Y: 特征矩阵 (n_samples, n_features_y)
        kernel: 核函数类型 ("linear" or "rbf")
        
    Returns:
        CKA 值 [0, 1]
    """
    assert X.shape[0] == Y.shape[0], "X and Y must have same number of samples"
    
    n = X.shape[0]
    device = X.device
    
    # 中心化矩阵
    H = centering_matrix(n, device)
    
    # 核矩阵
    if kernel == "linear":
        K_X = linear_kernel(X)
        K_Y = linear_kernel(Y)
    elif kernel == "rbf":
        K_X = rbf_kernel(X)
        K_Y = rbf_kernel(Y)
    else:
        raise ValueError(f"Unknown kernel: {kernel}")
    
    # HSIC
    hsic_xy = hsic(K_X, K_Y, H)
    hsic_xx = hsic(K_X, K_X, H)
    hsic_yy = hsic(K_Y, K_Y, H)
    
    # CKA
    cka_value = hsic_xy / (torch.sqrt(hsic_xx * hsic_yy) + 1e-8)
    
    return cka_value.item()


class CKAAnalyzer:
    """
    CKA 特征相似性分析器
    """
    
    def __init__(self, save_dir: str = "cka_analysis_results"):
        self.save_dir = save_dir
        os.makedirs(save_dir, exist_ok=True)
        self.results = {}
        
    def extract_features(
        self,
        model: torch.nn.Module,
        image: torch.Tensor,
        mode: str = "vanilla"
    ) -> Dict[str, torch.Tensor]:
        """
        提取特征
        
        Args:
            model: CLIP 模型
            image: 输入图像 (1, 3, H, W)
            mode: 提取模式
            
        Returns:
            特征字典
        """
        model.eval()
        features = {}
        
        with torch.no_grad():
            if mode in ["csa_vfm_distill", "qq_vfm_distill"]:
                output, context = model.encode_dense(image, normalize=False, keep_shape=True, mode=mode)
                features["output"] = output
                
                if isinstance(context, tuple):
                    if len(context) >= 2:
                        features["Q"] = context[0]
                        features["V"] = context[1]
                    elif len(context) == 1:
                        features["context"] = context[0]
                else:
                    features["context"] = context
            else:
                output = model.encode_dense(image, normalize=False, keep_shape=True, mode=mode)
                features["output"] = output
                
        return features
    
    def analyze_qv_similarity(
        self,
        model: torch.nn.Module,
        images: List[torch.Tensor],
        mode: str = "csa_vfm_distill"
    ) -> float:
        """
        分析 Q 和 V 特征的相似性
        
        Args:
            model: DeCLIP 模型
            images: 图像列表
            mode: 解耦模式
            
        Returns:
            Q 和 V 的 CKA 相似度
        """
        all_q = []
        all_v = []
        
        for image in images:
            features = self.extract_features(model, image, mode)
            
            if "Q" in features and "V" in features:
                # 展平特征
                q = features["Q"].flatten(start_dim=1)  # (B, N*dim)
                v = features["V"].flatten(start_dim=1)
                all_q.append(q)
                all_v.append(v)
        
        if not all_q:
            print("No Q/V features extracted")
            return 0.0
        
        # 合并所有样本
        Q_all = torch.cat(all_q, dim=0)  # (total_samples, features)
        V_all = torch.cat(all_v, dim=0)
        
        # 计算 CKA
        cka_qv = cka(Q_all, V_all, kernel="linear")
        
        self.results["Q_vs_V"] = cka_qv
        return cka_qv
    
    def analyze_integrated_vs_decoupled(
        self,
        decoupled_model: torch.nn.Module,
        integrated_model: torch.nn.Module,
        images: List[torch.Tensor]
    ) -> Dict[str, float]:
        """
        分析 Integrated 输出与 DeCLIP Q/V 的相似性
        
        Args:
            decoupled_model: 解耦蒸馏模型
            integrated_model: 集成蒸馏模型
            images: 图像列表
            
        Returns:
            CKA 相似度字典
        """
        all_integrated = []
        all_q = []
        all_v = []
        
        for image in images:
            # 提取 integrated 特征
            int_features = self.extract_features(integrated_model, image, mode="vanilla")
            int_output = int_features["output"].flatten(start_dim=1)
            all_integrated.append(int_output)
            
            # 提取 decoupled 特征
            dec_features = self.extract_features(decoupled_model, image, mode="csa_vfm_distill")
            if "Q" in dec_features and "V" in dec_features:
                q = dec_features["Q"].flatten(start_dim=1)
                v = dec_features["V"].flatten(start_dim=1)
                all_q.append(q)
                all_v.append(v)
        
        if not all_q:
            print("No Q/V features extracted from decoupled model")
            return {}
        
        # 合并
        Int_all = torch.cat(all_integrated, dim=0)
        Q_all = torch.cat(all_q, dim=0)
        V_all = torch.cat(all_v, dim=0)
        
        # 确保特征维度一致
        min_dim = min(Int_all.shape[1], Q_all.shape[1], V_all.shape[1])
        Int_all = Int_all[:, :min_dim]
        Q_all = Q_all[:, :min_dim]
        V_all = V_all[:, :min_dim]
        
        # 计算 CKA
        results = {
            "Integrated_vs_Q": cka(Int_all, Q_all, kernel="linear"),
            "Integrated_vs_V": cka(Int_all, V_all, kernel="linear"),
            "Q_vs_V": cka(Q_all, V_all, kernel="linear")
        }
        
        self.results.update(results)
        return results
    
    def visualize_cka_matrix(
        self,
        cka_matrix: np.ndarray,
        labels: List[str],
        save_name: str = "cka_matrix.png",
        title: str = "CKA Similarity Matrix"
    ):
        """
        可视化 CKA 相似度矩阵
        """
        plt.figure(figsize=(8, 6))
        sns.heatmap(
            cka_matrix,
            xticklabels=labels,
            yticklabels=labels,
            annot=True,
            fmt=".3f",
            cmap="YlOrRd",
            vmin=0,
            vmax=1,
            square=True
        )
        plt.title(title, fontsize=14)
        plt.tight_layout()
        
        save_path = os.path.join(self.save_dir, save_name)
        plt.savefig(save_path, dpi=150, bbox_inches="tight")
        plt.close()
        
        print(f"CKA matrix saved to {save_path}")
    
    def create_comparison_matrix(self) -> Tuple[np.ndarray, List[str]]:
        """
        创建对比矩阵
        """
        labels = ["DeCLIP Q", "DeCLIP V", "Integrated Output"]
        n = len(labels)
        matrix = np.eye(n)
        
        if "Q_vs_V" in self.results:
            matrix[0, 1] = matrix[1, 0] = self.results["Q_vs_V"]
        if "Integrated_vs_Q" in self.results:
            matrix[0, 2] = matrix[2, 0] = self.results["Integrated_vs_Q"]
        if "Integrated_vs_V" in self.results:
            matrix[1, 2] = matrix[2, 1] = self.results["Integrated_vs_V"]
            
        return matrix, labels
    
    def print_summary(self):
        """打印分析摘要"""
        print("\n" + "="*50)
        print("CKA Analysis Summary")
        print("="*50)
        
        for key, value in self.results.items():
            print(f"  {key}: {value:.4f}")
            
        print("\nInterpretation:")
        if "Q_vs_V" in self.results:
            qv = self.results["Q_vs_V"]
            if qv < 0.5:
                print(f"  Q and V are fairly different (CKA={qv:.3f}), indicating successful decoupling")
            else:
                print(f"  Q and V are similar (CKA={qv:.3f}), suggesting features are mixed")
                
        print("="*50 + "\n")
    
    def save_results(self, filename: str = "cka_results.json"):
        """保存分析结果"""
        import json
        
        filepath = os.path.join(self.save_dir, filename)
        with open(filepath, "w") as f:
            json.dump(self.results, f, indent=2)
        print(f"CKA results saved to {filepath}")


def run_cka_analysis(
    decoupled_checkpoint: str,
    integrated_checkpoint: str,
    image_paths: List[str],
    model_name: str = "EVA02-CLIP-B-16",
    save_dir: str = "cka_analysis_results"
):
    """
    运行完整的 CKA 分析
    
    Args:
        decoupled_checkpoint: 解耦蒸馏模型的 checkpoint 路径
        integrated_checkpoint: 集成蒸馏模型的 checkpoint 路径
        image_paths: 测试图像路径列表
        model_name: 模型名称
        save_dir: 保存目录
    """
    from open_clip import create_model
    from torchvision import transforms
    from PIL import Image
    
    print("Loading models...")
    device = "cuda" if torch.cuda.is_available() else "cpu"
    
    # 加载模型
    decoupled_model = create_model(model_name, pretrained="eva", device=device)
    decoupled_model.load_state_dict(torch.load(decoupled_checkpoint, map_location=device)["state_dict"])
    decoupled_model.eval()
    
    integrated_model = create_model(model_name, pretrained="eva", device=device)
    integrated_model.load_state_dict(torch.load(integrated_checkpoint, map_location=device)["state_dict"])
    integrated_model.eval()
    
    # 预处理
    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"Loading {len(image_paths)} images...")
    images = []
    for path in image_paths:
        image = Image.open(path).convert("RGB")
        image_tensor = transform(image).unsqueeze(0).to(device)
        images.append(image_tensor)
    
    # CKA 分析
    analyzer = CKAAnalyzer(save_dir)
    
    print("Analyzing Q vs V similarity...")
    analyzer.analyze_qv_similarity(decoupled_model, images)
    
    print("Analyzing Integrated vs Decoupled similarity...")
    analyzer.analyze_integrated_vs_decoupled(decoupled_model, integrated_model, images)
    
    # 可视化
    matrix, labels = analyzer.create_comparison_matrix()
    analyzer.visualize_cka_matrix(matrix, labels, save_name="cka_comparison.png")
    
    # 保存结果
    analyzer.print_summary()
    analyzer.save_results()
    
    print("Done!")


if __name__ == "__main__":
    print("CKA Analysis Tool")
    print("Usage:")
    print("  from decoupling_analysis.cka_analysis import CKAAnalyzer, cka")
    print("  analyzer = CKAAnalyzer('save_dir')")
    print("  analyzer.analyze_qv_similarity(model, images)")
    print("  analyzer.analyze_integrated_vs_decoupled(dec_model, int_model, images)")