| |
| """ |
| 梯度冲突分析可视化 - 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])) |
| |
| |
| 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) |
| |
| |
| 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)) |
| |
| |
| 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]) |
| |
| |
| 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') |
| |
| |
| 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 |
| ): |
| """绘制逐层冲突比例柱状图。""" |
| |
| 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_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])) |
| |
| |
| 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') |
| |
| 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) |
| |
| |
| plot_cosine_similarity_over_iterations( |
| iterations, layer_data, |
| os.path.join(OUTPUT_DIR, 'cosine_similarity_over_iterations.png') |
| ) |
| |
| |
| plot_layer_heatmap( |
| iterations, layer_data, |
| os.path.join(OUTPUT_DIR, 'cosine_similarity_heatmap.png') |
| ) |
| |
| |
| plot_conflict_ratio_bar( |
| stats, |
| os.path.join(OUTPUT_DIR, 'conflict_ratio_by_layer.png') |
| ) |
| |
| |
| plot_cosine_distribution( |
| layer_data, |
| os.path.join(OUTPUT_DIR, 'cosine_similarity_distribution.png') |
| ) |
| |
| |
| plot_mean_cosine_by_layer( |
| stats, |
| os.path.join(OUTPUT_DIR, 'mean_cosine_by_layer.png') |
| ) |
| |
| |
| 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') |
| ) |
| |
| |
| 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() |
|
|