| |
| """ |
| 绘制 2loss 实验的 Loss 曲线对比图。 |
| |
| 对比: DeCLIP vs Integrated_2loss |
| """ |
|
|
| import json |
| import os |
| import numpy as np |
| import matplotlib.pyplot as plt |
| from pathlib import Path |
|
|
|
|
| |
| DATA_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/decoupling_analysis/2loss/results/data" |
| OUTPUT_DIR = "/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/decoupling_analysis/2loss/results" |
|
|
| |
| SMOOTHING_WINDOW = 15 |
| COLORS = { |
| 'DeCLIP': '#2E86AB', |
| 'Integrated_2loss': '#E94F37', |
| } |
|
|
|
|
| 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_jsonl(filepath: str) -> list: |
| """加载JSONL文件。""" |
| data = [] |
| with open(filepath, 'r', encoding='utf-8') as f: |
| for line in f: |
| data.append(json.loads(line.strip())) |
| return data |
|
|
|
|
| def smooth_data(data: np.ndarray, window: int) -> np.ndarray: |
| """使用滑动平均平滑数据。""" |
| if window <= 1: |
| 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_paper_figure( |
| iters: np.ndarray, |
| declip_data: dict, |
| integrated_data: dict, |
| save_path_png: str, |
| save_path_pdf: str, |
| smoothing_window: int = SMOOTHING_WINDOW |
| ): |
| """绘制1x3论文用图。""" |
| fig, axes = plt.subplots(1, 3, figsize=(15, 4.5)) |
| |
| plot_configs = [ |
| (axes[0], 'loss_total', '(a) Total Loss'), |
| (axes[1], 'loss_content', '(b) Content Loss'), |
| (axes[2], 'loss_context', '(c) Context Loss'), |
| ] |
| |
| for ax, key, title in plot_configs: |
| for model_name, data, color in [ |
| ('DeCLIP', declip_data, COLORS['DeCLIP']), |
| ('Integrated (2loss)', integrated_data, COLORS['Integrated_2loss']) |
| ]: |
| y_data = np.array(data[key]) |
| ax.plot(iters, y_data, color=color, alpha=0.2, linewidth=1.0) |
| y_smooth = smooth_data(y_data, smoothing_window) |
| ax.plot(iters, y_smooth, color=color, linewidth=2.5, label=model_name) |
| |
| ax.set_xlabel('Iteration') |
| ax.set_ylabel('Loss') |
| ax.set_title(title, fontweight='bold') |
| ax.legend(loc='upper right', framealpha=0.9) |
| ax.grid(True, alpha=0.3) |
| |
| for spine in ax.spines.values(): |
| spine.set_linewidth(1.2) |
| |
| plt.tight_layout() |
| plt.savefig(save_path_png) |
| plt.savefig(save_path_pdf) |
| plt.close() |
| print(f"已保存: {save_path_png}") |
| print(f"已保存: {save_path_pdf}") |
|
|
|
|
| def compute_statistics(declip_data: dict, integrated_data: dict) -> dict: |
| """计算统计数据。""" |
| stats = {} |
| |
| for model_name, data in [('DeCLIP', declip_data), ('Integrated_2loss', integrated_data)]: |
| stats[model_name] = {} |
| for key in ['loss_total', 'loss_content', 'loss_context']: |
| values = np.array(data[key]) |
| stats[model_name][key] = { |
| 'mean': float(np.mean(values)), |
| 'std': float(np.std(values)), |
| 'min': float(np.min(values)), |
| 'max': float(np.max(values)), |
| 'final': float(values[-1]), |
| 'first': float(values[0]), |
| } |
| |
| return stats |
|
|
|
|
| def main(): |
| setup_plot_style() |
| os.makedirs(OUTPUT_DIR, exist_ok=True) |
| |
| print("=" * 60) |
| print("Loss曲线绘图工具 (2loss 版本)") |
| print("=" * 60) |
| |
| |
| declip_path = os.path.join(DATA_DIR, "declip_training.jsonl") |
| integrated_path = os.path.join(DATA_DIR, "integrated_2loss_training.jsonl") |
| |
| if not os.path.exists(declip_path) or not os.path.exists(integrated_path): |
| print("错误: 数据文件不存在,请先运行 extract_training_data.py") |
| return |
| |
| print("加载数据...") |
| declip_records = load_jsonl(declip_path) |
| integrated_records = load_jsonl(integrated_path) |
| |
| print(f" DeCLIP: {len(declip_records)} 条记录") |
| print(f" Integrated_2loss: {len(integrated_records)} 条记录") |
| |
| |
| min_len = min(len(declip_records), len(integrated_records)) |
| declip_records = declip_records[:min_len] |
| integrated_records = integrated_records[:min_len] |
| print(f" 截断后: {min_len} 条记录") |
| |
| |
| iters = np.arange(min_len) |
| |
| declip_data = { |
| 'loss_total': [r['loss_total'] for r in declip_records], |
| 'loss_content': [r['loss_content'] for r in declip_records], |
| 'loss_context': [r['loss_context'] for r in declip_records], |
| } |
| |
| integrated_data = { |
| 'loss_total': [r['loss_total'] for r in integrated_records], |
| 'loss_content': [r['loss_content'] for r in integrated_records], |
| 'loss_context': [r['loss_context'] for r in integrated_records], |
| } |
| |
| print() |
| print("=" * 60) |
| print("生成图表") |
| print("=" * 60) |
| |
| |
| plot_paper_figure( |
| iters, declip_data, integrated_data, |
| os.path.join(OUTPUT_DIR, 'loss_comparison_2loss_paper.png'), |
| os.path.join(OUTPUT_DIR, 'loss_comparison_2loss_paper.pdf') |
| ) |
| |
| |
| stats = compute_statistics(declip_data, integrated_data) |
| 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) |
| |
| for model in ['DeCLIP', 'Integrated_2loss']: |
| print(f"\n【{model}】") |
| for loss_type in ['loss_total', 'loss_content', 'loss_context']: |
| s = stats[model][loss_type] |
| print(f" {loss_type}: first={s['first']:.4f}, final={s['final']:.4f}, " |
| f"mean={s['mean']:.4f}, min={s['min']:.4f}") |
| |
| print() |
| print("=" * 60) |
| print("绘图完成!") |
| print("=" * 60) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|