"""Per-benchmark overlay: rewards vs MLLM_Judge in one panel. Both axes are min-max normalised to [0,1] per benchmark so all panels share identical [0,1] x [0,1] axes and a perfect aligner sits on the diagonal. Two figures are produced: Figure 1 (traditional rewards): CLIPScore, HPSv3, PickScore, UnifiedReward-9B, VQAScore-9B Figure 2 (VQA family): VQAScore-binary-9B, VQAScore-9B Each figure is a single row of 4 benchmark panels: longbencht2i, t2icompbench, t2icorebench_composition, tiifbench. """ from __future__ import annotations import re from pathlib import Path import matplotlib.colors as mcolors import matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.offsetbox import AnchoredOffsetbox, HPacker, TextArea, VPacker from matplotlib.patches import Polygon from scipy.stats import pearsonr ROOT = Path(__file__).resolve().parent SRC = ROOT.parent.parent / "sheet_exports" / "alignment.txt" # Register and select the shared STIX Two Text typeface. _FONT = ROOT.parent / "_fonts" / "STIX-Two-Text-Regular.ttf" fm.fontManager.addfont(str(_FONT)) _FAMILY = fm.FontProperties(fname=str(_FONT)).get_name() plt.rcParams.update({ "font.family": _FAMILY, "font.serif": [_FAMILY, "DejaVu Serif"], "mathtext.fontset": "stix", "axes.unicode_minus": False, }) JUDGE_COL = "MLLM_Judge" BENCHMARKS = ["t2icompbench", "tiifbench", "spatialgeneval", "t2icorebench_composition", "longbencht2i"] BENCHMARK_DISPLAY = { "t2icompbench": "T2I-CompBench", "tiifbench": "TIIFBench", "t2icorebench_composition": "T2I-CoReBench-\nComposition", "longbencht2i": "LongBench-T2I", "spatialgeneval": "SpatialGenEval", } GROUPS = { "rewards_classic": ["CLIPScore", "HPSv3", "PickScore", "ImageReward", "UnifiedReward-9B", "VQAScore-9B"], "rewards_vqa": ["VQAScore-binary-9B", "VQAScore-Gemma-4-E4B", "VQAScore-9B"], } # Google brand colors (+ Google purple for the 5th slot in the classic group) GOOGLE_BLUE = "#4285F4" GOOGLE_RED = "#EA4335" GOOGLE_YELLOW = "#FBBC05" GOOGLE_GREEN = "#34A853" GOOGLE_PURPLE = "#A142F4" # VQAScore-9B kept blue across both figures so the classic figure avoids a # collision with CLIPScore (also red); the VQA-family figure uses pure # Google brand colors (blue + red). GOOGLE_TEAL = "#00ACC1" GOOGLE_ORANGE = "#FF9800" COLORS = { "CLIPScore": GOOGLE_RED, "HPSv3": GOOGLE_YELLOW, "PickScore": GOOGLE_GREEN, "ImageReward": GOOGLE_TEAL, "UnifiedReward-9B": GOOGLE_PURPLE, "VQAScore-Gemma-4-E4B": GOOGLE_ORANGE, "VQAScore-9B": GOOGLE_BLUE, "VQAScore-binary-9B": GOOGLE_RED, } # Distinct marker per reward to disambiguate beyond color. MARKERS = { "CLIPScore": "s", # square "HPSv3": "P", # filled plus "PickScore": "D", # diamond "ImageReward": "*", # star "UnifiedReward-9B": "^", # triangle up "VQAScore-Gemma-4-E4B": "h", # hexagon "VQAScore-9B": "o", # circle (highlight) "VQAScore-binary-9B": "X", # filled x } # Per-marker visual scaling (some markers look smaller at the same area). MARKER_SCALE = { "s": 1.0, "P": 1.45, # plus needs more area to read clearly "D": 0.85, "*": 1.55, # star looks smaller at same area "^": 1.35, # triangle reads smaller too "h": 1.05, # hexagon "o": 1.0, "X": 1.15, } # --------------------------------------------------------------------------- # 视觉调节区 STYLE: 改下面这些数字就能调节图的字号 / 线宽 / 点大小 / 间距等 # --------------------------------------------------------------------------- STYLE = { # ---- 整张图的画布尺寸 (英寸) ---- # panel_w / panel_h 是单个 panel 的宽 / 高 (一共 2 行 × 3 列). # right_pad 是图右边留给 legend 的额外空白宽度 (越大空白越多). "panel_w": 3.8, # 单个 panel 宽 "panel_h": 2.5, # 单个 panel 高 (想整体拉高就调这个) "right_pad": 2.6, # 右侧给 legend 留的空白宽度 (英寸) # ---- 散点 panel 内, 右下角 benchmark 名字框 (T2I-CompBench 等) ---- "bench_label_fontsize": 15, # benchmark 名字框文字字号 "bench_label_x": 0.96, # 名字框水平位置 (1 = panel 最右) "bench_label_y": 0.07, # 名字框垂直位置 (0 = panel 最下) # ---- 散点 panel 坐标轴 ---- "panel_xlabel_fontsize": 16, # "Reward" 横坐标标题字号 "panel_ylabel_fontsize": 16, # "Score" 纵坐标标题字号 "panel_tick_fontsize": 14, # 散点 panel 刻度数字 (0.0 / 0.5 / 1.0) 字号 # ---- 散点 panel 内的散点和拟合线 ---- "scatter_highlight_line_width": 4, # 高亮 reward (VQAScore-9B) 拟合线粗 "scatter_highlight_point_size": 40, # 高亮 reward 散点大小 "scatter_other_line_width": 1.5, # 其他 reward 拟合线粗 "scatter_other_point_size": 32, # 其他 reward 散点大小 # ---- 中间下排的 r-vs-benchmark 折线图 ---- "line_xlabel_fontsize": 16, # "Benchmark" 横坐标标题字号 "line_ylabel_fontsize": 16, # "Pearson r" 纵坐标标题字号 "line_tick_fontsize": 14, # 折线图刻度数字字号 "line_highlight_line_width": 3, # 高亮 reward 折线粗细 "line_highlight_marker_size": 10, # 高亮 reward 折线上的点大小 "line_other_line_width": 2, # 其他 reward 折线粗细 "line_other_marker_size": 8, # 其他 reward 折线上的点大小 # ---- 右侧 legend (CLIPScore / HPSv3 / ... 那一列) ---- "legend_fontsize": 15, # legend 文字字号 "legend_marker_size": 12, # legend 上点的大小 (会按 MARKER_SCALE 再缩放) "legend_highlight_line_width": 3, # legend 上高亮 reward 的小线段粗细 "legend_other_line_width": 2.4, # legend 上其他 reward 的小线段粗细 "legend_handle_len": 2.4, # legend 上小线段的长度 "legend_label_spacing": 1.4, # legend 各项之间的垂直距离 (越大越松) "legend_x_offset": 0.2, # legend 相对 panel 区域右侧的水平偏移 (英寸) # ---- 中间下排折线图的 "纵坐标跳跃" (broken y-axis) ---- # 折线图会被切成上下两段, 中间用斜线断开. 两张图 (reward / vqa) 的范围不一样, # 所以下面分成两个子字典. main() 里给每张图传 split_key="reward" / "vqa". # 各字段含义: # low_min / low_max : 下半段纵坐标的下界 / 上界 # high_min / high_max: 上半段纵坐标的下界 / 上界 # height_ratio : (上半高度, 下半高度) 比例 — 写成跟 range 比例一致 # 画出来上下视觉密度就一样; 上半比下半大就是放大上半段 # hspace : 上下两段之间的间隙 (越大越分开) # break_size : 中间斜线小标记的大小 (axes 比例) # ylabel_x : "r" 标题相对 axes 的水平偏移 (越负越靠左) "line_split": { # alignment_reward 用: 上 0~1, 下 -1~-0.5 (中间 -0.5~0 被截掉) "reward": { "low_min": -1.0, "low_max": -0.4, "high_min": 0.1, "high_max": 1.1, "height_ratio": (2.5, 1.0), "hspace": 0.1, "break_size": 0.02, "ylabel_x": -0.13, }, # alignment_vqa 用: 上 0.95~1.0, 下 0.7~0.8 (中间 0.8~0.95 被截掉) "vqa": { "low_min": 0.7, "low_max": 0.8, "high_min": 0.95, "high_max": 1.0, "height_ratio": (3, 1.0), "hspace": 0.2, "break_size": 0.02, "ylabel_x": -0.13, }, }, } # --------------------------------------------------------------------------- def parse_sections(path: Path) -> dict[str, pd.DataFrame]: text = path.read_text() sections: dict[str, pd.DataFrame] = {} for match in re.finditer(r"=== (\S+) ===\n(.*?)(?=\n=== |\Z)", text, re.DOTALL): name = match.group(1) body = match.group(2).strip().splitlines() header = body[0].split("\t") rows = [line.split("\t") for line in body[1:] if line.strip()] df = pd.DataFrame(rows, columns=header).set_index("Model") df = df.apply(pd.to_numeric, errors="coerce") sections[name] = df return sections def lighten(color, amount: float = 0.6): """Mix toward white. amount=0 -> original, amount=1 -> white.""" r, g, b = mcolors.to_rgb(color) return (r + (1 - r) * amount, g + (1 - g) * amount, b + (1 - b) * amount) def minmax(x: np.ndarray) -> np.ndarray | None: if np.nanstd(x) == 0: return None return (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x)) HIGHLIGHT = "VQAScore-9B" # Display label override (data column name → legend label). DISPLAY_LABEL = { "VQAScore-binary-9B": "VQAScore-Binary", "VQAScore-Gemma-4-E4B": "VQAScore-Gemma", } def display_name(col: str) -> str: name = DISPLAY_LABEL.get(col, col) return re.sub(r"-\d+B$", "", name) def _draw_pearson_lines(ax, xs_idx: np.ndarray, rewards: list[str], rho_by_bench: dict[str, dict[str, float]]) -> None: """Draw the per-reward Pearson r line series onto a single axes.""" for col in rewards: ys = [rho_by_bench.get(b, {}).get(col, np.nan) for b in BENCHMARKS] is_hi = col == HIGHLIGHT base = COLORS[col] if is_hi: line_color = base marker_face = lighten(base, 0.30) marker_edge = base lw = STYLE["line_highlight_line_width"] ms = STYLE["line_highlight_marker_size"] else: line_color = (*lighten(base, 0.40), 0.75) marker_face = (*lighten(base, 0.60), 0.60) marker_edge = "white" lw = STYLE["line_other_line_width"] ms = STYLE["line_other_marker_size"] ax.plot(xs_idx, ys, color=line_color, lw=lw, marker=MARKERS[col], markersize=ms * (MARKER_SCALE[MARKERS[col]] ** 0.5), markerfacecolor=marker_face, markeredgecolor=marker_edge, markeredgewidth=0.6, zorder=5 if is_hi else 3) def plot_group(sections: dict[str, pd.DataFrame], rewards: list[str], out_stem: Path, legend_labels: dict[str, str] | None = None, split_key: str | None = None) -> None: """split_key: 如果传 "reward" / "vqa" 这种 STYLE['line_split'] 里的 key, 就启用 broken y-axis 并用对应那一组数值; 不传 (None) 就不分裂.""" split_y = split_key is not None split_cfg = STYLE["line_split"][split_key] if split_y else {} def split(key): return split_cfg[key] # Layout: 2 rows × 3 cols. Row 0 = first 3 benchmarks. Row 1 = [bench3, # r-vs-benchmark line plot, bench4]. So the middle of row 2 carries the # cross-benchmark r summary instead of a benchmark scatter panel. panels_w = STYLE["panel_w"] * 3 right_pad = STYLE["right_pad"] fig, axes = plt.subplots(2, 3, figsize=(panels_w + right_pad, STYLE["panel_h"] * 2)) panel_positions = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 2)] benchmark_axes = [axes[r, c] for r, c in panel_positions] line_ax = axes[1, 1] _stair_polygons: list[tuple] = [] # (top_packer, bot_packer, polygon, ax) rho_by_bench: dict[str, dict[str, float]] = {} for ax, bench in zip(benchmark_axes, BENCHMARKS): df = sections[bench] judge = df[JUDGE_COL].values y = minmax(judge) if y is None: ax.text(0.5, 0.5, "judge has no variance", transform=ax.transAxes, ha="center", va="center", color="gray") ax.text(STYLE["bench_label_x"], STYLE["bench_label_y"], BENCHMARK_DISPLAY[bench], transform=ax.transAxes, ha="right", va="bottom", fontsize=STYLE["bench_label_fontsize"], bbox=dict(boxstyle="round,pad=0.32", facecolor="white", edgecolor="0.7", linewidth=0.8, alpha=0.9)) continue # Plot non-highlight rewards first (lower zorder, lighter), then the # highlight reward on top with full saturation. ordered = [c for c in rewards if c != HIGHLIGHT] + [c for c in rewards if c == HIGHLIGHT] rho_per_reward: dict[str, float] = {} for col in ordered: vals = df[col].values mask = ~(np.isnan(vals) | np.isnan(judge)) x_raw = vals[mask] y_pts = y[mask] if len(x_raw) < 3: continue denom = x_raw.max() - x_raw.min() constant_x = denom == 0 if constant_x: # All values identical (e.g. binary judge collapsed to 0). Place # the points clustered at x=0 and draw a flat dotted line at # the y-mean so the reward still appears in the panel. x = np.zeros_like(x_raw, dtype=float) else: x = (x_raw - x_raw.min()) / denom base = COLORS[col] is_hi = col == HIGHLIGHT if is_hi: line_color = base pt_color = (*lighten(base, 0.30), 0.90) pt_edge = base lw = STYLE["scatter_highlight_line_width"] pt_size = STYLE["scatter_highlight_point_size"] z_line = 5 z_pt = 4 else: line_color = (*lighten(base, 0.40), 0.75) pt_color = (*lighten(base, 0.60), 0.60) pt_edge = "white" lw = STYLE["scatter_other_line_width"] pt_size = STYLE["scatter_other_point_size"] z_line = 3 z_pt = 2 ax.scatter(x, y_pts, color=pt_color, s=pt_size * MARKER_SCALE[MARKERS[col]], marker=MARKERS[col], edgecolor=pt_edge, linewidth=0.4, zorder=z_pt) xs = np.linspace(0, 1, 50) if constant_x: # No slope possible — flat dotted reference at the y mean. y_mean = float(np.nanmean(y_pts)) ax.plot(xs, np.full_like(xs, y_mean), color=line_color, lw=lw, linestyle=":", zorder=z_line) else: slope, intercept = np.polyfit(x, y_pts, 1) ax.plot(xs, slope * xs + intercept, color=line_color, lw=lw, zorder=z_line) rho_per_reward[col] = pearsonr(x_raw, judge[mask])[0] ax.text(STYLE["bench_label_x"], STYLE["bench_label_y"], BENCHMARK_DISPLAY[bench], transform=ax.transAxes, ha="right", va="bottom", fontsize=STYLE["bench_label_fontsize"], zorder=10, bbox=dict(boxstyle="round,pad=0.32", facecolor="white", edgecolor="0.7", linewidth=0.8, alpha=0.9)) ax.set_xlim(-0.03, 1.03) ax.set_ylim(-0.03, 1.03) ax.set_xticks([0.0, 0.5, 1.0]) ax.set_yticks([0.0, 0.5, 1.0]) ax.set_xlabel("Reward", fontsize=STYLE["panel_xlabel_fontsize"]) ax.set_ylabel("Score", fontsize=STYLE["panel_ylabel_fontsize"]) ax.tick_params(labelsize=STYLE["panel_tick_fontsize"]) ax.grid(True, color="0.75", linestyle="--", linewidth=0.7, alpha=0.85) rho_by_bench[bench] = rho_per_reward # ── r-vs-benchmark line plot in the middle of row 2 ─────────────────── xs_idx = np.arange(len(BENCHMARKS)) if split_y: # Replace the single cell with two stacked sub-axes (broken y-axis). gs = line_ax.get_subplotspec() line_ax.remove() inner = gs.subgridspec(2, 1, height_ratios=split("height_ratio"), hspace=split("hspace")) top_ax = fig.add_subplot(inner[0]) bot_ax = fig.add_subplot(inner[1]) _draw_pearson_lines(top_ax, xs_idx, rewards, rho_by_bench) _draw_pearson_lines(bot_ax, xs_idx, rewards, rho_by_bench) top_ax.set_ylim(split("high_min"), split("high_max")) bot_ax.set_ylim(split("low_min"), split("low_max")) for ax_part in (top_ax, bot_ax): ax_part.set_xticks(xs_idx) ax_part.set_xticklabels([]) ax_part.tick_params(axis="y", labelsize=STYLE["line_tick_fontsize"]) ax_part.grid(True, color="0.75", linestyle="--", linewidth=0.7, alpha=0.85) for side in ("top", "right", "left", "bottom"): ax_part.spines[side].set_visible(True) ax_part.spines[side].set_linewidth(0.8) # Hide the spines facing the break. top_ax.spines["bottom"].set_visible(False) bot_ax.spines["top"].set_visible(False) top_ax.tick_params(labelbottom=False, bottom=False) # Diagonal break marks. d = split("break_size") kw = dict(color="black", clip_on=False, lw=1.0) top_ax.plot((-d, +d), (-d, +d), transform=top_ax.transAxes, **kw) top_ax.plot((1 - d, 1 + d), (-d, +d), transform=top_ax.transAxes, **kw) bot_ax.plot((-d, +d), (1 - d, 1 + d), transform=bot_ax.transAxes, **kw) bot_ax.plot((1 - d, 1 + d), (1 - d, 1 + d), transform=bot_ax.transAxes, **kw) bot_ax.set_xlabel("Benchmark", fontsize=STYLE["line_xlabel_fontsize"]) # Centre the y-label vertically across BOTH sub-axes (and the gap). # In bot_ax axes-fraction coords: # bot_ax spans 0..1; gap above bot_ax = hspace * mean_h / h_bot; # top_ax spans (1+gap) .. (1+gap+h_top/h_bot). # Centre = average of bot_ax bottom (0) and top_ax top. bot_ax.set_ylabel("r", fontsize=STYLE["line_ylabel_fontsize"]) h_top, h_bot = split("height_ratio") gap_in_bot = split("hspace") * (h_top + h_bot) / (2 * h_bot) y_centre = (1.0 + gap_in_bot + h_top / h_bot) / 2.0 bot_ax.yaxis.set_label_coords(split("ylabel_x"), y_centre) else: _draw_pearson_lines(line_ax, xs_idx, rewards, rho_by_bench) line_ax.set_xticks(xs_idx) line_ax.set_xticklabels([]) line_ax.set_xlabel("Benchmark", fontsize=STYLE["line_xlabel_fontsize"]) line_ax.set_ylabel("r", fontsize=STYLE["line_ylabel_fontsize"]) line_ax.tick_params(axis="y", labelsize=STYLE["line_tick_fontsize"]) line_ax.grid(True, color="0.75", linestyle="--", linewidth=0.7, alpha=0.85) for side in ("top", "right", "left", "bottom"): line_ax.spines[side].set_visible(True) line_ax.spines[side].set_linewidth(0.8) handles = [] for name in rewards: is_hi = name == HIGHLIGHT face = lighten(COLORS[name], 0.30 if is_hi else 0.60) line_color = COLORS[name] if is_hi else (*lighten(COLORS[name], 0.40), 0.85) edge = COLORS[name] if is_hi else "white" handles.append(plt.Line2D( [0], [0], color=line_color, marker=MARKERS[name], markerfacecolor=face, markeredgecolor=edge, markersize=STYLE["legend_marker_size"] * (MARKER_SCALE[MARKERS[name]] ** 0.5), lw=STYLE["legend_highlight_line_width"] if is_hi else STYLE["legend_other_line_width"], label=(legend_labels or {}).get(name, display_name(name)))) legend_x = (panels_w + STYLE["legend_x_offset"]) / (panels_w + right_pad) fig.legend(handles=handles, loc="center left", ncol=1, bbox_to_anchor=(legend_x, 0.5), fontsize=STYLE["legend_fontsize"], frameon=False, labelspacing=STYLE["legend_label_spacing"], handlelength=STYLE["legend_handle_len"]) fig.tight_layout(rect=[0, 0, panels_w / (panels_w + right_pad), 1.0]) # Compute stair-step polygons after layout settles. fig.canvas.draw() renderer = fig.canvas.get_renderer() pad_px = 4 for top_p, bot_p, poly, ax in _stair_polygons: top_bb = top_p.get_window_extent(renderer) bot_bb = bot_p.get_window_extent(renderer) # Stair-step polygon (6 corners), clockwise from top-right. join_y = (top_bb.y0 + bot_bb.y1) / 2 px = np.array([ [top_bb.x1 + pad_px, top_bb.y1 + pad_px], # top-right [bot_bb.x1 + pad_px, bot_bb.y0 - pad_px], # bottom-right [bot_bb.x0 - pad_px, bot_bb.y0 - pad_px], # bottom-left [bot_bb.x0 - pad_px, join_y], # step up [top_bb.x0 - pad_px, join_y], # step right (under top row) [top_bb.x0 - pad_px, top_bb.y1 + pad_px], # up to top-left of top row ]) data_pts = ax.transData.inverted().transform(px) poly.set_xy(data_pts) fig.savefig(out_stem.with_suffix(".png"), dpi=200) fig.savefig(out_stem.with_suffix(".pdf")) plt.close(fig) def main() -> None: sections = parse_sections(SRC) missing = [b for b in BENCHMARKS if b not in sections] if missing: raise SystemExit(f"benchmarks not in source file: {missing}") plot_group(sections, GROUPS["rewards_classic"], ROOT / "alignment_reward", split_key="reward") plot_group(sections, GROUPS["rewards_vqa"], ROOT / "alignment_vqa", legend_labels={ "VQAScore-binary-9B": "Qwen3.5\n(Binary)", "VQAScore-Gemma-4-E4B": "Gemma", "VQAScore-9B": "Qwen3.5", }, split_key="vqa") print("wrote alignment_reward.{png,pdf} and alignment_vqa.{png,pdf}") if __name__ == "__main__": main()