File size: 10,092 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
#!/usr/bin/env python3
"""
论文用简化图表 - 2张图讲清楚结论

图1: Total Loss 对比 (DeCLIP vs Integrated)
图2: 梯度冲突分析 (1×2: 分布 + 逐层趋势)
"""

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


# 配置
BASE_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private"
DECLIP_LOG = f"{BASE_DIR}/logs/DeCLIP_EVA-B_DINOv2-B_560/out.log"
INTEGRATED_2LOSS_LOG = f"{BASE_DIR}/logs/Integrated_EVA-B_DINOv2-B_560_2loss/out.log"
GRADIENT_2LOSS_PATH = f"{BASE_DIR}/logs/Integrated_EVA-B_DINOv2-B_560_grad_analysis_2loss/gradient_analysis.jsonl"
OUTPUT_DIR = f"{BASE_DIR}/decoupling_analysis/2loss/results/paper_figures"

SMOOTHING_WINDOW = 20

# 颜色
COLOR_DECLIP = '#2E86AB'      # 蓝色
COLOR_INTEGRATED = '#E94F37'  # 红色
COLOR_CONFLICT = '#E94F37'    # 红色
COLOR_ALIGNED = '#2E86AB'     # 蓝色


def setup_plot_style():
    """设置论文级别绘图风格"""
    plt.rcParams.update({
        'font.family': 'serif',
        'font.serif': ['Times New Roman', 'DejaVu Serif'],
        'font.size': 12,
        'axes.labelsize': 14,
        'axes.titlesize': 15,
        'axes.titleweight': 'bold',
        'xtick.labelsize': 12,
        'ytick.labelsize': 12,
        'legend.fontsize': 12,
        'figure.dpi': 150,
        'savefig.dpi': 300,
        'savefig.bbox': 'tight',
        'savefig.pad_inches': 0.1,
        'axes.linewidth': 1.5,
        'axes.spines.top': False,
        'axes.spines.right': False,
        'lines.linewidth': 2.5,
    })


def parse_training_log(log_path: str) -> list:
    """解析训练日志"""
    import re
    records = []
    with open(log_path, 'r', encoding='utf-8') as f:
        for line in f:
            if "Train Epoch:" not in line:
                continue
            try:
                total_match = re.search(r'Loss:\s*([\d.e+-]+)\s*\(', line)
                if total_match:
                    records.append(float(total_match.group(1)))
            except:
                continue
    return records


