File size: 18,792 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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#!/usr/bin/env python3
"""
梯度冲突分析可视化 - Gradient Conflict Analysis Visualization

基于 gradient_analysis.jsonl 数据绘制高质量论文图表。

可视化内容:
1. 全局余弦相似度随训练迭代变化
2. 逐层余弦相似度热力图
3. 逐层冲突比例柱状图
4. 余弦相似度分布直方图
"""

import json
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.colors import TwoSlopeNorm
from collections import defaultdict


# 配置
GRADIENT_DATA_PATH = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/decoupling_analysis/gradient_analysis/data/gradient_analysis.jsonl"
OUTPUT_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/decoupling_analysis/gradient_analysis/results"

# 绘图配置
SMOOTHING_WINDOW = 5


def setup_plot_style():
    """设置顶会论文级别的绘图风格。"""
    plt.style.use('seaborn-v0_8-whitegrid')
    plt.rcParams.update({
        'font.family': 'serif',
        'font.serif': ['Times New Roman', 'DejaVu Serif'],
        'font.size': 11,
        'axes.labelsize': 13,
        'axes.titlesize': 14,
        'axes.titleweight': 'bold',
        'xtick.labelsize': 11,
        'ytick.labelsize': 11,
        'legend.fontsize': 11,
        'figure.dpi': 150,
        'savefig.dpi': 300,
        'savefig.bbox': 'tight',
        'savefig.pad_inches': 0.1,
        'axes.linewidth': 1.2,
        'grid.linewidth': 0.8,
        'grid.alpha': 0.3,
        'lines.linewidth': 2.0,
    })


def load_gradient_data(filepath: str) -> tuple:
    """
    加载梯度分析数据。
    
    Returns:
        (iterations, layer_data, global_data)
        - iterations: 迭代次数列表
        - layer_data: {layer_name: [cos_sim_list]}
        - global_data: 全局余弦相似度列表(如果有)
    """
    iterations = []
    layer_data = defaultdict(list)
    global_data = []
    
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            record = json.loads(line.strip())
            iterations.append(record['iteration'])
            
            layer_cos_sims = record.get('layer_cos_sims', {})
            for layer_name, cos_sim in layer_cos_sims.items():
                layer_data[layer_name].append(cos_sim)
            
            if 'global' in record:
                global_data.append(record['global'])
    
    return iterations, dict(layer_data), global_data


