File size: 9,623 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 | """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()
|