"""VQA reward-model size ablation - box plot. 每个 panel: 横坐标是 Base / 4B / 9B / 27B (四个 box),每个 box 概括 5 个 benchmark 的 normalised score (0~100)。FLUX 用红色渐变,Z-Image 用蓝色渐变。 要调样式只改下面 CONFIG dict 即可,其它代码逻辑不用动。 """ from __future__ import annotations import re from pathlib import Path import matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.ticker import MaxNLocator # ============================================================ # 全部可调参数都在这里 (CONFIG)。改这里就行。 # ============================================================ CONFIG = { # ---------- 整体布局 ---------- "figsize": (12.0, 4.8), # 整张图尺寸 (宽, 高)。当前 2.5:1。常用: 2:1 -> (12,6), 4:3 -> (12,9) "dpi": 200, # 输出 PNG 的分辨率 "out_stem": "reward_vqa_size_box", # 输出文件名 (不含扩展名),会同时写 .png 和 .pdf "tight_layout": True, # 是否调用 tight_layout 自动收紧白边 # ---------- 字体 ---------- "font_path": "../_fonts/STIX-Two-Text-Regular.ttf", # 字体 ttf 路径 (相对本脚本) "math_fontset": "stix", # 数学公式字体 ("stix" / "cm" / "dejavusans" 等) # ---------- X 轴 ---------- "x_step": 0.50, # 相邻 box 中心的水平间距,越小越挤 "x_margin": 0.30, # 第一个 / 最后一个 box 离 panel 边的留白 "x_labels": ["Base", "4B", "9B", "27B"], # 横坐标显示的文字 "xtick_fontsize": 20, # 横坐标字号 "tick_length": 7, # 刻度线长度 "tick_width": 1.6, # 刻度线粗细 "tick_direction": "out", # 刻度朝向: "in" / "out" / "inout" # ---------- Y 轴 ---------- "ylabel": "Score", # 纵坐标标题 "ylabel_fontsize": 20, # 纵坐标标题字号 "ytick_fontsize": 20, # 纵坐标刻度字号 "y_pad_frac": 0.10, # 上下留白 = 数据 range 的比例 "y_pad_min": 0.5, # 上下留白的最小值 (绝对单位) "y_nbins": 5, # Y 轴刻度数量上限 (matplotlib 自动取整) "y_integer_ticks": True, # Y 轴刻度是否强制为整数 # ---------- Box 形状 ---------- "box_width": 0.26, # 每个 box 的宽度,越大越胖 "show_fliers": False, # 是否画离群点 (5 个 benchmark 一般用不到) # ---------- Box 黑色框线 / whisker / 中位数 ---------- "outline_color": "black", # box 边、whisker、cap、中位数线的颜色 "box_edge_width": 2, # box 矩形边框粗细 "median_linewidth": 2, # 中位数横线粗细 "whisker_linewidth": 1.8, # 上下竖线 (whisker) 粗细 "cap_linewidth": 1.8, # whisker 顶端短横线粗细 # ---------- Box 填充颜色 (每个 panel 一个 Google 渐变, 浅→深 = Base→27B) ---------- # FLUX = 红色系, Z-Image = 蓝色系。Key 必须和下面 BASES 的 row 前缀一致。 "panel_colors": { "FLUX.2-4B": { "label": "FLUX.2-Klein-Base-4B", # 右下角 panel 名 "box_colors": ["#FAD2CF", "#F28B82", "#E04A3C", "#A50E0E"], # 4 个 box 的填充 "box_alpha": 0.90, # 填充透明度 "point_color": "black", # 散点颜色 (开启时) }, "Z-Image": { "label": "Z-Image", "box_colors": ["#E8F0FE", "#A0C2F5", "#4285F4", "#174EA6"], "box_alpha": 0.90, "point_color": "black", }, }, # ---------- 散点叠加 (show_points=True 时显示 5 个 benchmark 的实际值) ---------- "show_points": False, # 是否叠加散点 "point_size": 24, # 散点大小 "point_alpha": 0.75, # 散点透明度 "point_jitter": 0.06, # 散点水平抖动幅度 "point_edge": "white", # 散点描边颜色 "point_edge_w": 0.5, # 散点描边粗细 "point_zorder": 4, # 散点层级 (数字越大越在上层) "point_jitter_seed": 0, # 散点抖动随机种子 # ---------- 右下角 panel 名 (FLUX.2-4B / Z-Image) ---------- "panel_label_fontsize": 22, # 字号 "panel_label_xy": (0.95, 0.07), # 位置 (axes 坐标 0~1) "panel_label_ha": "right", # 水平对齐: "left" / "center" / "right" "panel_label_va": "bottom", # 竖直对齐: "top" / "center" / "bottom" "panel_label_weight": "normal", # 字重: "normal" / "bold" # ---------- panel 名外面的框 ---------- "panel_label_box": True, # 是否给 panel 名加框 "panel_label_box_style": "round,pad=0.3", # 框样式: "square,pad=0.3" / "round,pad=0.4" 等 "panel_label_box_face": "white", # 框填充色 ("none" = 透明) "panel_label_box_edge": "black", # 框边线颜色 "panel_label_box_lw": 1.6, # 框边线粗细 "panel_label_box_alpha": 1.0, # 框填充透明度 # ---------- 边框 (spines) ---------- "show_all_spines": True, # True = 四边都显示, False = 只显示底边 "spine_linewidth": 2.0, # 边框粗细 "spine_color": "black", # 边框颜色 # ---------- 背景网格 ---------- "show_grid": True, # 是否显示网格 (True / False) "grid_axis": "both", # 网格方向: "y" / "x" / "both" "grid_linestyle": "--", # 网格线型: ":" 点线 / "--" 虚线 / "-" 实线 / "-." 点划线 "grid_linewidth": 2.0, # 网格粗细 "grid_color": "0.7", # 网格颜色 (灰阶 "0"~"1" 或 hex; 越接近 1 越浅) "grid_alpha": 0.5, # 网格透明度 0~1 "grid_zorder": 0, # 网格层级 (越小越在底层, 0 = box 后面) } # ============================================================ # 数据 layout (一般不用改 — 改了会影响数据加载)。 # ============================================================ ROOT = Path(__file__).resolve().parent SRC = ROOT.parent.parent / "sheet_exports" / "reward_ablation.txt" BENCHMARKS = [ "TIIF-Bench", "T2I-CompBench", "SpatialGenEval", "T2I-CoReBench-Composition", "LongBench-T2I", ] BOUNDS = { # 每个 benchmark 的理论上下界 (用来归一化到 0~100) "T2I-CoReBench-Composition": (0.0, 100.0), "TIIF-Bench": (0.0, 100.0), "T2I-CompBench": (1.0, 5.0), "LongBench-T2I": (1.0, 5.0), "SpatialGenEval": (0.0, 100.0), } VARIANTS = ["Base", "VQA-4B", "VQA-9B", "VQA-27B"] # 每个 panel 的 4 个 box (从左到右) BASES = [("FLUX.2-Klein-4B-Base", "FLUX.2-4B"), # (展示名, row 前缀) ("Z-Image", "Z-Image")] # ============================================================ # 字体注册 (rcParams) # ============================================================ _font_path = (ROOT / CONFIG["font_path"]).resolve() fm.fontManager.addfont(str(_font_path)) _FAMILY = fm.FontProperties(fname=str(_font_path)).get_name() plt.rcParams.update({ "font.family": _FAMILY, "font.serif": [_FAMILY, "DejaVu Serif"], "mathtext.fontset": CONFIG["math_fontset"], "axes.unicode_minus": False, }) # ============================================================ # 数据加载 + 归一化 (一般不用改) # ============================================================ def load_summary(path: Path, table: str) -> pd.DataFrame: text = path.read_text() block = re.search(rf"=== {re.escape(table)} ===\n(.*?)(?:\n=== |\Z)", text, re.DOTALL) if block is None: raise SystemExit(f"could not locate {table!r} in {path}") lines = [ln for ln in block.group(1).strip().splitlines() if ln.strip()] header = lines[0].split("\t") rows = [ln.split("\t") for ln in lines[1:]] df = pd.DataFrame(rows, columns=header).set_index("Models") return df.apply(pd.to_numeric, errors="coerce") def normalise(value: float, bench: str) -> float: lo, hi = BOUNDS[bench] return (value - lo) / (hi - lo) * 100.0 # ============================================================ # 绘图主流程 (基本只是把 CONFIG 套到 matplotlib API 上) # ============================================================ def main() -> None: cfg = CONFIG df1 = load_summary(SRC, "Table 1.Summary") df2 = load_summary(SRC, "Table 2.Summary") panel_norm: dict[str, np.ndarray] = {} for _, base_prefix in BASES: mat = np.full((len(VARIANTS), len(BENCHMARKS)), np.nan) for i, v in enumerate(VARIANTS): row = f"{base_prefix}-{v}" src = df1 if v == "Base" else df2 for j, bench in enumerate(BENCHMARKS): if row in src.index: mat[i, j] = normalise(float(src.loc[row, bench]), bench) panel_norm[base_prefix] = mat fig, axes = plt.subplots(1, 2, figsize=cfg["figsize"], sharey=False) rng = np.random.default_rng(cfg["point_jitter_seed"]) x_positions = 1.0 + np.arange(len(VARIANTS)) * cfg["x_step"] for ax, (_, base_prefix) in zip(axes, BASES): scheme = cfg["panel_colors"][base_prefix] mat = panel_norm[base_prefix] data = [mat[i, :][~np.isnan(mat[i, :])] for i in range(len(VARIANTS))] # ---- box ---- bp = ax.boxplot( data, positions=x_positions, widths=cfg["box_width"], patch_artist=True, showfliers=cfg["show_fliers"], medianprops={"color": cfg["outline_color"], "linewidth": cfg["median_linewidth"]}, whiskerprops={"color": cfg["outline_color"], "linewidth": cfg["whisker_linewidth"]}, capprops={"color": cfg["outline_color"], "linewidth": cfg["cap_linewidth"]}, boxprops={"edgecolor": cfg["outline_color"], "linewidth": cfg["box_edge_width"]}, ) for patch, fc in zip(bp["boxes"], scheme["box_colors"]): patch.set_facecolor(fc) patch.set_alpha(scheme["box_alpha"]) # ---- 可选: 散点叠加 ---- if cfg["show_points"]: for i, vals in enumerate(data): jitter = rng.uniform(-cfg["point_jitter"], cfg["point_jitter"], size=len(vals)) ax.scatter( np.full(len(vals), x_positions[i]) + jitter, vals, s=cfg["point_size"], color=scheme["point_color"], alpha=cfg["point_alpha"], edgecolor=cfg["point_edge"], linewidth=cfg["point_edge_w"], zorder=cfg["point_zorder"], ) # ---- 坐标轴范围 ---- flat = mat[~np.isnan(mat)] lo, hi = float(np.min(flat)), float(np.max(flat)) pad = max((hi - lo) * cfg["y_pad_frac"], cfg["y_pad_min"]) ax.set_ylim(lo - pad, hi + pad) ax.set_xlim(x_positions[0] - cfg["x_margin"], x_positions[-1] + cfg["x_margin"]) # ---- 刻度 / 字号 ---- ax.set_xticks(x_positions) ax.set_xticklabels(cfg["x_labels"], fontsize=cfg["xtick_fontsize"]) ax.tick_params(axis="y", labelsize=cfg["ytick_fontsize"], length=cfg["tick_length"], width=cfg["tick_width"], direction=cfg["tick_direction"]) ax.tick_params(axis="x", labelsize=cfg["xtick_fontsize"], length=cfg["tick_length"], width=cfg["tick_width"], direction=cfg["tick_direction"]) ax.yaxis.set_major_locator( MaxNLocator(nbins=cfg["y_nbins"], integer=cfg["y_integer_ticks"]) ) # ---- 网格 ---- if cfg["show_grid"]: ax.grid(True, axis=cfg["grid_axis"], linestyle=cfg["grid_linestyle"], linewidth=cfg["grid_linewidth"], color=cfg["grid_color"], alpha=cfg["grid_alpha"], zorder=cfg["grid_zorder"]) else: ax.grid(False) ax.set_axisbelow(True) # ---- 边框 (spines) ---- for side in ("top", "right", "left", "bottom"): ax.spines[side].set_visible(cfg["show_all_spines"] or side == "bottom") ax.spines[side].set_linewidth(cfg["spine_linewidth"]) ax.spines[side].set_color(cfg["spine_color"]) # ---- 右下角 panel 名 (可选加框) ---- bbox = None if cfg["panel_label_box"]: bbox = dict( boxstyle=cfg["panel_label_box_style"], facecolor=cfg["panel_label_box_face"], edgecolor=cfg["panel_label_box_edge"], linewidth=cfg["panel_label_box_lw"], alpha=cfg["panel_label_box_alpha"], ) ax.text( cfg["panel_label_xy"][0], cfg["panel_label_xy"][1], scheme["label"], transform=ax.transAxes, ha=cfg["panel_label_ha"], va=cfg["panel_label_va"], fontsize=cfg["panel_label_fontsize"], fontweight=cfg["panel_label_weight"], bbox=bbox, ) axes[0].set_ylabel(cfg["ylabel"], fontsize=cfg["ylabel_fontsize"]) if cfg["tight_layout"]: fig.tight_layout() out_stem = ROOT / cfg["out_stem"] fig.savefig(out_stem.with_suffix(".png"), dpi=cfg["dpi"], bbox_inches="tight") fig.savefig(out_stem.with_suffix(".pdf"), bbox_inches="tight") plt.close(fig) print(f"wrote {out_stem.with_suffix('.png').name} / .pdf") if __name__ == "__main__": main()