Download analysis/code/main_tables.py from mverde73/mnemonic-proxy-agentlongbench: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/datasets/mverde73/mnemonic-proxy-agentlongbench/resolve/main/analysis/code/main_tables.py
- Command line
-
hf download hf://datasets/mverde73/mnemonic-proxy-agentlongbench/analysis/code/main_tables.py
-
curl -L -o main_tables.py https://huggingface.co/datasets/mverde73/mnemonic-proxy-agentlongbench/resolve/main/analysis/code/main_tables.py
13.7 kB
| """Analisi preregistrata (MAIN-RUN-CONFIRM.md) della corsa di conferma. Uso: python3 analysis/main_tables.py > analysis/tables.md | |
| Scrive anche analysis/summary.json (usato da grafici e post).""" | |
| import json | |
| import statistics | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import load as LD | |
| import stats as S | |
| OUT = Path(__file__).resolve().parent | |
| rows = LD.load_results() | |
| by = {(r["L"], r["pol"], r["qid"]): r for r in rows} | |
| SUMMARY = {} | |
| def P(*a): | |
| print(*a) | |
| def qids(L, excl=()): | |
| return sorted({r["qid"] for r in rows if r["L"] == L and r["qid"] not in excl}) | |
| def sel(Ls, excl=()): | |
| return [(L, q) for L in Ls for q in qids(L, excl)] | |
| SETS = {"64k": ["64k"], "128k": ["128k"], "unite": ["64k", "128k"]} | |
| # ---- §0 controlli di integrità ----------------------------------------------------------------------------- | |
| P("## 0. Integrità\n") | |
| for L in LD.LENGTHS: | |
| for pol in LD.POLS: | |
| rs = [r for r in rows if r["L"] == L and r["pol"] == pol] | |
| st = defaultdict(int) | |
| for r in rs: | |
| st[r["status"]] += 1 | |
| P(f"- {L} {pol}: {len(rs)} result.json, status {dict(st)}, finestra {sorted({r['window'] for r in rs})}, " | |
| f"violazioni di margine {sum((r['margin_viol'] or 0) for r in rs)}") | |
| # coerenza con results.jsonl del banco | |
| mism = 0 | |
| for L in LD.LENGTHS: | |
| for l in open(LD.RUNS / (LD.PREFIX + L) / "results.jsonl"): | |
| x = json.loads(l) | |
| r = by[(L, x["policy"], x["qid"])] | |
| if (x["score_official"], x["fully_correct"]) != (r["off"], r["full"]): | |
| mism += 1 | |
| P(f"- differenze tra results.jsonl e result.json: {mism}\n") | |
| # ---- §1 tabelle ------------------------------------------------------------------------------------------ | |
| P("## 1. Risposte corrette per politica\n") | |
| for metric, name in (("off", "ufficiale grezza (principale)"), ("norm", "normalizzata"), ("full", "interamente corretta")): | |
| P(f"### {name}\n") | |
| P("| insieme | n | " + " | ".join(LD.POLS) + " |") | |
| P("|---|---|" + "---|" * len(LD.POLS)) | |
| for sname, Ls in SETS.items(): | |
| for qt in (None, "CF", "FD"): | |
| ks = [(L, q) for (L, q) in sel(Ls) if qt is None or by[(L, "A", q)]["qt"] == qt] | |
| cells = [] | |
| for pol in LD.POLS: | |
| s = sum(by[(L, pol, q)][metric] for L, q in ks) | |
| cells.append(f"{s:g} ({100 * s / len(ks):.0f}%)") | |
| if qt is None: | |
| SUMMARY.setdefault("correct", {}).setdefault(metric, {}).setdefault(sname, {})[pol] = [s, len(ks)] | |
| else: | |
| SUMMARY.setdefault("correct_qt", {}).setdefault(metric, {}).setdefault(sname + "/" + qt, {})[pol] = [s, len(ks)] | |
| lab = sname + ("" if qt is None else " " + {"CF": "Count Frequency", "FD": "Find Duplicates"}[qt]) | |
| P(f"| {lab} | {len(ks)} | " + " | ".join(cells) + " |") | |
| P("") | |
| P("### Esiti anomali (vuote / troncate / chiamate residue / formato non valido / errori)\n") | |
| P("| lunghezza | politica | vuote | troncate | residue | formato non valido | errori | qid troncate/vuote |") | |
| P("|---|---|---|---|---|---|---|---|") | |
| for L in LD.LENGTHS: | |
| for pol in LD.POLS: | |
| rs = [r for r in rows if r["L"] == L and r["pol"] == pol] | |
| bad = [r["qid"] for r in rs if r["trunc"] or r["empty"]] | |
| P(f"| {L} | {pol} | {sum(r['empty'] for r in rs)} | {sum(r['trunc'] for r in rs)} | " | |
| f"{sum(r['resid'] for r in rs)} | {sum(r['invalid'] for r in rs)} | {sum(r['error'] for r in rs)} | " | |
| f"{', '.join(bad) or '—'} |") | |
| P("") | |
| # ---- §2–§4 confronti appaiati -------------------------------------------------------------------------------- | |
| def compare(p1, p2, ks, metric="off"): | |
| x = [int(by[(L, p1, q)][metric] >= 1) for L, q in ks] | |
| y = [int(by[(L, p2, q)][metric] >= 1) for L, q in ks] | |
| a, b, c, d = S.paired_counts(x, y) | |
| p = S.binom_two_sided(b, c) | |
| nc = S.newcombe10(a, b, c, d) | |
| tg = S.tango(a, b, c, d) | |
| # bootstrap a grappoli per storia condivisa | |
| cl = defaultdict(list) | |
| for (L, q), xi, yi in zip(ks, x, y): | |
| cl[(L, int(q.split("_")[0]))].append((xi, yi)) | |
| bs = S.cluster_bootstrap(cl, B=10000) | |
| b05, b95, b025, b975 = (S.pct(bs, t) for t in (0.05, 0.95, 0.025, 0.975)) | |
| return {"n": len(ks), "x": sum(x), "y": sum(y), "a": a, "b": b, "c": c, "d": d, "p_mcnemar": p, | |
| "diff": nc[0], "nc90": nc[1:], "tango90": tg[1:], "boot90": (b05, b95), "boot95": (b025, b975), | |
| "clusters": len(cl), | |
| "ni_nc": S.ni_verdict(nc[1]), "ni_tango": S.ni_verdict(tg[1]), "ni_boot": S.ni_verdict(b05), | |
| "sig_mcnemar": p < 0.05, "sig_boot": not (b025 <= 0 <= b975)} | |
| PAIRS = [("D", "B"), ("D", "T"), ("B", "T"), ("D", "A"), ("B", "A"), ("T", "A")] | |
| def comp_table(title, excl=(), drop_trunc=False, metric="off", key=None): | |
| P(f"### {title}\n") | |
| P("| confronto | insieme | n | corr. 1 | corr. 2 | solo 1 | solo 2 | McNemar p | diff | IC90 Newcombe | " | |
| "IC90 Tango | IC90 bootstrap (grappoli) | non inf. 5 pt (N / T / boot) |") | |
| P("|---|---|---|---|---|---|---|---|---|---|---|---|---|") | |
| res = {} | |
| for p1, p2 in PAIRS: | |
| for sname, Ls in SETS.items(): | |
| ks = sel(Ls, excl) | |
| if drop_trunc: | |
| ks = [(L, q) for L, q in ks if not any(by[(L, pp, q)]["trunc"] for pp in (p1, p2))] | |
| c = compare(p1, p2, ks, metric) | |
| res[f"{p1}-{p2}/{sname}"] = c | |
| f = lambda t: f"[{100 * t[0]:+.1f}, {100 * t[1]:+.1f}]" | |
| P(f"| {p1} vs {p2} | {sname} | {c['n']} | {c['x']} | {c['y']} | {c['b']} | {c['c']} | " | |
| f"{c['p_mcnemar']:.3f} | {100 * c['diff']:+.1f} | {f(c['nc90'])} | {f(c['tango90'])} | " | |
| f"{f(c['boot90'])} ({c['clusters']} storie) | {c['ni_nc']} / {c['ni_tango']} / {c['ni_boot']} |") | |
| P("") | |
| if key: | |
| SUMMARY.setdefault("compare", {})[key] = res | |
| return res | |
| P("## 2–3. Confronti appaiati (ufficiale grezza; 1 = interamente giusta secondo lo scorer ufficiale)\n") | |
| P("Principale: D contro B, McNemar esatto a due code. Secondari: differenza appaiata con IC 90% (Newcombe metodo 10 e " | |
| "Tango), non inferiorità a 5 punti dimostrata se il limite inferiore > −5 punti. Bootstrap: 10.000 ricampionamenti " | |
| "delle storie (cluster = lunghezza × sample_id), percentili.\n") | |
| main = comp_table("Tutte le domande", key="main") | |
| P("## 4. Sensibilità\n") | |
| s1 = comp_table(f"Senza {LD.DEV_QID} (usata nello sviluppo)", excl=(LD.DEV_QID,), key="no_dev") | |
| s2 = comp_table("Senza le risposte troncate (coppia tolta se una delle due è troncata)", drop_trunc=True, key="no_trunc") | |
| s3 = comp_table("Misura normalizzata", metric="norm", key="norm") | |
| s4 = comp_table("Misura interamente corretta", metric="full", key="full") | |
| P("### Verdetti che cambiano\n") | |
| changes = [] | |
| for name, rs in (("senza 0031", s1), ("senza troncate", s2), ("normalizzata", s3), ("interamente corretta", s4)): | |
| for k, c in rs.items(): | |
| m = main[k] | |
| for f, lab in (("sig_mcnemar", "significatività McNemar"), ("ni_nc", "non inferiorità Newcombe"), | |
| ("ni_tango", "non inferiorità Tango")): | |
| if c[f] != m[f]: | |
| changes.append(f"- {name}, {k}: {lab} {m[f]} → {c[f]}") | |
| for k, m in main.items(): | |
| if m["ni_boot"] != m["ni_nc"]: | |
| changes.append(f"- bootstrap, {k}: non inferiorità Newcombe {m['ni_nc']}, bootstrap {m['ni_boot']}") | |
| if m["sig_boot"] != m["sig_mcnemar"]: | |
| changes.append(f"- bootstrap, {k}: significatività McNemar {m['sig_mcnemar']}, IC95 bootstrap esclude 0: {m['sig_boot']}") | |
| if m["ni_tango"] != m["ni_nc"]: | |
| changes.append(f"- Tango contro Newcombe, {k}: {m['ni_nc']} / {m['ni_tango']}") | |
| P("\n".join(changes) if changes else "- nessuno") | |
| P("") | |
| SUMMARY["verdict_changes"] = changes | |
| # ---- §5 costi --------------------------------------------------------------------------------------------- | |
| P("## 5. Costi (dal contatore engine_calls.jsonl e da resources.jsonl)\n") | |
| P("Tempo per domanda = wall_s del result.json (dall'inizio della politica alla risposta; per D comprende il rigioco " | |
| "della storia attraverso il proxy). Prompt nuovi = prompt_tokens − cached_tokens (vedi new_prompt: correzione " | |
| "per le risposte in streaming che toccano il budget di ragionamento); generati = completion_tokens. TTFT = ttft_s della chiamata che produce la risposta.\n") | |
| def new_prompt(c): | |
| """Token di prompt calcolati davvero. Nelle risposte in streaming che toccano il budget di ragionamento Strata | |
| riporta usage/timings della continuazione interna (prompt quasi tutto in cache, prompt_n ~5) mentre il TTFT mostra | |
| il prefill completo: per queste chiamate, se TTFT > 3 s, si conta l'intero prompt come nuovo.""" | |
| p, ca = c.get("prompt_tokens") or 0, c.get("cached_tokens") or 0 | |
| if c.get("stream") and (c.get("completion_tokens") or 0) >= 3072 and (c.get("ttft_s") or 0) > 3: | |
| return p | |
| return max(0, p - ca) | |
| def q_start(ec): | |
| """Inizio della fase alla domanda per D: prima chiamata round/final.""" | |
| ts = [c["t_start"] for c in ec if c["kind"] in ("round", "final", "answer")] | |
| return min(ts) if ts else float("inf") | |
| P("Fase alla domanda: per D le chiamate round/final (il rigioco della storia e le note fatte durante il rigioco sono " | |
| "preparazione: in un agente vero sono distribuite lungo la conversazione); per B le compattazioni sono " | |
| "preparazione e la risposta è la fase alla domanda; per A e T tutto è fase alla domanda. Tempi del motore " | |
| "(somma wall delle chiamate).\n") | |
| P("| lunghezza | politica | W | tempo mediano (s) | preparazione mediana (s) | fase alla domanda mediana (s) | tempo totale (h) | chiamate/dom. (mediana) | prompt nuovi/dom. " | |
| "(mediana, k) | generati/dom. (mediana) | TTFT risposta mediano (s) | prompt max | VRAM picco (MiB) | " | |
| "RSS Strata picco (GiB) | RAM disp. minima (GiB) |") | |
| P("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|") | |
| COST = {} | |
| kinds_tot = defaultdict(lambda: defaultdict(float)) | |
| for L in LD.LENGTHS: | |
| for pol in LD.POLS: | |
| rs = [r for r in rows if r["L"] == L and r["pol"] == pol] | |
| walls, ncalls, pn, gen, ttft, pmax, vram, rss, avail = [], [], [], [], [], [], [], [], [] | |
| qphase, prep = [], [] | |
| for r in rs: | |
| ec = LD.load_engine_calls(r["dir"]) | |
| walls.append(r["wall_s"]) | |
| ncalls.append(len(ec)) | |
| pn.append(sum(new_prompt(c) for c in ec)) | |
| # fase "alla domanda": chiamate dopo l'ultima di preparazione (replay per D, compact per B) | |
| prep_kinds = {"replay", "compact"} | |
| prep.append(sum(c["wall_s"] or 0 for c in ec if c["kind"] in prep_kinds or | |
| (c["kind"] == "notes" and pol == "D" and c["t_start"] < q_start(ec)))) | |
| qphase.append(sum(c["wall_s"] or 0 for c in ec if c["kind"] not in prep_kinds and | |
| not (c["kind"] == "notes" and c["t_start"] < q_start(ec)))) | |
| gen.append(sum(c.get("completion_tokens") or 0 for c in ec)) | |
| pmax.append(max((c.get("prompt_tokens") or 0) for c in ec)) | |
| fin = [c for c in ec if c["kind"] in ("final", "answer")] or [ec[-1]] | |
| # per D la risposta è l'ultima chiamata di tipo final/round | |
| if pol == "D": | |
| fin = [c for c in ec if c["kind"] in ("final", "round")] | |
| ttft.append(fin[-1].get("ttft_s") or 0) | |
| for c in ec: | |
| k = kinds_tot[(L, pol, c["kind"])] | |
| k["n"] += 1 | |
| k["prompt_new"] += new_prompt(c) | |
| k["prompt"] += c.get("prompt_tokens") or 0 | |
| k["gen"] += c.get("completion_tokens") or 0 | |
| k["wall"] += c.get("wall_s") or 0 | |
| res = LD.load_resources(r["dir"]) | |
| vram.append(max((x.get("vram_mib") or 0) for x in res) if res else 0) | |
| rss.append(max((x.get("strata_rss_mib") or 0) for x in res) if res else 0) | |
| avail.append(min((x.get("mem_avail_mib") or 1e9) for x in res) if res else 0) | |
| med = statistics.median | |
| COST[f"{L}/{pol}"] = {"wall_med": med(walls), "wall_tot_h": sum(walls) / 3600, "calls_med": med(ncalls), | |
| "prompt_new_med": med(pn), "gen_med": med(gen), "ttft_med": med(ttft), | |
| "prompt_max": max(pmax), "vram_peak": max(vram), "rss_peak": max(rss), | |
| "avail_min": min(avail), "walls": walls, "prep_med": med(prep), "q_med": med(qphase), "qphase": qphase, "window": rs[0]["window"], | |
| "prompt_new_tot": sum(pn), "gen_tot": sum(gen)} | |
| P(f"| {L} | {pol} | {rs[0]['window']} | {med(walls):.0f} | {med(prep):.0f} | {med(qphase):.0f} | {sum(walls) / 3600:.2f} | {med(ncalls):.0f} | " | |
| f"{med(pn) / 1000:.1f} | {med(gen):.0f} | {med(ttft):.1f} | {max(pmax)} | {max(vram):.0f} | " | |
| f"{max(rss) / 1024:.1f} | {min(avail) / 1024:.1f} |") | |
| P("") | |
| P("### Per tipo di chiamata (totali sulle 50 domande)\n") | |
| P("| lunghezza | politica | tipo | chiamate | prompt totali (k) | prompt nuovi (k) | generati (k) | tempo motore (min) |") | |
| P("|---|---|---|---|---|---|---|---|") | |
| for (L, pol, k), v in sorted(kinds_tot.items()): | |
| P(f"| {L} | {pol} | {k} | {v['n']:.0f} | {v['prompt'] / 1000:.0f} | {v['prompt_new'] / 1000:.0f} | " | |
| f"{v['gen'] / 1000:.1f} | {v['wall'] / 60:.1f} |") | |
| P("") | |
| SUMMARY["cost"] = COST | |
| SUMMARY["cost_kinds"] = {"/".join(k): dict(v) for k, v in kinds_tot.items()} | |
| SUMMARY["rows"] = [{k: r[k] for k in ("L", "pol", "qid", "qt", "off", "norm", "full", "trunc", "empty", "wall_s")} | |
| for r in rows] | |
| (OUT / "summary.json").write_text(json.dumps(SUMMARY, indent=1, default=list)) | |