def load_gradient_data(filepath: str) -> dict:
    """加载梯度分析数据"""
    layer_data = defaultdict(list)
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            record = json.loads(line.strip())
            for layer_name, cos_sim in record.get('layer_cos_sims', {}).items():
                layer_data[layer_name].append(cos_sim)
    return dict(layer_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 plot_loss_comparison(declip_loss, integrated_loss, output_path):
    """
    图1: Total Loss 对比
    简洁版:只画 Total Loss,突出差距
    """
    min_len = min(len(declip_loss), len(integrated_loss))
    declip_loss = np.array(declip_loss[:min_len])
    integrated_loss = np.array(integrated_loss[:min_len])
    iters = np.arange(min_len)
    
    fig, ax = plt.subplots(figsize=(8, 5))
    
    # 绘制曲线
    ax.plot(iters, declip_loss, color=COLOR_DECLIP, alpha=0.15, linewidth=1.0)
    ax.plot(iters, smooth_data(declip_loss, SMOOTHING_WINDOW), 
            color=COLOR_DECLIP, linewidth=3, label='DeCLIP (Decoupled)')
    
    ax.plot(iters, integrated_loss, color=COLOR_INTEGRATED, alpha=0.15, linewidth=1.0)
    ax.plot(iters, smooth_data(integrated_loss, SMOOTHING_WINDOW), 
            color=COLOR_INTEGRATED, linewidth=3, label='Integrated')
    
    # 标注最终值
    final_declip = declip_loss[-1]
    final_integrated = integrated_loss[-1]
    
    # 添加水平虚线和数值标注
    ax.axhline(y=final_declip, color=COLOR_DECLIP, linestyle='--', alpha=0.5, linewidth=1.5)
    ax.axhline(y=final_integrated, color=COLOR_INTEGRATED, linestyle='--', alpha=0.5, linewidth=1.5)
    
    ax.text(min_len * 1.02, final_declip, f'{final_declip:.2f}', 
            color=COLOR_DECLIP, fontsize=14, fontweight='bold', va='center')
    ax.text(min_len * 1.02, final_integrated, f'{final_integrated:.2f}', 
            color=COLOR_INTEGRATED, fontsize=14, fontweight='bold', va='center')
    
    # 添加差距标注
    ratio = final_integrated / final_declip
    mid_y = (final_declip + final_integrated) / 2
    ax.annotate('', xy=(min_len * 0.95, final_declip), xytext=(min_len * 0.95, final_integrated),
                arrowprops=dict(arrowstyle='<->', color='gray', lw=2))
    ax.text(min_len * 0.92, mid_y, f'{ratio:.1f}×', fontsize=13, 
            color='gray', fontweight='bold', ha='right', va='center')
    
    ax.set_xlabel('Iteration')
    ax.set_ylabel('Total Loss')
    ax.set_title('Decoupled Distillation Converges Better')
    ax.legend(loc='upper right', framealpha=0.95)
    ax.set_xlim(0, min_len * 1.1)
    ax.set_ylim(0, max(integrated_loss) * 1.1)
    ax.grid(True, alpha=0.3, linestyle='-', linewidth=0.5)
    
    plt.tight_layout()
    plt.savefig(output_path.replace('.png', '.png'))
    plt.savefig(output_path.replace('.png', '.pdf'))
    plt.close()
    print(f"已保存: {output_path}")


def plot_gradient_analysis(layer_data, output_path):
    """
    图2: 梯度冲突分析 (1×2)
    左: 分布直方图
    右: 逐层趋势
    """
    # 收集所有数据
    all_values = []
    for cos_sims in layer_data.values():
        all_values.extend(cos_sims)
    all_array = np.array(all_values)
    
    # 计算统计
    conflict_ratio = np.mean(all_array < 0) * 100
    mean_cos = np.mean(all_array)
    
    # 逐层统计
    layer_names = sorted(layer_data.keys(), key=lambda x: int(x.split('_')[1]))
    layer_means = [np.mean(layer_data[name]) for name in layer_names]
    layer_stds = [np.std(layer_data[name]) for name in layer_names]
    layer_indices = [int(name.split('_')[1]) for name in layer_names]
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    
    # ===== 左图: 分布直方图 =====
    ax1 = axes[0]
    
    bins = np.linspace(-0.5, 0.5, 31)
    n, bins_edges, patches = ax1.hist(all_array, bins=bins, edgecolor='white', 
                                       linewidth=0.8, alpha=0.9)
    
    # 根据值着色
    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(COLOR_CONFLICT)
        else:
            patch.set_facecolor(COLOR_ALIGNED)
    
    # 添加零线
    ax1.axvline(x=0, color='black', linestyle='-', linewidth=2)
    
    # 添加统计标注框
    textstr = f'Conflict: {conflict_ratio:.0f}%\nMean: {mean_cos:.3f}'
    props = dict(boxstyle='round,pad=0.5', facecolor='white', alpha=0.95, edgecolor='gray')
    ax1.text(0.05, 0.95, textstr, transform=ax1.transAxes, fontsize=13,
             verticalalignment='top', bbox=props, fontweight='bold')
    
    # 图例
    legend_elements = [
        mpatches.Patch(facecolor=COLOR_CONFLICT, label='Conflict (cos < 0)'),
        mpatches.Patch(facecolor=COLOR_ALIGNED, label='Aligned (cos > 0)')
    ]
    ax1.legend(handles=legend_elements, loc='upper right', framealpha=0.95)
    
    ax1.set_xlabel('Gradient Cosine Similarity')
    ax1.set_ylabel('Frequency')
    ax1.set_title('(a) Distribution of Gradient Similarity')
    ax1.set_xlim(-0.55, 0.55)
    
    # ===== 右图: 逐层趋势 =====
    ax2 = axes[1]
    
    # 绘制柱状图
    colors = [COLOR_CONFLICT if m < 0 else COLOR_ALIGNED for m in layer_means]
    bars = ax2.bar(layer_indices, layer_means, color=colors, alpha=0.85, 
                   edgecolor='white', linewidth=1)
    ax2.errorbar(layer_indices, layer_means, yerr=layer_stds, fmt='none', 
                 color='black', capsize=4, capthick=1.5, elinewidth=1.5)
    
    # 零线
    ax2.axhline(y=0, color='black', linestyle='-', linewidth=1.5)
    
    # 添加趋势箭头和标注
    ax2.annotate('', xy=(11, layer_means[-1] - 0.05), xytext=(0, layer_means[0] + 0.05),
                 arrowprops=dict(arrowstyle='->', color='gray', lw=2, 
                               connectionstyle='arc3,rad=-0.2'))
    ax2.text(5.5, -0.38, 'Deeper = More Conflict', fontsize=11, 
             color='gray', ha='center', style='italic')
    
    ax2.set_xlabel('Layer Index')
    ax2.set_ylabel('Mean Cosine Similarity')
    ax2.set_title('(b) Conflict Increases in Deeper Layers')
    ax2.set_xticks(layer_indices)
    ax2.set_ylim(-0.45, 0.15)
    ax2.grid(True, alpha=0.3, axis='y', linestyle='-', linewidth=0.5)
    
    plt.tight_layout()
    plt.savefig(output_path)
    plt.savefig(output_path.replace('.png', '.pdf'))
    plt.close()
    print(f"已保存: {output_path}")


def main():
    setup_plot_style()
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    print("=" * 60)
    print("生成论文用图表")
    print("=" * 60)
    
    # 加载数据
    print("\n加载数据...")
    declip_loss = parse_training_log(DECLIP_LOG)
    integrated_loss = parse_training_log(INTEGRATED_2LOSS_LOG)
    layer_data = load_gradient_data(GRADIENT_2LOSS_PATH)
    
    print(f"  DeCLIP: {len(declip_loss)} 条记录")
    print(f"  Integrated: {len(integrated_loss)} 条记录")
    print(f"  梯度数据: {len(layer_data)} 层")
    
    # 生成图表
    print("\n生成图表...")
    
    # 图1: Loss 对比
    plot_loss_comparison(
        declip_loss, integrated_loss,
        os.path.join(OUTPUT_DIR, 'fig1_loss_comparison.png')
    )
    
    # 图2: 梯度冲突分析
    plot_gradient_analysis(
        layer_data,
        os.path.join(OUTPUT_DIR, 'fig2_gradient_analysis.png')
    )
    
    print("\n" + "=" * 60)
    print("完成!图表保存在:")
    print(f"  {OUTPUT_DIR}/")
    print("=" * 60)


if __name__ == "__main__":
    main()