File size: 13,718 Bytes
510314e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | """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))
|