File size: 17,165 Bytes
74349a1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | """How well do the four classic rewards (HPSv3, PickScore, ImageReward,
UnifiedReward) align with each other?
We pool all (model, benchmark) cells from sheet_exports/alignment.txt, z-score
each (reward, benchmark) so cross-benchmark scales are comparable, then show:
1. ``reward_alignment_pairgrid.{png,pdf}`` — 4×4 pair grid:
diagonal = KDE of each reward's pooled distribution
lower-tri = pairwise scatter, colour-coded by benchmark
upper-tri = Pearson r (large) + Spearman ρ (small)
2. ``reward_alignment_density.{png,pdf}`` — single panel overlay of the four
z-scored marginal KDEs.
"""
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 scipy.stats import gaussian_kde, pearsonr, spearmanr
from sklearn.decomposition import PCA
ROOT = Path(__file__).resolve().parent
SRC = ROOT.parent.parent / "sheet_exports" / "alignment.txt"
# 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,
})
REWARDS = ["HPSv3", "PickScore", "ImageReward", "UnifiedReward-9B"]
DISPLAY = {
"HPSv3": "HPSv3",
"PickScore": "PickScore",
"ImageReward": "ImageReward",
"UnifiedReward-9B": "UnifiedReward",
}
# Skip: t2icorebench composite (kept via its split components),
# plus sciencet2i / wise per current scope.
SKIP_BENCHES = {"t2icorebench", "t2icorebench_reasoning", "sciencet2i", "wise"}
# Two-tone palette: 边缘 (字体 / 条形 / region 边线) 用饱和色,region 内部用浅色。
# 按色相对应: 蓝 = ImageReward, 橙 = HPSv3, 红 = UnifiedReward-9B, 绿 = PickScore.
EDGE_COLORS = {
"HPSv3": "#e59837", # 橙
"PickScore": "#5cb360", # 绿 (与 fill 相同)
"ImageReward": "#3a8dde", # 蓝
"UnifiedReward-9B": "#d94f4f", # 红
}
FILL_COLORS = {
"HPSv3": "#ffdaae", # 浅橙
"PickScore": "#bcebbd", # 浅绿
"ImageReward": "#b1d9ff", # 浅蓝
"UnifiedReward-9B": "#ffb5b5", # 浅红
}
# COLORS 保留, 给 bar / label 用饱和色。
COLORS = EDGE_COLORS
def parse_sections(path: Path) -> dict[str, pd.DataFrame]:
text = path.read_text()
out: dict[str, pd.DataFrame] = {}
for m in re.finditer(r"=== (\S+) ===\n(.*?)(?=\n=== |\Z)", text, re.DOTALL):
name = m.group(1)
if name in SKIP_BENCHES:
continue
body = m.group(2).strip().splitlines()
header = body[0].split("\t")
rows = [ln.split("\t") for ln in body[1:] if ln.strip()]
df = pd.DataFrame(rows, columns=header).set_index("Model")
df = df.apply(pd.to_numeric, errors="coerce")
out[name] = df
return out
def build_long_df(sections: dict[str, pd.DataFrame]) -> pd.DataFrame:
"""One row per (benchmark, model) with z-scored reward columns."""
frames = []
for bench, df in sections.items():
sub = df[REWARDS].copy()
sub = (sub - sub.mean()) / sub.std(ddof=0)
sub["benchmark"] = bench
sub["model"] = df.index
frames.append(sub.reset_index(drop=True))
return pd.concat(frames, ignore_index=True)
def lighten(color, amount: float = 0.5):
r, g, b = mcolors.to_rgb(color)
return (r + (1 - r) * amount, g + (1 - g) * amount, b + (1 - b) * amount)
def darken(color, amount: float = 0.35):
r, g, b = mcolors.to_rgb(color)
return (r * (1 - amount), g * (1 - amount), b * (1 - amount))
# Labels / bar fills / region 边框: 纯正 Google 配色, 不做 darken / lighten。
LABEL_COLORS = dict(COLORS)
# ─── BAR CHART KNOBS — edit these to tweak the upper-right bar chart ──
# The bar right-edge is anchored at a FIXED data position (right_anchor=1.0),
# so changing bar_length_scale only stretches bars LEFTWARD — the right edge
# stays locked to bar_ax's right spine regardless of scale.
BAR_CHART = dict(
block_rows=(0,), # which 4×4 grid rows the chart spans
block_cols=(1, 2, 3), # which 4×4 grid cols the chart spans
pad_x_left=0.04, # left padding inside the block (room for value text overflow)
pad_x_right=0.15, # right padding (reserved for name text; names right-aligned to matrix right)
pad_top=0.1, # top padding inside the block
pad_bottom=0.06, # bottom padding inside the block
bar_height=0.05, # bar thickness as fraction of FIGURE height; bigger → bar_ax grows taller
bar_gap=0.04, # gap between bars as fraction of FIGURE height; bigger → bar_ax grows taller
baseline_gap=0.02, # smaller = bigger length-difference ratio
bar_length_scale=5.0, # bigger = longer bars (xlim_lo auto-extends to fit)
xlim_pad_left=0.12, # extra data-space left of longest bar (for value text)
value_fontsize=16, # numeric label fontsize
name_fontsize=16, # reward name fontsize
text_offset=0.012, # x gap between bar end and adjacent text
)
# bar_ax height (in figure coords) = 4*bar_height + 3*bar_gap. Top is anchored
# at the top of block_rows; bottom bar moves DOWN as bar_height/bar_gap grow,
# possibly overlapping cells in row 1 / etc. (which is fine — they're empty).
# ─────────────────────────────────────────────────────────────────────
# ---------- figure 1: pair grid ----------
def _kde_region(ax, coords: np.ndarray, weights: np.ndarray,
edge_color: str, fill_color: str,
xlim: tuple[float, float], ylim: tuple[float, float],
mass_level: float = 0.5, bw: float = 0.45,
grid_n: int = 180,
fill_alpha: float = 0.55) -> None:
"""Filled 2D-KDE contour: lighter fill_color inside, saturated edge_color outline."""
xs = np.linspace(xlim[0], xlim[1], grid_n)
ys = np.linspace(ylim[0], ylim[1], grid_n)
X, Y = np.meshgrid(xs, ys)
grid = np.vstack([X.ravel(), Y.ravel()])
w = np.clip(weights, 0, None)
if w.sum() == 0:
return
kde = gaussian_kde(coords.T, weights=w, bw_method=bw)
Z = kde(grid).reshape(X.shape)
flat = np.sort(Z.ravel())[::-1]
cum = np.cumsum(flat)
cum /= cum[-1]
idx = np.searchsorted(cum, mass_level)
level = flat[min(idx, len(flat) - 1)]
ax.contourf(X, Y, Z, levels=[level, Z.max() + 1e-9],
colors=[fill_color], alpha=fill_alpha, zorder=2)
ax.contour(X, Y, Z, levels=[level], colors=[edge_color],
linewidths=2.0, zorder=3)
def plot_pairgrid(long_df: pd.DataFrame, out_stem: Path) -> None:
"""Pair grid where:
diagonal = each reward's PCA-based KDE region
lower triangle = the two rewards' regions overlaid + Pearson r
upper triangle = blank (axes hidden)
"""
n = len(REWARDS)
# Cells to embed: drop any row missing a reward column.
df = long_df.dropna(subset=REWARDS).reset_index(drop=True)
M = df[REWARDS].to_numpy()
pca = PCA(n_components=2)
coords = pca.fit_transform(M)
# Crop tightly around where the regions actually live: bounding box of
# cells whose weight (reward z-score) is positive for *any* reward,
# using a generous percentile to ignore far outliers.
# Compute the union bbox of every reward's actual region (where the KDE
# exceeds the 50%-mass level), so the panels are framed by what's drawn
# rather than by where cells happen to land.
full_xlim = (coords[:, 0].min() - 1.0, coords[:, 0].max() + 1.0)
full_ylim = (coords[:, 1].min() - 1.0, coords[:, 1].max() + 1.0)
region_xs, region_ys = [], []
grid_n = 220
xs_g = np.linspace(full_xlim[0], full_xlim[1], grid_n)
ys_g = np.linspace(full_ylim[0], full_ylim[1], grid_n)
Xg, Yg = np.meshgrid(xs_g, ys_g)
grid_pts = np.vstack([Xg.ravel(), Yg.ravel()])
for r in REWARDS:
w = np.clip(df[r].to_numpy(), 0, None)
if w.sum() == 0:
continue
kde = gaussian_kde(coords.T, weights=w, bw_method=0.45)
Z = kde(grid_pts).reshape(Xg.shape)
flat = np.sort(Z.ravel())[::-1]
cum = np.cumsum(flat) / flat.sum()
level = flat[min(np.searchsorted(cum, 0.5), len(flat) - 1)]
mask = Z >= level
if mask.any():
region_xs.extend(Xg[mask].tolist())
region_ys.extend(Yg[mask].tolist())
rxs = np.array(region_xs)
rys = np.array(region_ys)
qx_lo, qx_hi = rxs.min(), rxs.max()
qy_lo, qy_hi = rys.min(), rys.max()
xrange = qx_hi - qx_lo
yrange = qy_hi - qy_lo
xlim = (qx_lo - 0.14 * xrange, qx_hi + 0.14 * xrange)
ylim = (qy_lo - 0.20 * yrange, qy_hi + 0.20 * yrange)
fig, axes = plt.subplots(n, n, figsize=(13.5, 6.0),
gridspec_kw=dict(wspace=0.0, hspace=0.0))
for i, ri in enumerate(REWARDS):
for j, rj in enumerate(REWARDS):
ax = axes[i, j]
if i < j:
ax.axis("off")
continue
if i == j:
_kde_region(ax, coords, df[ri].to_numpy(),
EDGE_COLORS[ri], FILL_COLORS[ri], xlim, ylim)
ax.text(0.04, 0.95, DISPLAY[ri], transform=ax.transAxes,
fontsize=17, color=LABEL_COLORS[ri], fontweight="bold",
ha="left", va="top")
else:
_kde_region(ax, coords, df[rj].to_numpy(),
EDGE_COLORS[rj], FILL_COLORS[rj], xlim, ylim)
_kde_region(ax, coords, df[ri].to_numpy(),
EDGE_COLORS[ri], FILL_COLORS[ri], xlim, ylim)
xs = df[rj].to_numpy()
ys = df[ri].to_numpy()
r_val = pearsonr(xs, ys)[0]
ax.text(0.04, 0.95, f"r = {r_val:.2f}",
transform=ax.transAxes, ha="left", va="top",
fontsize=17, fontweight="bold", color="0.15")
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.xaxis.set_major_locator(
plt.FixedLocator(np.linspace(xlim[0], xlim[1], 5)))
ax.yaxis.set_major_locator(
plt.FixedLocator(np.linspace(ylim[0], ylim[1], 5)))
ax.tick_params(labelbottom=False, labelleft=False, length=0)
ax.grid(True, color="0.82", linewidth=0.5, alpha=0.8, zorder=1)
for spine in ax.spines.values():
spine.set_linewidth(0.8)
fig.tight_layout(pad=0.2)
# Figure-level PC1 / PC2 labels, centered on the whole 4×4 matrix.
matrix_left = axes[0, 0].get_position().x0
matrix_right = axes[n - 1, n - 1].get_position().x1
matrix_bottom = axes[n - 1, 0].get_position().y0
matrix_top = axes[0, 0].get_position().y1
fig.text((matrix_left + matrix_right) / 2, matrix_bottom - 0.020,
"PC1", ha="center", va="top", fontsize=20)
fig.text(matrix_left - 0.010, (matrix_bottom + matrix_top) / 2,
"PC2", ha="right", va="center", fontsize=20, rotation=90)
# Bar chart in the upper-right area — controlled by the BAR_CHART dict.
cfg = BAR_CHART
block_cells = [axes[i, j].get_position()
for i in cfg["block_rows"] for j in cfg["block_cols"]]
bx0 = min(p.x0 for p in block_cells)
bx1 = max(p.x1 for p in block_cells)
by0 = min(p.y0 for p in block_cells)
by1 = max(p.y1 for p in block_cells)
block_w = bx1 - bx0
block_h = by1 - by0
mx_left = block_w * cfg["pad_x_left"]
mx_right = block_w * cfg["pad_x_right"]
my_top = block_h * cfg["pad_top"]
# bar_ax PHYSICAL height (figure coords) is driven by bar_height + bar_gap
# so that growing those values pushes the bottom bar downward.
n_bars = len(REWARDS)
bar_ax_h = n_bars * cfg["bar_height"] + (n_bars - 1) * cfg["bar_gap"]
bar_ax_top = by1 - my_top # always anchored to top of block
bar_ax = fig.add_axes([bx0 + mx_left, bar_ax_top - bar_ax_h,
block_w - mx_left - mx_right,
bar_ax_h])
# Render the bar chart BEHIND every matrix panel so any region/diagonal
# cell the bar passes through cleanly covers the bar.
bar_ax.set_zorder(-1)
for ax_row in axes:
for ax in ax_row:
ax.set_zorder(1)
# Matrix panels need transparent backgrounds where they're "off"
# (upper-tri); for visible cells keep their white fill so they
# fully occlude the bar chart underneath.
pairs = []
for r in REWARDS:
others = [pearsonr(df[r].to_numpy(), df[r2].to_numpy())[0]
for r2 in REWARDS if r2 != r]
pairs.append((r, float(np.mean(others))))
pairs.sort(key=lambda x: -x[1]) # longest bar at top
sorted_rewards = [r for r, _ in pairs]
sorted_means = [m for _, m in pairs]
# In axis-y (ylim=0..1), bars fill the chart exactly: bar+gap fractions =
# bar_height/total and bar_gap/total of axis height.
bh = cfg["bar_height"] / bar_ax_h
bg = cfg["bar_gap"] / bar_ax_h
spacing = bh + bg
top_y = 1.0 - bh / 2
y_pos = np.array([top_y - i * spacing for i in range(n_bars)])
baseline = min(sorted_means) - cfg["baseline_gap"]
widths = [(m - baseline) * cfg["bar_length_scale"] for m in sorted_means]
# Right anchor is FIXED — bars always end at xlim_hi (= bar_ax right spine).
right_anchor = 1.0
left_anchors = [right_anchor - w for w in widths]
bar_colors = [FILL_COLORS[r] for r in sorted_rewards]
bar_ax.barh(y_pos, widths, left=left_anchors, color=bar_colors,
edgecolor="white", linewidth=1.0, alpha=1.0,
height=bh, zorder=3)
bar_ax.set_xlim(min(left_anchors) - cfg["xlim_pad_left"], right_anchor)
bar_ax.set_ylim(0, 1)
# Drawn via fig.text so labels sit ABOVE every matrix panel (axes zorder
# doesn't affect figure-level artists). Values right-aligned at each bar's
# left end; names left-aligned at common x past bar right.
def _to_fig(xd, yd):
disp = bar_ax.transData.transform((xd, yd))
return fig.transFigure.inverted().transform(disp)
for y, r, m, lo in zip(y_pos, sorted_rewards, sorted_means, left_anchors,
strict=False):
fx, fy = _to_fig(lo - cfg["text_offset"], y)
fig.text(fx, fy, f"{m:.2f}", ha="right", va="center",
fontsize=cfg["value_fontsize"], color="0.15",
fontweight="bold")
nfx, nfy = _to_fig(right_anchor + cfg["text_offset"], y)
fig.text(nfx, nfy, DISPLAY[r], ha="left", va="center",
fontsize=cfg["name_fontsize"], color=LABEL_COLORS[r],
fontweight="bold")
bar_ax.set_xticks([])
bar_ax.set_yticks([])
for spine in bar_ax.spines.values():
spine.set_visible(False)
fig.savefig(out_stem.with_suffix(".pdf"), bbox_inches="tight")
plt.close(fig)
print(f"wrote {out_stem.name}.pdf")
# ---------- figure 2: marginal density overlay ----------
def plot_density_overlay(long_df: pd.DataFrame, out_stem: Path) -> None:
fig, ax = plt.subplots(figsize=(8, 4.4))
pooled = long_df[REWARDS].to_numpy().ravel()
pooled = pooled[~np.isnan(pooled)]
lo, hi = np.quantile(pooled, [0.005, 0.995])
pad = (hi - lo) * 0.05
lo, hi = lo - pad, hi + pad
grid = np.linspace(lo, hi, 300)
for r in REWARDS:
vals = long_df[r].dropna().to_numpy()
kde = gaussian_kde(vals, bw_method=0.4)
ys = kde(grid)
ax.fill_between(grid, ys, color=COLORS[r], alpha=0.18, zorder=2)
ax.plot(grid, ys, color=COLORS[r], lw=2.5, zorder=3, label=DISPLAY[r])
ax.set_xlim(lo, hi)
ax.set_xlabel("Score (z-scored within each benchmark)", fontsize=13)
ax.set_ylabel("Density", fontsize=13)
ax.set_yticks([])
ax.tick_params(axis="x", labelsize=11)
ax.grid(True, axis="x", linestyle=":", linewidth=0.5, alpha=0.5)
for spine in ("top", "right"):
ax.spines[spine].set_visible(False)
ax.legend(fontsize=12, frameon=False, loc="upper right", handlelength=2.2)
fig.tight_layout()
fig.savefig(out_stem.with_suffix(".png"), dpi=200, bbox_inches="tight")
fig.savefig(out_stem.with_suffix(".pdf"), bbox_inches="tight")
plt.close(fig)
print(f"wrote {out_stem.name}.png / .pdf")
def main() -> None:
sections = parse_sections(SRC)
print("benchmarks pooled:", sorted(sections.keys()))
long_df = build_long_df(sections)
print(f"pooled rows: {len(long_df)} (= {len(sections)} benchmarks × ~{long_df['model'].nunique()} models)")
plot_pairgrid(long_df, ROOT / "reward_alignment_pairgrid")
if __name__ == "__main__":
main()
|