carlostoxtli's picture
Upload MAUI-Bench v1.0.0
7c188b6 verified
Raw History Blame Contribute Delete
11.6 kB
"""Analysis for MAUI-Bench runs.
python src/analysis/analyze.py --run-id RUN [--results-dir results]
Reads results/<run_id>/records.jsonl and produces results/<run_id>/analysis/:
summary.csv per (model, topology, family) means with BCa-free
percentile bootstrap CIs for normalized regret
tci.csv TCI_seed (F3) and TCI_para (F2) per cell group
gds.csv degradation slopes (F7) per perturbation class
lpi.csv latency predictability (F6) and token cost
kappa.csv regret-adjusted token cost vs single (F8)
divergence.csv committee divergence (F4)
mixed_effects.txt regret ~ topology * log_params + family + (1|instance)
(fit only when params_b metadata is available)
All numbers the paper reports come from these files; make_paper_assets.py
renders them into LaTeX tables under paper/generated/.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import numpy as np
import pandas as pd
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from metrics import tci, lpi, kappa_cost # noqa: E402
def bootstrap_ci(x: np.ndarray, n_boot: int = 10000, ci: float = 0.95,
seed: int = 0) -> tuple[float, float]:
x = x[np.isfinite(x)]
if len(x) == 0:
return (float("nan"), float("nan"))
rng = np.random.default_rng(seed)
idx = rng.integers(0, len(x), size=(n_boot, len(x)))
means = x[idx].mean(axis=1)
lo, hi = np.percentile(means, [(1 - ci) / 2 * 100, (1 + ci) / 2 * 100])
return float(lo), float(hi)
def load_records(run_dir: str) -> pd.DataFrame:
rows = []
seen = set()
with open(os.path.join(run_dir, "records.jsonl")) as f:
for line in f:
try:
r = json.loads(line)
except Exception:
continue
if r.get("key") == "ERR":
continue
# concurrent or resumed runners can append the same cell twice;
# keep the first completion of each key
if r["key"] in seen:
continue
seen.add(r["key"])
rows.append(r)
df = pd.DataFrame(rows)
df["tokens"] = df["prompt_tokens"] + df["completion_tokens"]
return df
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--run-id", required=True)
ap.add_argument("--results-dir", default="results")
ap.add_argument("--n-boot", type=int, default=10000)
args = ap.parse_args()
run_dir = os.path.join(args.results_dir, args.run_id)
out_dir = os.path.join(run_dir, "analysis")
os.makedirs(out_dir, exist_ok=True)
df = load_records(run_dir)
print(f"[info] {len(df)} records loaded")
with open(os.path.join(run_dir, "manifest.json")) as f:
manifest = json.load(f)
params = {m["id"]: m.get("params_b") for m in manifest["models"]}
# records from models later dropped from the design are excluded
df = df[df["model"].isin(params)].reset_index(drop=True)
print(f"[info] {len(df)} records after restricting to manifest models")
# ---------------- F1 summary with bootstrap CIs (replication cells only)
# regret_mean includes penalty-scored unparseable outputs (the preregistered
# continuous metric); regret_parsed conditions on parse success so budget
# exhaustion effects are separable from decision quality
rep = df[df.condition.isin(["replication", "paraphrase"])]
rows = []
for (model, topo, fam), g in rep.groupby(["model", "topology", "family"]):
x = g["normalized_regret"].to_numpy(dtype=float)
lo, hi = bootstrap_ci(x, args.n_boot)
xp = g.loc[g["parsed_ok"], "normalized_regret"].to_numpy(dtype=float)
plo, phi = bootstrap_ci(xp, args.n_boot)
rows.append({"model": model, "topology": topo, "family": fam,
"n": len(x), "regret_mean": float(np.nanmean(x)),
"regret_lo": lo, "regret_hi": hi,
"regret_parsed": (float(np.nanmean(xp)) if len(xp)
else float("nan")),
"regret_parsed_lo": plo, "regret_parsed_hi": phi,
"parse_fail_rate": float(1 - g["parsed_ok"].mean()),
"mean_tokens": float(g["tokens"].mean()),
"mean_latency_s": float(g["wall_latency_s"].mean())})
pd.DataFrame(rows).to_csv(os.path.join(out_dir, "summary.csv"), index=False)
# ---------------- F2 / F3: TCI over replication and paraphrase groups
rows = []
for (model, topo, fam, idx), g in df.groupby(
["model", "topology", "family", "instance_idx"]):
seed_actions = g[g.condition == "replication"]["action"].tolist()
para_actions = (g[g.condition == "paraphrase"]["action"].tolist()
+ g[(g.condition == "replication") & (g.rep == 0)]
["action"].tolist())
rows.append({"model": model, "topology": topo, "family": fam,
"instance_idx": idx,
"tci_seed": tci(fam, seed_actions),
"tci_para": tci(fam, para_actions)})
pd.DataFrame(rows).to_csv(os.path.join(out_dir, "tci.csv"), index=False)
# ---------------- F7: degradation slopes per perturbation class
# computed on both scales; parse-conditional (gds_parsed) avoids the
# penalty constant and parse-rate shifts driving the slope
base = (rep.groupby(["model", "topology", "family", "instance_idx"])
["normalized_regret"].mean().rename("regret_intact"))
basep = (rep[rep.parsed_ok]
.groupby(["model", "topology", "family", "instance_idx"])
["normalized_regret"].mean().rename("regret_intact_p"))
rows = []
for cond in ["dropout", "corruption", "ctx_truncation"]:
sub = df[df.condition == cond]
if sub.empty:
continue
merged = sub.merge(base.reset_index(),
on=["model", "topology", "family", "instance_idx"])
merged["gds"] = merged["normalized_regret"] - merged["regret_intact"]
mp = sub[sub.parsed_ok].merge(
basep.reset_index(),
on=["model", "topology", "family", "instance_idx"])
mp["gds_p"] = mp["normalized_regret"] - mp["regret_intact_p"]
gp = mp.groupby(["model", "topology", "family"])["gds_p"].mean()
for (model, topo, fam), g in merged.groupby(["model", "topology", "family"]):
lo, hi = bootstrap_ci(g["gds"].to_numpy(dtype=float), args.n_boot)
rows.append({"condition": cond, "model": model, "topology": topo,
"family": fam, "gds_mean": float(g["gds"].mean()),
"gds_lo": lo, "gds_hi": hi,
"gds_parsed": float(gp.get((model, topo, fam),
np.nan)),
"n": len(g)})
pd.DataFrame(rows).to_csv(os.path.join(out_dir, "gds.csv"), index=False)
# ---------------- F6: latency predictability + F8 groundwork
rows = []
for (model, topo), g in df.groupby(["model", "topology"]):
lat = g["wall_latency_s"].to_numpy(dtype=float)
rows.append({"model": model, "topology": topo,
"lpi_p95_over_p50": lpi(list(lat)),
"latency_p50_s": float(np.percentile(lat, 50)),
"latency_p95_s": float(np.percentile(lat, 95)),
"mean_tokens": float(g["tokens"].mean())})
pd.DataFrame(rows).to_csv(os.path.join(out_dir, "lpi.csv"), index=False)
# ---------------- F8: kappa vs single baseline
piv_r = rep.groupby(["model", "topology"])["normalized_regret"].mean()
piv_t = rep.groupby(["model", "topology"])["tokens"].mean()
rows = []
for model in rep["model"].unique():
if (model, "single") not in piv_r.index:
continue
r1, t1 = piv_r[(model, "single")], piv_t[(model, "single")]
for topo in rep[rep.model == model]["topology"].unique():
if topo == "single":
continue
rows.append({"model": model, "topology": topo,
"kappa_tokens_per_regret":
kappa_cost(piv_t[(model, topo)],
piv_r[(model, topo)], t1, r1),
"delta_regret": float(r1 - piv_r[(model, topo)]),
"delta_tokens": float(piv_t[(model, topo)] - t1)})
pd.DataFrame(rows).to_csv(os.path.join(out_dir, "kappa.csv"), index=False)
# ---------------- F4: committee divergence
div = df[df["committee_divergence"].notna()]
if not div.empty:
rows = []
for (model, topo, fam), g in div.groupby(["model", "topology", "family"]):
x = g["committee_divergence"].to_numpy(dtype=float)
lo, hi = bootstrap_ci(x, args.n_boot)
rows.append({"model": model, "topology": topo, "family": fam,
"divergence_mean": float(np.nanmean(x)),
"divergence_lo": lo, "divergence_hi": hi, "n": len(x)})
pd.DataFrame(rows).to_csv(os.path.join(out_dir, "divergence.csv"),
index=False)
# ---------------- mixed effects (exploratory; needs params_b metadata)
# DV is parse-conditional normalized regret (penalty-inclusive values are
# dominated by an arbitrary penalty constant); groups are the 64 sampled
# instances (family x instance_idx); models lacking params_b metadata are
# excluded and listed in the output header. With 7 models, scale is
# confounded with family and reasoning tuning; treat as exploratory.
df["params_b"] = df["model"].map(params)
me_path = os.path.join(out_dir, "mixed_effects.txt")
sub = rep[rep["parsed_ok"]].copy()
sub["params_b"] = sub["model"].map(params)
excluded = sorted(set(rep["model"]) - set(
sub.dropna(subset=["params_b"])["model"]))
sub = sub.dropna(subset=["params_b"])
sub["group"] = sub["family"].astype(str) + "_" + \
sub["instance_idx"].astype(str)
if len(sub) > 100:
try:
import statsmodels.formula.api as smf
sub["log_params"] = np.log(sub["params_b"].astype(float))
model = smf.mixedlm(
"normalized_regret ~ C(topology) * log_params + C(family)",
sub, groups=sub["group"])
fit = model.fit(method="lbfgs", maxiter=200)
with open(me_path, "w") as f:
f.write("DV: parse-conditional normalized regret; groups: "
f"{sub['group'].nunique()} family x instance units; "
f"models excluded for missing params_b: {excluded}; "
"note: with 7 models, log_params is confounded with "
"family and reasoning tuning; exploratory only.\n\n")
f.write(str(fit.summary()))
print("[info] mixed-effects model written")
except Exception as e:
with open(me_path, "w") as f:
f.write(f"mixed-effects fit failed: {e}\n")
else:
with open(me_path, "w") as f:
f.write("insufficient params_b metadata; fill models.metadata in "
"config/experiment.yaml and re-run analysis\n")
print(f"[info] analysis written to {out_dir}")
if __name__ == "__main__":
main()