def smooth_data(data: np.ndarray, window: int) -> np.ndarray:
    """使用滑动平均平滑数据。"""
    if window <= 1 or len(data) < window:
        return data
    kernel = np.ones(window) / window
    smoothed = np.convolve(data, kernel, mode='same')
    for i in range(window // 2):
        smoothed[i] = np.mean(data[:i + window // 2 + 1])
        smoothed[-(i + 1)] = np.mean(data[-(i + window // 2 + 1):])
    return smoothed


def compute_statistics(layer_data: dict) -> dict:
    """计算统计信息。"""
    stats = {}
    
    for layer_name, cos_sims in layer_data.items():
        cos_array = np.array(cos_sims)
        stats[layer_name] = {
            'mean': float(np.mean(cos_array)),
            'std': float(np.std(cos_array)),
            'min': float(np.min(cos_array)),
            'max': float(np.max(cos_array)),
            'conflict_ratio': float(np.mean(cos_array < 0)),  # 冲突比例
            'orthogonal_ratio': float(np.mean(np.abs(cos_array) < 0.1)),  # 正交比例
            'positive_ratio': float(np.mean(cos_array > 0)),  # 正向比例
        }
    
    # 计算全局统计
    all_values = []
    for cos_sims in layer_data.values():
        all_values.extend(cos_sims)
    
    if all_values:
        all_array = np.array(all_values)
        stats['overall'] = {
            'mean': float(np.mean(all_array)),
            'std': float(np.std(all_array)),
            'conflict_ratio': float(np.mean(all_array < 0)),
            'orthogonal_ratio': float(np.mean(np.abs(all_array) < 0.1)),
        }
    
    return stats


def plot_cosine_similarity_over_iterations(
    iterations: list,
    layer_data: dict,
    output_path: str
):
    """绘制余弦相似度随迭代变化的曲线。"""
    fig, ax = plt.subplots(figsize=(10, 6))
    
    # 排序层名
    layer_names = sorted(layer_data.keys(), key=lambda x: int(x.split('_')[1]))
    
    # 使用colormap
    cmap = plt.cm.viridis
    colors = [cmap(i / len(layer_names)) for i in range(len(layer_names))]
    
    iters = np.array(iterations)
    
    for layer_name, color in zip(layer_names, colors):
        cos_sims = np.array(layer_data[layer_name])
        cos_smooth = smooth_data(cos_sims, SMOOTHING_WINDOW)
        
        # 只画平滑后的曲线,避免过于杂乱
        layer_idx = layer_name.split('_')[1]
        ax.plot(iters, cos_smooth, color=color, linewidth=1.5, 
                label=f'Layer {layer_idx}', alpha=0.8)
    
    # 添加零线
    ax.axhline(y=0, color='red', linestyle='--', linewidth=2, alpha=0.7, label='Conflict Boundary')
    
    ax.set_xlabel('Iteration')
    ax.set_ylabel('Gradient Cosine Similarity')
    ax.set_title('Gradient Cosine Similarity Over Training')
    ax.legend(loc='upper right', ncol=2, fontsize=9, framealpha=0.9)
    ax.grid(True, alpha=0.3)
    
    # 设置y轴范围
    ax.set_ylim(-0.5, 0.5)
    
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()
    print(f"已保存: {output_path}")


def plot_layer_heatmap(
    iterations: list,
    layer_data: dict,
    output_path: str
):
    """绘制逐层余弦相似度热力图。"""
    # 排序层名
    layer_names = sorted(layer_data.keys(), key=lambda x: int(x.split('_')[1]))
    
    # 构建矩阵
    matrix = np.array([layer_data[name] for name in layer_names])
    
    fig, ax = plt.subplots(figsize=(14, 6))
    
    # 使用发散色图,0为中心
    norm = TwoSlopeNorm(vmin=-0.4, vcenter=0, vmax=0.4)
    im = ax.imshow(matrix, aspect='auto', cmap='RdBu_r', norm=norm,
                   extent=[iterations[0], iterations[-1], len(layer_names)-0.5, -0.5])
    
    # 设置y轴标签
    ax.set_yticks(range(len(layer_names)))
    ax.set_yticklabels([f'Layer {name.split("_")[1]}' for name in layer_names])
    
    ax.set_xlabel('Iteration')
    ax.set_ylabel('ViT Block')
    ax.set_title('Gradient Cosine Similarity Heatmap')
    
    # 添加colorbar
    cbar = plt.colorbar(im, ax=ax, shrink=0.8)
    cbar.set_label('Cosine Similarity', rotation=270, labelpad=15)
    
    # 添加注释
    ax.text(iterations[-1] * 1.02, len(layer_names) * 0.25, 'Conflict\n(< 0)', 
            fontsize=10, color='#B22222', va='center')
    ax.text(iterations[-1] * 1.02, len(layer_names) * 0.75, 'Aligned\n(> 0)', 
            fontsize=10, color='#4169E1', va='center')
    
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()
    print(f"已保存: {output_path}")


def plot_conflict_ratio_bar(
    stats: dict,
    output_path: str
):
    """绘制逐层冲突比例柱状图。"""
    # 排序层(排除overall)
    layer_names = [k for k in stats.keys() if k != 'overall']
    layer_names = sorted(layer_names, key=lambda x: int(x.split('_')[1]))
    
    conflict_ratios = [stats[name]['conflict_ratio'] * 100 for name in layer_names]
    orthogonal_ratios = [stats[name]['orthogonal_ratio'] * 100 for name in layer_names]
    positive_ratios = [stats[name]['positive_ratio'] * 100 for name in layer_names]
    
    x = np.arange(len(layer_names))
    width = 0.6
    
    fig, ax = plt.subplots(figsize=(10, 6))
    
    # 堆叠柱状图
    bars1 = ax.bar(x, conflict_ratios, width, label='Conflict (cos < 0)', 
                   color='#E94F37', alpha=0.85)
    bars2 = ax.bar(x, orthogonal_ratios, width, bottom=conflict_ratios,
                   label='Orthogonal (|cos| < 0.1)', color='#F5A623', alpha=0.85)
    
    # 计算aligned部分(既不是冲突也不是正交的正向部分)
    aligned_ratios = [max(0, 100 - c - o) for c, o in zip(conflict_ratios, orthogonal_ratios)]
    bars3 = ax.bar(x, aligned_ratios, width, 
                   bottom=[c + o for c, o in zip(conflict_ratios, orthogonal_ratios)],
                   label='Aligned (cos > 0.1)', color='#2E86AB', alpha=0.85)
    
    ax.set_xlabel('ViT Block')
    ax.set_ylabel('Percentage (%)')
    ax.set_title('Gradient Conflict Ratio by Layer')
    ax.set_xticks(x)
    ax.set_xticklabels([f'{name.split("_")[1]}' for name in layer_names])
    ax.legend(loc='upper right', framealpha=0.9)
    ax.set_ylim(0, 100)
    ax.grid(True, alpha=0.3, axis='y')
    
    # 添加平均冲突比例线
    avg_conflict = stats['overall']['conflict_ratio'] * 100
    ax.axhline(y=avg_conflict, color='#E94F37', linestyle='--', linewidth=2, alpha=0.7)
    ax.text(len(layer_names) - 0.5, avg_conflict + 2, f'Avg: {avg_conflict:.1f}%', 
            fontsize=10, color='#E94F37', ha='right')
    
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()
    print(f"已保存: {output_path}")


def plot_cosine_distribution(
    layer_data: dict,
    output_path: str
):
    """绘制余弦相似度分布直方图。"""
    # 收集所有数据
    all_values = []
    for cos_sims in layer_data.values():
        all_values.extend(cos_sims)
    
    all_array = np.array(all_values)
    
    fig, ax = plt.subplots(figsize=(10, 6))
    
    # 直方图
    bins = np.linspace(-0.5, 0.5, 41)
    n, bins_edges, patches = ax.hist(all_array, bins=bins, edgecolor='white', 
                                      linewidth=0.5, alpha=0.85)
    
    # 根据值着色
    for i, (patch, left_edge) in enumerate(zip(patches, bins_edges[:-1])):
        right_edge = bins_edges[i + 1]
        center = (left_edge + right_edge) / 2
        if center < 0:
            patch.set_facecolor('#E94F37')  # 冲突 - 红色
        elif abs(center) < 0.1:
            patch.set_facecolor('#F5A623')  # 正交 - 橙色
        else:
            patch.set_facecolor('#2E86AB')  # 对齐 - 蓝色
    
    # 添加零线
    ax.axvline(x=0, color='black', linestyle='--', linewidth=2, alpha=0.7)
    
    # 添加统计信息
    conflict_pct = np.mean(all_array < 0) * 100
    orthogonal_pct = np.mean(np.abs(all_array) < 0.1) * 100
    
    textstr = f'Conflict: {conflict_pct:.1f}%\nOrthogonal: {orthogonal_pct:.1f}%\nMean: {np.mean(all_array):.3f}'
    props = dict(boxstyle='round', facecolor='white', alpha=0.9)
    ax.text(0.02, 0.98, textstr, transform=ax.transAxes, fontsize=11,
            verticalalignment='top', bbox=props)
    
    # 添加图例
    legend_elements = [
        mpatches.Patch(facecolor='#E94F37', label='Conflict (cos < 0)'),
        mpatches.Patch(facecolor='#F5A623', label='Orthogonal (|cos| < 0.1)'),
        mpatches.Patch(facecolor='#2E86AB', label='Aligned (cos > 0.1)')
    ]
    ax.legend(handles=legend_elements, loc='upper right', framealpha=0.9)
    
    ax.set_xlabel('Gradient Cosine Similarity')
    ax.set_ylabel('Frequency')
    ax.set_title('Distribution of Gradient Cosine Similarity')
    ax.grid(True, alpha=0.3, axis='y')
    
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()
    print(f"已保存: {output_path}")


def plot_mean_cosine_by_layer(
    stats: dict,
    output_path: str
):
    """绘制每层平均余弦相似度。"""
    layer_names = [k for k in stats.keys() if k != 'overall']
    layer_names = sorted(layer_names, key=lambda x: int(x.split('_')[1]))
    
    means = [stats[name]['mean'] for name in layer_names]
    stds = [stats[name]['std'] for name in layer_names]
    
    x = np.arange(len(layer_names))
    
    fig, ax = plt.subplots(figsize=(10, 6))
    
    # 柱状图带误差棒
    colors = ['#E94F37' if m < 0 else '#2E86AB' for m in means]
    bars = ax.bar(x, means, color=colors, alpha=0.85, edgecolor='white', linewidth=1)
    ax.errorbar(x, means, yerr=stds, fmt='none', color='black', capsize=4, capthick=1.5, elinewidth=1.5)
    
    # 添加零线
    ax.axhline(y=0, color='black', linestyle='-', linewidth=1.5)
    
    ax.set_xlabel('ViT Block')
    ax.set_ylabel('Mean Cosine Similarity')
    ax.set_title('Mean Gradient Cosine Similarity by Layer')
    ax.set_xticks(x)
    ax.set_xticklabels([f'{name.split("_")[1]}' for name in layer_names])
    ax.grid(True, alpha=0.3, axis='y')
    
    # 添加数值标签
    for bar, mean in zip(bars, means):
        height = bar.get_height()
        va = 'bottom' if height >= 0 else 'top'
        offset = 0.01 if height >= 0 else -0.01
        ax.annotate(f'{mean:.3f}',
                   xy=(bar.get_x() + bar.get_width() / 2, height + offset),
                   ha='center', va=va, fontsize=9, fontweight='bold')
    
    plt.tight_layout()
    plt.savefig(output_path)
    plt.close()
    print(f"已保存: {output_path}")


def plot_paper_figure(
    iterations: list,
    layer_data: dict,
    stats: dict,
    output_path_png: str,
    output_path_pdf: str
):
    """绘制论文用组合图 (1x3)。"""
    fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
    
    # 排序层名
    layer_names = sorted(layer_data.keys(), key=lambda x: int(x.split('_')[1]))
    
    # ====== 图1: 热力图 ======
    ax1 = axes[0]
    matrix = np.array([layer_data[name] for name in layer_names])
    norm = TwoSlopeNorm(vmin=-0.4, vcenter=0, vmax=0.4)
    im = ax1.imshow(matrix, aspect='auto', cmap='RdBu_r', norm=norm,
                    extent=[iterations[0], iterations[-1], len(layer_names)-0.5, -0.5])
    ax1.set_yticks(range(len(layer_names)))
    ax1.set_yticklabels([f'{name.split("_")[1]}' for name in layer_names])
    ax1.set_xlabel('Iteration')
    ax1.set_ylabel('Layer')
    ax1.set_title('(a) Cosine Similarity Heatmap', fontweight='bold')
    cbar = plt.colorbar(im, ax=ax1, shrink=0.8)
    cbar.set_label('Cosine Sim.', rotation=270, labelpad=10, fontsize=10)
    
    # ====== 图2: 平均余弦相似度 ======
    ax2 = axes[1]
    means = [stats[name]['mean'] for name in layer_names]
    stds = [stats[name]['std'] for name in layer_names]
    x = np.arange(len(layer_names))
    colors = ['#E94F37' if m < 0 else '#2E86AB' for m in means]
    bars = ax2.bar(x, means, color=colors, alpha=0.85, edgecolor='white', linewidth=1)
    ax2.errorbar(x, means, yerr=stds, fmt='none', color='black', capsize=3, capthick=1, elinewidth=1)
    ax2.axhline(y=0, color='black', linestyle='-', linewidth=1.5)
    ax2.set_xlabel('Layer')
    ax2.set_ylabel('Mean Cosine Similarity')
    ax2.set_title('(b) Mean Similarity by Layer', fontweight='bold')
    ax2.set_xticks(x)
    ax2.set_xticklabels([f'{name.split("_")[1]}' for name in layer_names])
    ax2.grid(True, alpha=0.3, axis='y')
    
    # ====== 图3: 冲突比例 ======
    ax3 = axes[2]
    conflict_ratios = [stats[name]['conflict_ratio'] * 100 for name in layer_names]
    orthogonal_ratios = [stats[name]['orthogonal_ratio'] * 100 for name in layer_names]
    aligned_ratios = [max(0, 100 - c - o) for c, o in zip(conflict_ratios, orthogonal_ratios)]
    
    bars1 = ax3.bar(x, conflict_ratios, 0.6, label='Conflict', color='#E94F37', alpha=0.85)
    bars2 = ax3.bar(x, orthogonal_ratios, 0.6, bottom=conflict_ratios,
                    label='Orthogonal', color='#F5A623', alpha=0.85)
    bars3 = ax3.bar(x, aligned_ratios, 0.6, 
                    bottom=[c + o for c, o in zip(conflict_ratios, orthogonal_ratios)],
                    label='Aligned', color='#2E86AB', alpha=0.85)
    
    ax3.set_xlabel('Layer')
    ax3.set_ylabel('Percentage (%)')
    ax3.set_title('(c) Gradient Conflict Ratio', fontweight='bold')
    ax3.set_xticks(x)
    ax3.set_xticklabels([f'{name.split("_")[1]}' for name in layer_names])
    ax3.legend(loc='upper right', fontsize=9, framealpha=0.9)
    ax3.set_ylim(0, 100)
    ax3.grid(True, alpha=0.3, axis='y')
    
    plt.tight_layout()
    plt.savefig(output_path_png)
    plt.savefig(output_path_pdf)
    plt.close()
    print(f"已保存: {output_path_png}")
    print(f"已保存: {output_path_pdf}")


def main():
    setup_plot_style()
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    print("=" * 60)
    print("梯度冲突分析可视化")
    print("=" * 60)
    
    # 加载数据
    print(f"加载数据: {GRADIENT_DATA_PATH}")
    iterations, layer_data, global_data = load_gradient_data(GRADIENT_DATA_PATH)
    print(f"  迭代次数: {len(iterations)}")
    print(f"  层数: {len(layer_data)}")
    
    # 计算统计
    stats = compute_statistics(layer_data)
    
    print()
    print("=" * 60)
    print("生成图表")
    print("=" * 60)
    
    # 1. 余弦相似度随迭代变化
    plot_cosine_similarity_over_iterations(
        iterations, layer_data,
        os.path.join(OUTPUT_DIR, 'cosine_similarity_over_iterations.png')
    )
    
    # 2. 热力图
    plot_layer_heatmap(
        iterations, layer_data,
        os.path.join(OUTPUT_DIR, 'cosine_similarity_heatmap.png')
    )
    
    # 3. 冲突比例柱状图
    plot_conflict_ratio_bar(
        stats,
        os.path.join(OUTPUT_DIR, 'conflict_ratio_by_layer.png')
    )
    
    # 4. 分布直方图
    plot_cosine_distribution(
        layer_data,
        os.path.join(OUTPUT_DIR, 'cosine_similarity_distribution.png')
    )
    
    # 5. 每层平均余弦相似度
    plot_mean_cosine_by_layer(
        stats,
        os.path.join(OUTPUT_DIR, 'mean_cosine_by_layer.png')
    )
    
    # 6. 论文用组合图
    plot_paper_figure(
        iterations, layer_data, stats,
        os.path.join(OUTPUT_DIR, 'gradient_analysis_paper.png'),
        os.path.join(OUTPUT_DIR, 'gradient_analysis_paper.pdf')
    )
    
    # 7. 保存统计数据
    stats_path = os.path.join(OUTPUT_DIR, 'statistics.json')
    with open(stats_path, 'w', encoding='utf-8') as f:
        json.dump(stats, f, indent=2, ensure_ascii=False)
    print(f"已保存: {stats_path}")
    
    print()
    print("=" * 60)
    print("统计摘要")
    print("=" * 60)
    
    print(f"\n【全局统计】")
    overall = stats['overall']
    print(f"  平均余弦相似度: {overall['mean']:.4f} ± {overall['std']:.4f}")
    print(f"  冲突比例 (cos < 0): {overall['conflict_ratio']*100:.1f}%")
    print(f"  正交比例 (|cos| < 0.1): {overall['orthogonal_ratio']*100:.1f}%")
    
    print(f"\n【逐层统计】")
    layer_names = sorted([k for k in stats.keys() if k != 'overall'], 
                         key=lambda x: int(x.split('_')[1]))
    for name in layer_names:
        s = stats[name]
        print(f"  Layer {name.split('_')[1]}: mean={s['mean']:+.4f}, "
              f"conflict={s['conflict_ratio']*100:.1f}%")
    
    print()
    print("=" * 60)
    print("可视化完成!")
    print("=" * 60)


if __name__ == "__main__":
    main()