| |
| """ |
| 梯度冲突分析可视化 - 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])) |
| |
| |
| 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) |
| |
| |
| 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') |
| |
| |
| 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() |
|
|