StepProbe / scripts /make_multi_seed_figure.py
Akiyue's picture
Add files using upload-large-folder tool
3ccaf5a verified
Raw
History Blame Contribute Delete
8.83 kB
"""Render the multi-seed robustness figure (paper fig 9).
Shows per-seed accuracy dots (jittered), mean bar, across-seed std whisker,
and the within-cell bootstrap CI as a shaded band — so a reviewer can see
two sources of uncertainty in one frame.
If fewer than 2 seeds have completed, we drop the std whisker (it's
meaningless with n=1) and annotate the figure so the reader knows.
"""
import argparse
import glob
import json
import os
import re
import sys
from typing import List, Tuple
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
mpl.rcParams.update({
"font.family": "sans-serif",
"font.sans-serif": ["Inter", "Helvetica Neue", "Arial", "DejaVu Sans"],
"font.size": 9,
"axes.labelsize": 10,
"xtick.labelsize": 8.5,
"ytick.labelsize": 8.5,
"legend.fontsize": 8,
"legend.frameon": False,
"figure.dpi": 200,
"savefig.dpi": 400,
"savefig.bbox": "tight",
"pdf.fonttype": 42,
"ps.fonttype": 42,
"axes.linewidth": 0.7,
"axes.spines.top": False,
"axes.spines.right": False,
})
COLOR_BASE = "#B0B7C3"
COLOR_REST = "#2E7D32"
def _trace_correctness(trace: dict, golds: dict) -> float:
"""Return 1.0 if this trace's final answer matches gold, else 0.0.
Prefers the diagnoser's `is_correct_final` label when present;
otherwise falls back to math_verify on the raw inference output.
This lets the figure read from `inference/` for seeds where
`diagnosis/` hasn't been produced (e.g. multi-seed runs where only
a single FP16 reference exists)."""
if "is_correct_final" in trace:
return 1.0 if trace.get("is_correct_final") else 0.0
try:
from eval_accuracy import extract_pred, _equiv
except ImportError:
return 0.0
pred = extract_pred(trace)
gold = trace.get("gold_answer") or golds.get(trace.get("problem_id", ""), "")
return 1.0 if _equiv(pred, gold) else 0.0
def _find_per_seed_files(base_dir: str, benchmark: str) -> dict:
"""Return {seed: path} preferring inference/<f> over diagnosis/<f>.
Multi-seed runs typically have full inference for every seed but only
a single diagnosis run (since DTW-based step diagnosis needs a paired
FP16 reference and we run only one). Mixing the two correctness
judges across seeds produced bogus across-seed std (the diagnosis
pipeline's `is_correct_final` is more permissive than the figure's
fallback `_equiv` / math_verify path). Using inference for all seeds
keeps the same judge across the comparison."""
found: dict = {}
for sub in ("inference", "diagnosis"):
for fp in sorted(glob.glob(os.path.join(base_dir, sub, f"{benchmark}_run*.jsonl"))):
m = re.search(r"run(\d+)\.jsonl$", fp)
if not m:
continue
seed = int(m.group(1))
found.setdefault(seed, fp)
return found
def seed_accuracies(base_dir: str, benchmark: str, golds: dict) -> List[Tuple[int, float]]:
out = []
for seed, fp in sorted(_find_per_seed_files(base_dir, benchmark).items()):
n, c = 0, 0.0
with open(fp) as f:
for line in f:
t = json.loads(line)
n += 1
c += _trace_correctness(t, golds)
if n > 0:
out.append((seed, c / n))
return out
def bootstrap_ci(base_dir: str, benchmark: str, golds: dict, n_boot=5000):
v = []
for seed, fp in sorted(_find_per_seed_files(base_dir, benchmark).items()):
with open(fp) as f:
for line in f:
t = json.loads(line)
v.append(_trace_correctness(t, golds))
if not v:
return None
v = np.array(v)
rng = np.random.default_rng(0)
s = np.empty(n_boot)
for i in range(n_boot):
idx = rng.integers(0, len(v), size=len(v))
s[i] = v[idx].mean()
return float(v.mean()), float(np.percentile(s, 2.5)), float(np.percentile(s, 97.5))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--multiseed-root", required=True)
parser.add_argument("--model", required=True)
parser.add_argument("--quant", required=True)
parser.add_argument("--benchmark", required=True)
parser.add_argument("--metrics", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
try:
from eval_accuracy import _load_gold
golds = _load_gold(args.benchmark)
except Exception:
golds = {}
cells = {}
for cfg, color in [("base", COLOR_BASE), ("restored", COLOR_REST)]:
base_dir = os.path.join(args.multiseed_root, cfg)
seeds = seed_accuracies(base_dir, args.benchmark, golds)
ci = bootstrap_ci(base_dir, args.benchmark, golds)
if not seeds or ci is None:
continue
cells[cfg] = {"seeds": seeds, "ci": ci, "color": color}
if not cells:
print("No multi-seed diagnosis data found.")
return
n_seeds = max(len(v["seeds"]) for v in cells.values())
fig, ax = plt.subplots(figsize=(4.6, 3.2), constrained_layout=True)
xpos = {"base": 0, "restored": 1}
xticks, xlabels = [], []
for cfg, info in cells.items():
x = xpos[cfg]
xticks.append(x); xlabels.append(cfg.capitalize())
seeds = info["seeds"]
color = info["color"]
accs = np.array([s[1] for s in seeds]) * 100
mean = float(accs.mean())
std = float(accs.std(ddof=0)) if len(seeds) > 1 else 0.0
boot_mean, lo, hi = (v * 100 for v in info["ci"])
# Within-cell bootstrap CI as a shaded rectangle.
ax.fill_between([x - 0.28, x + 0.28], [lo, lo], [hi, hi],
color=color, alpha=0.22, linewidth=0, zorder=1)
# Mean bar (horizontal line across the cell width).
ax.plot([x - 0.28, x + 0.28], [mean, mean], color=color,
linewidth=2.6, solid_capstyle="butt", zorder=3)
# Across-seed std whisker — only if we have >=2 seeds.
if len(seeds) >= 2:
ax.plot([x, x], [mean - std, mean + std],
color=color, linewidth=1.6, alpha=0.85, zorder=3)
# Per-seed dots, lightly jittered in x.
rng = np.random.default_rng(0)
for j, (_seed, a) in enumerate(seeds):
jx = x + rng.uniform(-0.10, 0.10)
ax.scatter(jx, a * 100, s=36, color=color,
edgecolor="white", linewidth=1.0, zorder=4)
# Label above the bar.
if len(seeds) >= 2:
label = f"{mean:.1f} ±{std:.1f}"
else:
label = f"{mean:.1f}"
ax.annotate(label, xy=(x, mean), xytext=(0, 18),
textcoords="offset points", ha="center", va="bottom",
fontsize=10, color=color, fontweight="bold")
ax.set_xticks(xticks)
ax.set_xticklabels(xlabels)
ax.set_ylabel("Accuracy (%)")
ax.yaxis.grid(True, linewidth=0.4, color="#DDDDDD")
ax.set_axisbelow(True)
all_y = []
for info in cells.values():
all_y.extend([s[1] * 100 for s in info["seeds"]])
all_y.extend([info["ci"][1] * 100, info["ci"][2] * 100])
ax.set_ylim(min(all_y) - 4, max(all_y) + 7)
ax.set_xlim(-0.55, 1.55)
pretty_quant = {"awq_w4": "AWQ w4", "gptq_w4": "GPTQ w4", "bnb_nf4_w4": "BnB NF4"}.get(args.quant, args.quant)
ax.text(1.0, 1.02,
f"{args.model} · {pretty_quant} · {args.benchmark}",
transform=ax.transAxes, ha="right", va="bottom",
fontsize=8, color="#555")
# If only one seed ran, flag it so a reader doesn't misread ±0.0.
if n_seeds < 2:
fig.text(0.02, -0.03,
"Note: only 1 seed completed in this snapshot; resume "
"run_multi_seed.sh for full 3-seed variance.",
ha="left", va="top", fontsize=7, color="#C03A2B", style="italic")
# Legend explaining what the visual elements mean.
handles = [
plt.Line2D([0], [0], marker="o", color="gray", markersize=6,
linestyle="", label="per-seed"),
plt.Line2D([0], [0], color="gray", linewidth=2.4, label="mean"),
plt.Line2D([0], [0], color="gray", linewidth=1.6, alpha=0.6,
label="±1 std (across seeds)"),
plt.Rectangle((0, 0), 1, 1, color="gray", alpha=0.22,
label="95% CI (bootstrap over problems)"),
]
ax.legend(handles=handles, loc="lower right", handlelength=1.6,
handletextpad=0.5, borderpad=0.4, labelspacing=0.5)
os.makedirs(os.path.dirname(args.output), exist_ok=True)
fig.savefig(args.output)
plt.close(fig)
print(f" Paper fig 9 (multi-seed) saved: {args.output}")
if __name__ == "__main__":
main()