"""Offline re-analyzer for the Q4 transfer study (Section 5.5). Recomputes, from the shipped per-trial files with no endpoint and no HuggingFace download, the per-task per-model accuracy and five-bin ECE, the benchmark-to-downstream Spearman rank correlations (with exact permutation p-values), the pre-set gate split, and the gate-pass vs gate-fail downstream calibration ratios with and without the leanstral-2603 outlier; it checks the recomputed Spearman values and gate split against the shipped summary tcb_criterion.json. python3 analyze_criterion.py Inputs: tcb_criterion_trials.json (downstream SST-2 + battery trials) and tcb_v03_trials.json (the benchmark panel under the validated protocol). Stdlib only. """ import json, pathlib, itertools from collections import defaultdict HERE = pathlib.Path(__file__).resolve().parent CRIT = HERE / ".." / "data" / "tcb_criterion_trials.json" BENCH = HERE / ".." / "data" / "tcb_v03_trials.json" SUMMARY = HERE / ".." / "data" / "tcb_criterion.json" GATE_ACC, GATE_ECE = 0.90, 0.05 def ece5(items): bins = defaultdict(list) for cp, corr in items: bins[min(4, int(cp * 5))].append((cp, corr)) n = len(items) return sum(len(xs) / n * abs(sum(x[0] for x in xs) / len(xs) - sum(x[1] for x in xs) / len(xs)) for xs in bins.values()) def metrics(trials): # Score over ANSWERED trials only (an unparseable/unavailable item carries no answer or # confidence), matching the canonical convention behind tcb_criterion.json; imputed-confidence # answered trials count toward ECE at neutral 0.5. by = defaultdict(list) for t in trials: if t.get("answer") is None or t.get("correct") is None: continue cp = 0.5 if t.get("conf") is None else t["conf"] / 100.0 by[t["model"]].append((cp, t["correct"])) acc = {m: sum(c for _, c in xs) / len(xs) for m, xs in by.items()} ece = {m: ece5(xs) for m, xs in by.items()} return acc, ece def avg_ranks(vals): order = sorted(range(len(vals)), key=lambda i: vals[i]) r = [0.0] * len(vals) i = 0 while i < len(vals): j = i while j + 1 < len(vals) and vals[order[j + 1]] == vals[order[i]]: j += 1 for k in range(i, j + 1): r[order[k]] = sum(range(i, j + 1)) / (j - i + 1) i = j + 1 return r def pearson(x, y): n = len(x); mx = sum(x) / n; my = sum(y) / n sxy = sum((x[i] - mx) * (y[i] - my) for i in range(n)) sx = sum((x[i] - mx) ** 2 for i in range(n)) ** 0.5 sy = sum((y[i] - my) ** 2 for i in range(n)) ** 0.5 return sxy / (sx * sy) if sx * sy else 0.0 def spearman(xv, yv): return pearson(avg_ranks(xv), avg_ranks(yv)) def perm_p(xv, yv): obs = spearman(xv, yv); xr = avg_ranks(xv); cnt = tot = 0 for perm in itertools.permutations(range(len(yv))): r = pearson(xr, avg_ranks([yv[i] for i in perm])); tot += 1 if abs(r) >= abs(obs) - 1e-12: cnt += 1 return obs, cnt / tot def main(): crit = json.load(open(CRIT)) bench = json.load(open(BENCH)) summary = json.load(open(SUMMARY)) bacc, bece = metrics(bench) gate_pass = set(summary["gate"]["pass"]) mismatches = 0 for task in ("sst2", "battery"): tr = [t for t in crit if t["task"] == task] acc, ece = metrics(tr) ms = [m for m in bacc if m in acc] ra, pa = perm_p([bacc[m] for m in ms], [acc[m] for m in ms]) re, pe = perm_p([bece[m] for m in ms], [ece[m] for m in ms]) passm = [m for m in ms if m in gate_pass] failm = [m for m in ms if m not in gate_pass] fail_no = [m for m in failm if "leanstral" not in m] mean = lambda d, g: sum(d[m] for m in g) / len(g) pf, ff = mean(ece, passm), mean(ece, failm) ff2 = mean(ece, fail_no) print(f"--- {task}: n_models={len(ms)}") print(f" accuracy rank: rho={ra:.3f} permutation p={pa:.3f}") print(f" calib (ECE) rank: rho={re:.3f} permutation p={pe:.3f}") print(f" gate-pass ECE={pf:.3f} gate-fail ECE={ff:.3f} ratio={ff/pf:.1f}x" f" | without leanstral fail ECE={ff2:.3f} ratio={ff2/pf:.1f}x") ref = summary["per_task"][task] for label, got, want in [("spearman_acc", ra, ref["spearman_tcbacc_vs_acc"]), ("spearman_ece", re, ref["spearman_tcbece_vs_ece"])]: if abs(got - want) > 5e-3: print(f" MISMATCH {label}: recomputed {got:.3f} vs shipped {want:.3f}") mismatches += 1 print("CRITERION OK" if mismatches == 0 else f"{mismatches} MISMATCHES") if __name__ == "__main__": main()