"""Cross-cell results aggregator for the trainable-KV length ablation. Run AFTER the 10 cells (5 lengths × 2 datasets) finish. Walks every data/eval/kvlen//p

/preds.jsonl, recomputes metrics from the per-record source of truth (so it's robust to a cell that was interrupted mid-judge), and renders side-by-side comparison tables that no single per-cell stats.json gives: 1. Per-dataset summary: rows = KV length p, cols = n / coverage / judge_acc / judge_correct_rate / em / f1 2. Per-dataset judge_acc broken out BY query_type × KV length (which question types benefit from a longer cartridge?) Pure stdlib — NO torch / NO cartridges import — so it runs on any machine (including CPU-only), unlike eval_direct_ask.py. Usage: python scripts/train/analyze_kvlen.py # both datasets, default lengths python scripts/train/analyze_kvlen.py --datasets lmes # one dataset python scripts/train/analyze_kvlen.py --csv data/eval/kvlen/summary.csv """ import argparse import json import os import sys from collections import defaultdict PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEFAULT_DATASETS = ["lmes", "metamem5k"] DEFAULT_LENGTHS = [64, 128, 256, 512, 1024] DS_DIR = {"lmes": "longmemeval_s", "metamem5k": "metamem_5k"} def _r(p): return p if os.path.isabs(p) else os.path.join(PROJECT_ROOT, p) # ---- metric helpers (verdict->numeric mapping kept identical to ---- # ---- eval_direct_ask.aggregate_direct / eval_metrics._judge_num) ---- def _judge_num(v): if isinstance(v, str): return {"correct": 1.0, "partial": 0.5, "wrong": 0.0}.get(v) if isinstance(v, bool): return 1.0 if v else 0.0 return None def _mean(xs): xs = [x for x in xs if x is not None] return sum(xs) / len(xs) if xs else None def _read_jsonl(path): recs = [] with open(path) as f: for line in f: line = line.strip() if line: try: recs.append(json.loads(line)) except Exception: pass return recs def analyze_cell(eval_root, ds, p, n_sampled=None): """Recompute one cell's metrics from preds.jsonl. Returns None if not run yet.""" preds = os.path.join(_r(eval_root), ds, f"p{p}", "preds.jsonl") if not os.path.exists(preds): return None recs = _read_jsonl(preds) if not recs: return {"n": 0, "exists": True} jc = [1.0 if r.get("answer_judge") == "correct" else 0.0 for r in recs if r.get("answer_judge") is not None] users_answered = {r.get("user_id") for r in recs} cell = { "exists": True, "n": len(recs), "n_judged": len(jc), "n_users": len(users_answered), "coverage": (len(users_answered) / n_sampled) if n_sampled else None, "judge_acc": _mean([_judge_num(r.get("answer_judge")) for r in recs]), "judge_correct_rate": (sum(jc) / len(jc)) if jc else None, "em": _mean([r.get("answer_em") for r in recs]), "f1": _mean([r.get("answer_f1") for r in recs]), } by = defaultdict(list) for r in recs: by[r.get("query_type")].append(r) cell["by_qtype"] = { str(qt): _mean([_judge_num(r.get("answer_judge")) for r in rs]) for qt, rs in by.items() } cell["by_qtype_n"] = {str(qt): len(rs) for qt, rs in by.items()} return cell def _load_sample_count(ds, seed): """How many users were sampled (denominator for coverage). None if list missing.""" path = os.path.join( _r("data/processed"), DS_DIR[ds], "splits", f"kvlen_sample200_seed{seed}.json" ) if os.path.exists(path): try: return len(json.load(open(path))) except Exception: return None return None def _fmt(x, pct=False): if x is None: return " — " if pct: return f"{100*x:5.1f}" return f"{x:5.3f}" if isinstance(x, float) else str(x) def print_summary(ds, lengths, cells, n_sampled): print(f"\n{'='*78}") print(f" Dataset: {ds} (sampled users: {n_sampled if n_sampled else '?'})") print(f"{'='*78}") hdr = f"{'p (KV len)':>10} | {'n':>5} {'users':>6} {'cov%':>6} | " \ f"{'judge_acc':>9} {'correct%':>9} | {'EM':>6} {'F1':>6}" print(hdr) print("-" * len(hdr)) for p in lengths: c = cells.get(p) if c is None: print(f"{('p'+str(p)):>10} | {'(not run yet)':>30}") continue print( f"{('p'+str(p)):>10} | {c['n']:>5} {c.get('n_users','-'):>6} " f"{_fmt(c.get('coverage'), pct=True):>6} | " f"{_fmt(c.get('judge_acc')):>9} {_fmt(c.get('judge_correct_rate'), pct=True):>9} | " f"{_fmt(c.get('em')):>6} {_fmt(c.get('f1')):>6}" ) def print_by_qtype(ds, lengths, cells): """judge_acc broken out by query_type (rows) × KV length (cols).""" qtypes = sorted({qt for c in cells.values() if c for qt in c.get("by_qtype", {})}) if not qtypes: return print(f"\n [{ds}] judge_acc by query_type × KV length") cols = " ".join(f"{('p'+str(p)):>7}" for p in lengths) print(f" {'query_type':>26} | {cols}") print(f" {'-'*26}-+-{'-'*len(cols)}") for qt in qtypes: row = [] for p in lengths: c = cells.get(p) v = c.get("by_qtype", {}).get(qt) if c else None row.append(f"{_fmt(v):>7}") print(f" {qt:>26} | {' '.join(row)}") def main(): ap = argparse.ArgumentParser(description="Cross-cell KV-length ablation analyzer") ap.add_argument("--datasets", nargs="+", default=DEFAULT_DATASETS, choices=DEFAULT_DATASETS) ap.add_argument("--lengths", nargs="+", type=int, default=DEFAULT_LENGTHS) ap.add_argument("--seed", type=int, default=42) ap.add_argument("--eval-root", default="data/eval/kvlen") ap.add_argument("--csv", default=None, help="Optional: write a flat CSV for plotting") ap.add_argument("--no-qtype", action="store_true", help="Skip the by-query_type table") args = ap.parse_args() all_results = {} # ds -> {p -> cell} for ds in args.datasets: n_sampled = _load_sample_count(ds, args.seed) cells = {} for p in args.lengths: cells[p] = analyze_cell(args.eval_root, ds, p, n_sampled=n_sampled) all_results[ds] = (cells, n_sampled) print_summary(ds, args.lengths, cells, n_sampled) if not args.no_qtype: print_by_qtype(ds, args.lengths, cells) # ---- optional CSV (one row per cell; flat, plot-friendly) ---- if args.csv: csv_path = _r(args.csv) os.makedirs(os.path.dirname(csv_path), exist_ok=True) with open(csv_path, "w", encoding="utf-8") as f: f.write("dataset,kv_len,n,n_users,n_sampled,coverage,judge_acc," "judge_correct_rate,em,f1\n") for ds in args.datasets: cells, n_sampled = all_results[ds] for p in args.lengths: c = cells.get(p) if not c: continue f.write(",".join(str(x) for x in [ ds, p, c.get("n", 0), c.get("n_users", ""), n_sampled if n_sampled else "", c.get("coverage", ""), c.get("judge_acc", ""), c.get("judge_correct_rate", ""), c.get("em", ""), c.get("f1", ""), ]) + "\n") print(f"\nCSV written -> {csv_path}") # ---- machine-readable JSON dump alongside CSV semantics ---- missing = [(ds, p) for ds in args.datasets for p in args.lengths if all_results[ds][0].get(p) is None] if missing: print(f"\n[note] {len(missing)} cell(s) not run yet: " + ", ".join(f"{ds}/p{p}" for ds, p in missing)) if __name__ == "__main__": main()