visual-answerability / scripts /build_crossdomain_paper_assets.py
sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw History Blame Contribute Delete
6.94 kB
#!/usr/bin/env python3
"""Render the cross-domain manuscript assets from audited saved-response metrics."""
import argparse
from decimal import Decimal, ROUND_HALF_UP
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from analyze_crossdomain_paper import MODELS, STATES
NAMES = {"qwen38-flash-next": "Qwen 3.8 Flash Next", "gemma4-31b-it": "Gemma 4 31B",
"qwen": "Qwen 3.8 27B", "gemma4-26b-a4b-it": "Gemma 4 26B A4B",
"glm": "GLM 5.3 Flash", "molmo2-8b": "Molmo2-8B"}
def percentage(n, d, places=2):
return str((Decimal(int(n)) * 100 / Decimal(int(d))).quantize(Decimal(10) ** -places, rounding=ROUND_HALF_UP))
def pct(value, places=2):
# Metrics are sample means; remove insignificant summation noise before formatting.
return str(Decimal(str(round(value * 100, 9))).quantize(Decimal(10) ** -places, rounding=ROUND_HALF_UP))
def table(path, header, rows, columns):
path.write_text("\n".join([r"\begin{tabular}{@{}" + columns + r"@{}}", r"\toprule",
header + r" \\", r"\midrule", *rows,
r"\bottomrule", r"\end{tabular}"]) + "\n")
def model_table(data, path):
"""Report complete task success before its decision diagnostics."""
rows = []
for model in MODELS:
cells = []
for source in STATES:
domain = data["domains"][source]
counts = domain["models"][model]["counts"]
cells.extend([
percentage(counts["joint_groups_correct"], 1000, 1),
percentage(counts["groups_correct"], 1000, 1),
percentage(counts["failures"], domain["views"]),
])
rows.append(NAMES[model] + " & " + " & ".join(cells) + r" \\")
rows.extend([
r"\midrule",
r"Always answerable & 0.0 & 0.0 & 40.00 & 0.0 & 0.0 & 25.00 & 0.0 & 0.0 & 33.33 \\",
r"Always unanswerable & 0.0 & 0.0 & 60.00 & 0.0 & 0.0 & 75.00 & 0.0 & 0.0 & 66.67 \\",
])
header = (
r"& \multicolumn{3}{c}{PlotQA} & \multicolumn{3}{c}{CLEVR} & \multicolumn{3}{c}{GQA} \\ "
r"\cmidrule(lr){2-4}\cmidrule(lr){5-7}\cmidrule(l){8-10} "
r"System & $J_5\uparrow$ & $B_5\uparrow$ & $E\downarrow$ "
r"& $J_4\uparrow$ & $B_4\uparrow$ & $E\downarrow$ "
r"& $J_3\uparrow$ & $B_3\uparrow$ & $E\downarrow$"
)
table(path, header, rows, "lrrrrrrrrr")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--analysis", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
data = json.loads(args.analysis.read_text())
out = args.output
out.mkdir(parents=True, exist_ok=True)
domains = data["domains"]
model_table(data, out / "model_table.tex")
rows = []
for model in MODELS:
cells = []
for source in STATES:
m = domains[source]["models"][model]["metrics"]
cells.extend([pct(m["balanced_failure"]), pct(m["common_state_failure"])])
rows.append(NAMES[model] + " & " + " & ".join(cells) + r" \\")
rows += [r"\midrule", r"Always answerable & 50.00 & 33.33 & 50.00 & 33.33 & 50.00 & 33.33 \\"]
table(out / "balanced_table.tex", r"System & PlotQA Bal. & $E_{FSM}$ & CLEVR Bal. & $E_{FSM}$ & GQA Bal. & $E_{FSM}$", rows, "lrrrrrr")
rows = []
for model in MODELS:
cells = []
for source in STATES:
c = domains[source]["models"][model]["counts"]
cells.extend([percentage(c["strict_answers_correct"], c["answerable_views"]),
percentage(c["joint_groups_correct"], 1000, 1)])
rows.append(NAMES[model] + " & " + " & ".join(cells) + r" \\")
table(out / "answer_table.tex", r"System & PlotQA $A$ & $J_5$ & CLEVR $A$ & $J_4$ & GQA $A$ & $J_3$", rows, "lrrrrrr")
rows = []
for model in MODELS:
cells = []
for stratum in ["location", "other"]:
c = domains["gqa"]["location_sensitivity"]["models"][model][stratum]
cells.extend([percentage(c["failures"], c["views"]), percentage(c["groups_correct"], c["groups"], 1),
percentage(c["missing_failures"], c["groups"])])
rows.append(NAMES[model] + " & " + " & ".join(cells) + r" \\")
table(out / "location_table.tex", r"System & Loc. Fail & $B_3$ & $M$ Fail & Other Fail & $B_3$ & $M$ Fail", rows, "lrrrrrr")
rows = []
for source in STATES:
for model in MODELS:
d = domains[source]["models"][model]
c = d["counts"]
lo, hi = d["intervals_95"]["failure"]
rows.append(source.upper() + " / " + NAMES[model] + " & " + str(c["valid_decision_errors"]) + "/" + str(c["valid"]) +
" & " + str(c["invalid"]) + " & " + pct(lo) + "--" + pct(hi) + r" \\")
table(out / "denominator_table.tex", r"Domain / system & $W/V$ & Invalid & Failure 95\% interval", rows, "lrrr")
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 12, "pdf.fonttype": 42})
fig, axes = plt.subplots(1, 3, figsize=(8.3, 3.7), gridspec_kw={"width_ratios": [5, 4, 3]})
for ax, (source, states) in zip(axes, STATES.items()):
values = np.array([[domains[source]["models"][m]["states"][s]["failures"] / 10 for s in states] for m in MODELS])
ax.imshow(values, cmap="YlOrRd", vmin=0, vmax=80, aspect="auto")
for i in range(len(MODELS)):
for j in range(len(states)):
ax.text(j, i, f"{values[i, j]:.1f}", ha="center", va="center",
color="white" if values[i, j] > 48 else "#222222", fontsize=11)
ax.set_title({"plotqa": "A PlotQA", "clevr": "B CLEVR", "gqa": "C GQA"}[source], loc="left", fontsize=12)
ax.set_xticks(range(len(states)), [{"FULL": "F", "A_SAME": "S", "A_CHANGED": "C", "U_MISSING": "M", "U_INVALID": "I"}[s] for s in states])
ax.set_yticks(range(6), [NAMES[m] for m in MODELS] if source == "plotqa" else [])
ax.tick_params(length=0)
fig.tight_layout(w_pad=.6, rect=(0, .06, 1, 1))
fig.text(.60, .025, "Failure (%); 1,000 views per cell", ha="center", fontsize=12)
for ext in ["pdf", "png"]:
fig.savefig(out / ("state_failures." + ext), dpi=220, bbox_inches="tight")
plt.close(fig)
summary = {"status": "passed", "model_domain_cells": 18,
"rounded_percentages": "decimal half-up from integer counts; percentages are not truncated",
"tables": ["model_table.tex", "balanced_table.tex", "answer_table.tex", "denominator_table.tex", "location_table.tex"],
"figure": "state_failures.pdf", "sha_validation_performed": False}
(out / "asset-validation.json").write_text(json.dumps(summary, indent=2) + "\n")
print(json.dumps(summary))
if __name__ == "__main__":
main()