"""Bootstrap confidence intervals and paired significance tests. Reads the per-problem diagnosed traces in results/diagnosis/ and, for each (model, benchmark, quantization) cell, computes: - 95% bootstrap CIs for accuracy, average FFS, and ECR (5000 resamples). - A full SSR curve CI band (per-depth bootstrap). - For (base, restored) pairs: a paired bootstrap significance test on ΔAccuracy (uses the SAME sampled problem ids for base and restored in each resample, so the null cancels properly). Emits one *_ci.json next to each existing *_metrics.json, plus one pair-level *_sig.json per (model, benchmark, method) restoration comparison. These are real, defensible uncertainty estimates given a SINGLE inference run: they capture variance across problems, not variance across seeds. For a Q1 paper you want both — this script delivers the first half for free; the seed-variance half requires re-running inference with NUM_RUNS>=3. """ from __future__ import annotations import argparse import glob import json import os import re from typing import Dict, List, Optional, Tuple import numpy as np BENCHMARKS = ("gsm8k", "math500", "gpqa") QUANT_METHODS = ("awq_w4", "gptq_w4", "bnb_nf4_w4") # --------------------------------------------------------------------------- # Per-problem metric extraction # --------------------------------------------------------------------------- def first_failure_step(steps: List[dict]) -> Optional[int]: for s in steps: if s.get("is_correct") is False: return s.get("index") return None def cascade_rate(steps: List[dict]) -> Optional[float]: """Fraction of steps AFTER the first failure that are also incorrect. Returns None for problems with no failure (so the aggregate only averages over problems that actually failed — matches aggregate_metrics.ecr).""" ffs = first_failure_step(steps) if ffs is None: return None tail = [s for s in steps if s.get("index", 0) > ffs] if not tail: return None return sum(1 for s in tail if s.get("is_correct") is False) / len(tail) def survival_at_depth(steps: List[dict], depth: int) -> Optional[bool]: """True if all of steps[0..depth] are correct, None if the trace is shorter.""" if len(steps) <= depth: return None return all(s.get("is_correct", True) for s in steps[: depth + 1]) def load_per_problem(jsonl_path: str) -> List[dict]: """Return a list of per-problem records with the fields bootstrapping needs.""" out = [] with open(jsonl_path) as f: for line in f: t = json.loads(line) steps = t.get("steps", []) or [] out.append({ "problem_id": t.get("problem_id"), "is_correct": bool(t.get("is_correct_final", False)), "ffs": first_failure_step(steps), "ecr": cascade_rate(steps), "step_correct": [s.get("is_correct", True) for s in steps], }) return out # --------------------------------------------------------------------------- # Bootstrap utilities # --------------------------------------------------------------------------- def _ci(samples: np.ndarray, alpha: float = 0.05) -> Tuple[float, float]: lo, hi = np.percentile(samples, [100 * alpha / 2, 100 * (1 - alpha / 2)]) return float(lo), float(hi) def bootstrap_single(records: List[dict], n_boot: int = 5000, rng: Optional[np.random.Generator] = None) -> dict: """Bootstrap accuracy, avg_ffs, ecr, and the SSR curve for one cell.""" rng = rng or np.random.default_rng(0) n = len(records) if n == 0: return {} acc_vec = np.array([r["is_correct"] for r in records], dtype=float) ffs_vec = np.array([r["ffs"] if r["ffs"] is not None else np.nan for r in records], dtype=float) ecr_vec = np.array([r["ecr"] if r["ecr"] is not None else np.nan for r in records], dtype=float) # SSR per depth: for problems with enough steps, is the trace "alive" at depth d? max_depth = 30 alive = np.full((n, max_depth), np.nan) for i, r in enumerate(records): steps = r["step_correct"] for d in range(max_depth): if d < len(steps): alive[i, d] = float(all(steps[: d + 1])) acc_samples = np.empty(n_boot) ffs_samples = np.empty(n_boot) ecr_samples = np.empty(n_boot) ssr_samples = np.full((n_boot, max_depth), np.nan) for b in range(n_boot): idx = rng.integers(0, n, size=n) acc_samples[b] = acc_vec[idx].mean() f = ffs_vec[idx] ffs_samples[b] = np.nanmean(f) if np.any(~np.isnan(f)) else np.nan e = ecr_vec[idx] ecr_samples[b] = np.nanmean(e) if np.any(~np.isnan(e)) else np.nan for d in range(max_depth): col = alive[idx, d] valid = ~np.isnan(col) if valid.any(): ssr_samples[b, d] = col[valid].mean() def summarize(x): x = x[~np.isnan(x)] if x.size == 0: return None lo, hi = _ci(x) return {"mean": float(x.mean()), "ci_lo": lo, "ci_hi": hi} ssr_ci_lo = np.nanpercentile(ssr_samples, 2.5, axis=0) ssr_ci_hi = np.nanpercentile(ssr_samples, 97.5, axis=0) ssr_mean = np.nanmean(ssr_samples, axis=0) return { "n": int(n), "accuracy": summarize(acc_samples), "avg_ffs": summarize(ffs_samples), "ecr": summarize(ecr_samples), "ssr_curve_ci": { "mean": [None if np.isnan(v) else float(v) for v in ssr_mean], "ci_lo": [None if np.isnan(v) else float(v) for v in ssr_ci_lo], "ci_hi": [None if np.isnan(v) else float(v) for v in ssr_ci_hi], }, } def paired_bootstrap_sig(base: List[dict], rest: List[dict], n_boot: int = 5000, rng: Optional[np.random.Generator] = None) -> dict: """Paired bootstrap on ΔAccuracy between base and restored. Problems are paired by problem_id. For each bootstrap resample we draw the SAME indices in both conditions, compute the delta, and accumulate. The two-sided p-value is 2 * min(P(Δ<=0), P(Δ>=0)). """ rng = rng or np.random.default_rng(0) base_by_id = {r["problem_id"]: r for r in base} rest_by_id = {r["problem_id"]: r for r in rest} shared = sorted(set(base_by_id) & set(rest_by_id)) if not shared: return {"n_pairs": 0} b_vec = np.array([base_by_id[pid]["is_correct"] for pid in shared], dtype=float) r_vec = np.array([rest_by_id[pid]["is_correct"] for pid in shared], dtype=float) n = len(shared) deltas = np.empty(n_boot) for i in range(n_boot): idx = rng.integers(0, n, size=n) deltas[i] = r_vec[idx].mean() - b_vec[idx].mean() observed = float(r_vec.mean() - b_vec.mean()) p_two = 2 * min((deltas <= 0).mean(), (deltas >= 0).mean()) lo, hi = _ci(deltas) return { "n_pairs": int(n), "delta_acc_observed": observed, "delta_acc_ci_lo": lo, "delta_acc_ci_hi": hi, "p_value": float(p_two), } # --------------------------------------------------------------------------- # CLI glue # --------------------------------------------------------------------------- def _discover_cells(diagnosis_dir: str): """Yield (model, benchmark, quant, jsonl_path) tuples for everything on disk.""" for quant_dir in sorted(glob.glob(os.path.join(diagnosis_dir, "*"))): if not os.path.isdir(quant_dir): continue quant = os.path.basename(quant_dir) for model_dir in sorted(glob.glob(os.path.join(quant_dir, "*"))): if not os.path.isdir(model_dir): continue model = os.path.basename(model_dir) for jsonl in sorted(glob.glob(os.path.join(model_dir, "*_run0.jsonl"))): base = os.path.basename(jsonl) m = re.match(r"(.+)_run0\.jsonl$", base) if not m: continue bench = m.group(1) if bench not in BENCHMARKS: continue yield model, bench, quant, jsonl def main(): parser = argparse.ArgumentParser() parser.add_argument("--diagnosis", default="results/diagnosis", help="Root diagnosis dir (quant/model/_run0.jsonl)") parser.add_argument("--output", default="results/metrics", help="Where to drop *_ci.json and *_sig.json") parser.add_argument("--n-boot", type=int, default=5000) parser.add_argument("--seed", type=int, default=0) args = parser.parse_args() os.makedirs(args.output, exist_ok=True) rng = np.random.default_rng(args.seed) # --- Phase A: single-cell CIs ------------------------------------------ cells = list(_discover_cells(args.diagnosis)) print(f"Found {len(cells)} diagnosis cells to bootstrap") per_problem_cache: Dict[Tuple[str, str, str], List[dict]] = {} for model, bench, quant, jsonl in cells: records = load_per_problem(jsonl) per_problem_cache[(model, bench, quant)] = records ci = bootstrap_single(records, n_boot=args.n_boot, rng=rng) out_path = os.path.join(args.output, f"{model}_{quant}_{bench}_run0_ci.json") with open(out_path, "w") as f: json.dump(ci, f, indent=2) print(f" wrote {len(cells)} *_ci.json files") # --- Phase B: paired significance (base vs restored) -------------------- n_sig = 0 for (model, bench, quant), base_recs in per_problem_cache.items(): if quant.endswith("_restored"): continue rest_recs = per_problem_cache.get((model, bench, quant + "_restored")) if not rest_recs: continue sig = paired_bootstrap_sig(base_recs, rest_recs, n_boot=args.n_boot, rng=rng) out_path = os.path.join(args.output, f"{model}_{quant}_{bench}_run0_sig.json") with open(out_path, "w") as f: json.dump(sig, f, indent=2) n_sig += 1 print(f" wrote {n_sig} *_sig.json files (paired base vs restored)") if __name__ == "__main__": main()