#!/usr/bin/env python3 """Collect the outputs of bench/gemma4_parity.sh into SUMMARY.json and SUMMARY.md, with a pass / fail line per gate. python -m bench.gemma4_parity_summary --out-dir /workspace/gemma4-parity/out The thresholds are PROPOSALS taken from the Jeffan-31b-1710 study (docs/models/jeffan-31b-1710.md: bf16 agreement 99.84 % on DI-1000, FP8 + FP8 KV 99.38 % DI / 97.64 % P300; batched vs batch-1 bf16 differs by up to 0.028); the reviewer sets the final ones. A missing input is reported as "not run", never as a pass. """ from __future__ import annotations import argparse import json from pathlib import Path GATES = { # per precision arm: minimum top-choice agreement with the HF reference, largest tolerated per-item |dp| "bf16": {"agreement": 0.990, "max_abs_dp": 0.05}, "fp8-kv": {"agreement": 0.970, "max_abs_dp": 0.15}, } BATCHING = {"agreement": 0.990} # engine concurrency 8 vs concurrency 1 (same arm) def _load(p): p = Path(p) return json.loads(p.read_text()) if p.is_file() else None def _golden(path): """decide_dump `compare` prints one JSON line: {n, identical, max_abs_diff, shape_mismatch, status_mismatch, ...}.""" p = Path(path) if not p.is_file(): return None for line in reversed(p.read_text().splitlines()): if line.startswith("{"): return json.loads(line) return None def _ok(d): return d is not None and d["n"] > 0 and d["identical"] == d["n"] and not d["shape_mismatch"] and not d["status_mismatch"] def build(out: Path) -> dict: s: dict = {"env": _load(out / "env.json"), "gates": {}, "arms": {}} rc = _load(out / "render-check.json") if rc: bad = {n: (r["id_mismatches_reference_vs_engine"], r["first_read_differs_from_jeffan"]) for n, r in rc["sets"].items() if r["id_mismatches_reference_vs_engine"] or r["first_read_differs_from_jeffan"]} s["render_check"] = {n: {k: r[k] for k in ("n_items", "n_rendered", "over_prompt_cap_refused", "prompt_tokens", "ids_digest_sha256")} for n, r in rc["sets"].items()} s["gates"]["G1 reference renderer == engine renderer == jeffan first read"] = "pass" if not bad else f"FAIL {bad}" else: s["gates"]["G1 reference renderer == engine renderer == jeffan first read"] = "not run" for arm_dir in sorted(out.glob("arm-*")): arm = arm_dir.name[4:] a = s["arms"][arm] = {"hf_vs_engine_c1": {}, "engine_c8_vs_c1": {}, "load_p300": None, "peak_mem_mib": None} verdict = [] for f in sorted(arm_dir.glob("agreement-*-hf-vs-engine-c1.json")): name, d = f.name.split("-")[1], json.loads(f.read_text()) p, g = d.get("paired", {}), d.get("gold") a["hf_vs_engine_c1"][name] = {"n": p.get("n"), "answered_ref": d["ref"]["answered"], "answered_engine": d["cand"]["answered"], "unsupported_ref": d["ref"]["unsupported"], "unsupported_engine": d["cand"]["unsupported"], "top_choice_agreement": p.get("top_choice_agreement"), "mean_abs_dp": p.get("mean_abs_dp"), "max_abs_dp": p.get("max_abs_dp"), "accuracy_delta_pp": g and g["accuracy_delta"], "gold_prob_delta_pp": g and g["gold_prob_delta"]} t = GATES.get(arm) if t and p.get("n"): verdict.append(p["top_choice_agreement"] >= t["agreement"] and p["max_abs_dp"] <= t["max_abs_dp"] and d["ref"]["answered"] == d["cand"]["answered"] and (not g or g["accuracy_delta"]["ci95"][0] <= 0 <= g["accuracy_delta"]["ci95"][1])) for f in sorted(arm_dir.glob("agreement-*-engine-c8-vs-c1.json")): name, d = f.name.split("-")[1], json.loads(f.read_text()) p = d.get("paired", {}) a["engine_c8_vs_c1"][name] = {k: p.get(k) for k in ("n", "top_choice_agreement", "mean_abs_dp", "max_abs_dp", "frac_max_dp_gt_0.005")} load = _load(arm_dir / "load-p300.json") a["load_p300"] = load and [{k: lv.get(k) for k in ("concurrency", "decisions_per_s", "single_q_p50_ms", "single_q_p95_ms", "http_codes")} for lv in load["levels"]] pm = out / f"peak-mem-arm-{arm}.txt" a["peak_mem_mib"] = int(pm.read_text().strip()) if pm.is_file() and pm.read_text().strip() else None s["gates"][f"G2 HF reference vs engine {arm} (concurrency 1 vs batch 1)"] = ( "not run" if not verdict else "pass" if all(verdict) else "FAIL") for arm, a in s["arms"].items(): # informational: how much concurrency moves the engine's own answers s["gates"][f"info: {arm} c8 vs c1 agreement"] = ", ".join(f"{n} {v['top_choice_agreement']}" for n, v in a["engine_c8_vs_c1"].items()) or "not run" g = _golden(out / "golden-run1-vs-run2.txt") s["golden_gemma4"] = g s["gates"]["G3 gemma4 fp8-kv-colo-bi golden run1 == run2"] = "not run" if g is None else "pass" if _ok(g) else "FAIL" g3 = _golden(out / "golden-run1-vs-run3.txt") if g3: s["gates"]["G3b golden run1 == run3 (after restart)"] = "pass" if _ok(g3) else "FAIL" nf, jg = _golden(out / "jeffan-base1-vs-base2.txt"), _golden(out / "jeffan-base-vs-branch.txt") s["jeffan_golden"] = {"noise_floor_base1_vs_base2": nf, "base_vs_branch": jg} s["gates"]["G4 jeffan-31b-1710 goldens byte-identical (pre-change vs this change)"] = "not run" if jg is None else "pass" if _ok(jg) else "FAIL" if jg is not None and nf is not None and not _ok(nf): s["gates"]["G4 note"] = "the base code differs from itself: the comparison is not conclusive" return s def _f(x): return f"{x:.5g}" if isinstance(x, float) else str(x) def markdown(s: dict) -> str: L = ["# gemma4-code-v1 parity run", "", "| gate | result |", "|---|---|", *[f"| {k} | {v} |" for k, v in s["gates"].items()], ""] if s.get("env"): L += ["Environment: " + json.dumps(s["env"]), ""] for arm, a in s["arms"].items(): L += [f"## arm {arm}", "", "| set | n | agreement | mean abs dp | max abs dp | accuracy delta pp [CI] |", "|---|---|---|---|---|---|"] for name, v in a["hf_vs_engine_c1"].items(): ad = v["accuracy_delta_pp"] L.append(f"| {name} | {v['n']} | {_f(v['top_choice_agreement'])} | {_f(v['mean_abs_dp'])} | {_f(v['max_abs_dp'])} | " + (f"{ad['delta_pp']:+.2f} [{ad['ci95'][0]:+.2f}, {ad['ci95'][1]:+.2f}]" if ad else "-") + " |") if a["load_p300"]: L += ["", "| concurrency | decisions/s | p50 ms | p95 ms |", "|---|---|---|---|", *[f"| {x['concurrency']} | {x['decisions_per_s']} | {x.get('single_q_p50_ms')} | {x.get('single_q_p95_ms')} |" for x in a["load_p300"]]] L += ["", f"peak GPU memory (whole device): {a['peak_mem_mib']} MiB", ""] return "\n".join(L) def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--out-dir", required=True) a = ap.parse_args(argv) out = Path(a.out_dir) s = build(out) (out / "SUMMARY.json").write_text(json.dumps(s, indent=1) + "\n") (out / "SUMMARY.md").write_text(markdown(s) + "\n") print(markdown(s)) return 1 if any(str(v).startswith("FAIL") for v in s["gates"].values()) else 0 if __name__ == "__main__": raise SystemExit(main())