Images / figures /benchmark /plot_benchmark_overview.py
Jialuo21's picture
Add figures (155 files)
74349a1 verified
Raw History Blame Contribute Delete
9.62 kB
"""Benchmark overview scatter.
X-axis: average prompt length (words) per benchmark.
Y-axis: average MLLM-Judge performance across all evaluated models, normalised
to the benchmark's native max score so values land in [0, 1].
Marker: filled circle whose area is proportional to the benchmark's prompt count.
Data source:
- sheet_exports/alignment.txt -> per-benchmark MLLM_Judge scores per model
- HuggingFace datasets -> prompt counts and average prompt length
"""
from __future__ import annotations
import re
from pathlib import Path
from statistics import mean
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
from datasets import load_dataset
ROOT = Path(__file__).resolve().parent
SRC = ROOT.parent.parent / "sheet_exports" / "alignment.txt"
_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"
# Display name, native score max (used to normalise the judge column to [0, 1]).
BENCHMARKS = {
"longbencht2i": {"display": "LongBench-T2I", "score_max": 5.0},
"spatialgeneval": {"display": "SpatialGenEval", "score_max": 100.0},
"t2icompbench": {"display": "T2I-CompBench", "score_max": 5.0},
"t2icorebench_composition": {"display": "T2I-CoReBench", "score_max": 1.0},
"tiifbench": {"display": "TIIF-Bench", "score_max": 1.0},
}
# ---------------------------------------------------------------------------
# Per-benchmark label tweaks. Edit only this block to change how each label
# is rendered.
# fontsize : text size in points
# dx, dy : offset in points from the bubble center
# (positive dy = above, negative = below; positive dx = right)
# ha, va : matplotlib horizontal/vertical alignment ("left"/"center"/"right",
# "top"/"center"/"bottom"). va="auto" places the label just outside
# the bubble's top edge automatically.
# ---------------------------------------------------------------------------
LABEL_STYLE: dict[str, dict] = {
"longbencht2i": {"fontsize": 11, "dx": 40, "dy": -5, "ha": "center", "va": "auto"},
"spatialgeneval": {"fontsize": 11, "dx": -5, "dy": -60, "ha": "center", "va": "auto"},
"t2icompbench": {"fontsize": 11, "dx": 0, "dy": -5, "ha": "center", "va": "auto"},
"t2icorebench_composition": {"fontsize": 11, "dx": 10, "dy": -5, "ha": "center", "va": "auto"},
"tiifbench": {"fontsize": 11, "dx": 0, "dy": -8, "ha": "center", "va": "auto"},
}
# (HF dataset path, callable returning the list of generated prompt strings)
HF_SOURCES = {
"longbencht2i": ("Jialuo21/LongBench-T2I", lambda d: list(d["prompt"])),
"spatialgeneval": ("Jialuo21/SpatialGenEval", lambda d: list(d["prompt"])),
"t2icompbench": ("Jialuo21/T2I_CompBench", lambda d: list(d["prompt"])),
"t2icorebench_composition": (
"Jialuo21/T2I-CoReBench",
lambda d: [p for p, t in zip(d["Prompt"], d["task"], strict=False) if str(t).startswith("C-")],
),
# TIIF-Bench's default plan emits both the short and long description per row.
"tiifbench": ("Jialuo21/TIIF-Bench",
lambda d: list(d["short_description"]) + list(d["long_description"])),
}
def parse_alignment(path: Path) -> dict[str, dict[str, float]]:
"""Return {benchmark_name: {model: judge_score}}."""
text = path.read_text()
blocks = re.split(r"=== (\w+) ===\n", text)
out: dict[str, dict[str, float]] = {}
for i in range(1, len(blocks), 2):
name = blocks[i].strip()
body = blocks[i + 1].strip().splitlines()
if not body:
continue
header = body[0].split("\t")
try:
judge_idx = header.index(JUDGE_COL)
except ValueError:
continue
scores: dict[str, float] = {}
for row in body[1:]:
cells = row.split("\t")
if len(cells) <= judge_idx:
continue
cell = cells[judge_idx].strip()
if not cell or cell == "-":
continue
try:
scores[cells[0]] = float(cell)
except ValueError:
continue
if scores:
out[name] = scores
return out
def benchmark_prompt_stats() -> dict[str, dict[str, float]]:
stats: dict[str, dict[str, float]] = {}
for key, (path, getter) in HF_SOURCES.items():
ds = load_dataset(path, split="test")
prompts = [str(p).strip() for p in getter(ds) if str(p).strip()]
stats[key] = {
"count": float(len(prompts)),
"avg_words": float(mean(len(p.split()) for p in prompts)),
}
return stats
def main() -> None:
judge = parse_alignment(SRC)
prompt_stats = benchmark_prompt_stats()
rows = []
for key, meta in BENCHMARKS.items():
if key not in judge:
continue
avg_score = mean(judge[key].values()) / meta["score_max"]
rows.append({
"key": key,
"display": meta["display"],
"x": prompt_stats[key]["avg_words"],
"y": avg_score,
"size": prompt_stats[key]["count"],
})
# Pastel colors keyed by avg prompt-length bucket.
def bucket_color(x: float) -> str:
if x < 100:
return "#A8D5FF" # short prompts (light blue)
if x <= 500:
return "#FFD6A5" # medium prompts (light orange)
return "#FFADAD" # long prompts (light red)
fig, ax = plt.subplots(figsize=(7.6, 4.0))
sizes = np.array([r["size"] for r in rows])
# Map prompt count -> marker area (points^2).
s_min, s_max = 600.0, 4200.0
if sizes.max() > sizes.min():
size_norm = (sizes - sizes.min()) / (sizes.max() - sizes.min())
else:
size_norm = np.zeros_like(sizes, dtype=float)
marker_areas = s_min + size_norm * (s_max - s_min)
for r, area in zip(rows, marker_areas, strict=False):
ax.scatter(
r["x"], r["y"],
s=area,
facecolor=bucket_color(r["x"]),
edgecolor="white",
linewidth=1.2,
alpha=0.9,
zorder=3,
)
for r, area in zip(rows, marker_areas, strict=False):
radius_pts = np.sqrt(area / np.pi)
style = LABEL_STYLE.get(r["key"], {})
fontsize = style.get("fontsize", 11)
ha = style.get("ha", "center")
va = style.get("va", "auto")
dx = style.get("dx", 0)
dy = style.get("dy", 0)
# va="auto" places the label just above the bubble's edge.
if va == "auto":
xytext = (dx, dy + radius_pts + 6)
va_final = "bottom"
else:
xytext = (dx, dy)
va_final = va
ax.annotate(
r["display"],
xy=(r["x"], r["y"]),
xytext=xytext,
textcoords="offset points",
ha=ha, va=va_final,
fontsize=fontsize,
zorder=4,
)
ax.set_xscale("log")
ax.set_ylabel("Score", fontsize=15)
ax.tick_params(axis="both", labelsize=13)
ax.grid(True, which="major", linestyle="--", linewidth=0.5, alpha=0.5, zorder=1)
for boundary in (100, 500):
ax.axvline(boundary, color="black", linestyle=(0, (10, 8)),
linewidth=1.0, alpha=0.85, zorder=2)
from matplotlib.ticker import FixedLocator, NullLocator
ax.xaxis.set_minor_locator(NullLocator())
ax.xaxis.set_major_locator(FixedLocator([10, 100, 500]))
ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda v, _: f"{int(v)}"))
for side in ("top", "left", "right"):
ax.spines[side].set_visible(False)
xs = np.array([r["x"] for r in rows])
ys = np.array([r["y"] for r in rows])
ax.set_xlim(xs.min() * 0.55, xs.max() * 3.0)
pad = 0.02 * (ys.max() - ys.min() + 1e-9)
ax.set_ylim(ys.min() - pad - 0.02, ys.max() + pad + 0.04)
# Bucket labels centered (geometric mean) inside each region, sitting just
# above the x-axis. Color each label with its bucket's bubble color
# (slightly darkened for legibility against the white background).
xlo, xhi = ax.get_xlim()
bucket_centers = [
("short", np.sqrt(xlo * 100), "#3A8DDE", "bottom"), # darker blue, below
("medium", np.sqrt(100 * 500), "#E59837", "top"), # darker orange, above
("long", np.sqrt(500 * xhi), "#D94F4F", "top"), # darker red, above
]
trans = ax.get_xaxis_transform() # x in data coords, y in axes fraction
for label, x_center, color, position in bucket_centers:
if position == "bottom":
y_frac, va = 0.04, "bottom"
else:
y_frac, va = 0.96, "top"
ax.text(
x_center, y_frac, label,
transform=trans,
ha="center", va=va,
fontsize=14,
color=color,
family=["Comic Sans MS", "Chalkboard SE", "DejaVu Sans"],
fontweight="bold",
zorder=5,
)
fig.tight_layout()
out_png = ROOT / "benchmark_overview.png"
out_pdf = ROOT / "benchmark_overview.pdf"
fig.savefig(out_png, dpi=200)
fig.savefig(out_pdf)
print(f"saved {out_png}")
print(f"saved {out_pdf}")
if __name__ == "__main__":
main()