#!/usr/bin/env python3 """Paired analysis of lm-eval sample files: base vs loop, per task. lm-eval writes one jsonl per task with `filtered_resps` (one loglikelihood per choice) and `target` (gold index). Correctness = argmax(choice scores) == target. Prints accuracy for both models and an exact McNemar (binomial) p-value. """ import glob, json, math, os, sys ROOT = os.environ.get("LM_EVAL_ROOT", "out-lm") def load(tag, task): files = sorted(glob.glob(os.path.join(ROOT, tag, "**", f"samples_{task}_*.jsonl"), recursive=True)) if not files: files = sorted(glob.glob(os.path.join(ROOT, tag, "**", f"*{task}*.jsonl"), recursive=True)) if not files: return None rows = [] for line in open(files[-1]): d = json.loads(line) v = d.get("acc_norm", d.get("acc")) if v is None: continue rows.append(int(v)) return rows def mcnemar(a, b): n01 = sum(1 for x, y in zip(a, b) if x and not y) n10 = sum(1 for x, y in zip(a, b) if not x and y) m = n01 + n10 p = min(1.0, 2 * sum(math.comb(m, i) for i in range(0, min(n01, n10) + 1)) / 2 ** m) if m else 1.0 return n01, n10, p TASKS = sys.argv[1:] or ["hellaswag", "piqa", "winogrande", "arc_easy", "arc_challenge", "boolq"] print(f"{'task':16s} {'n':>6s} {'base':>7s} {'loop':>7s} {'delta':>8s} {'disc':>9s} p") for t in TASKS: a, b = load("base", t), load("loop", t) if not a or not b: print(f"{t:16s} missing samples (base={bool(a)}, loop={bool(b)})") continue n = min(len(a), len(b)) a, b = a[:n], b[:n] ab, bb = sum(a) / n, sum(b) / n n01, n10, p = mcnemar(a, b) print(f"{t:16s} {n:6d} {ab*100:6.1f}% {bb*100:6.1f}% {(bb-ab)*100:+7.1f}pp {n01:4d}/{n10:<4d} {p:.4f}")