File size: 10,617 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 | #!/usr/bin/env python3
"""
梯度冲突分析可视化 - 2loss 版本
分析 Integrated_2loss 实验的梯度冲突情况。
"""
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/logs/Integrated_EVA-B_DINOv2-B_560_grad_analysis_2loss/gradient_analysis.jsonl"
OUTPUT_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/decoupling_analysis/2loss/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:
"""加载梯度分析数据。"""
iterations = []
layer_data = defaultdict(list)
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)
return iterations, dict(layer_data)
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_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')
# 添加平均冲突比例线
avg_conflict = stats['overall']['conflict_ratio'] * 100
ax3.axhline(y=avg_conflict, color='#E94F37', linestyle='--', linewidth=2, alpha=0.7)
ax3.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_png)
plt.savefig(output_path_pdf)
plt.close()
print(f"已保存: {output_path_png}")
print(f"已保存: {output_path_pdf}")
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 (2loss)')
ax.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.savefig(output_path)
plt.close()
print(f"已保存: {output_path}")
def main():
setup_plot_style()
os.makedirs(OUTPUT_DIR, exist_ok=True)
print("=" * 60)
print("梯度冲突分析可视化 (2loss)")
print("=" * 60)
# 加载数据
print(f"加载数据: {GRADIENT_DATA_PATH}")
iterations, layer_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)
# 论文用组合图
plot_paper_figure(
iterations, layer_data, stats,
os.path.join(OUTPUT_DIR, 'gradient_analysis_2loss_paper.png'),
os.path.join(OUTPUT_DIR, 'gradient_analysis_2loss_paper.pdf')
)
# 分布直方图
plot_cosine_distribution(
layer_data,
os.path.join(OUTPUT_DIR, 'cosine_similarity_distribution_2loss.png')
)
# 保存统计数据
stats_path = os.path.join(OUTPUT_DIR, 'gradient_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("统计摘要 (2loss)")
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()
|