"""Does our stack reproduce Laya's published numbers for Laya's own checkpoints? Every published figure is recomputed from ``runs/macjev/laya_baselines`` (our LayaScorer on MPS, or round-1 imports) with Laya's protocol: raw logits -> softmax with the checkpoint's *shipped* temperature exactly as laya 0.2.0 applied it (no [0.5, 5] clamp; the published runs predate the clamp), 15-bin top-probability ECE, macro-F1 over class indices, and so on (``bench_local.metrics`` / the T4 notebook's ``hard_metrics``). Sources of the published numbers: ``research/results/t4_colab_benchmark.json`` (T4 suites, flip rates, calibration repair), ``research/results/cpu_51_language_sweep.json`` (51-language MASSIVE, typed-decisions on three checkpoints) and ``BENCHMARKS.md`` (the application table; its ``app_benchmark.json`` is not shipped, so those values are transcribed below). Verdicts. Laya's checkpoints are deterministic and are re-scored on the *identical* rows, so there is no sampling noise: a binomial standard error is not a tolerance. For an accuracy-like rate over n rows, with ``h`` = half a unit of the published value's last printed decimal: * ``exact`` |ours - published| <= h (equal at the published precision); * ``reproduced`` <= 1/n + h (one row differs: a near-tie argmax flipping between devices); * ``within_noise`` <= 3/n + h (two or three rows; only acceptable for the T4 notebook, which ran on a Tesla T4, versus our MPS fp32 re-scoring); * ``gap`` anything larger. Every gap must match an entry of ``EXPLANATIONS``; the others are listed as UNEXPLAINED. ECE / macro-F1: ``reproduced`` <= 0.005, ``within_noise`` <= 0.02 (a few near-tie rows); NLL: relative 0.2%; other quantities: 0.005. (Before 2026-09-23 review, ``reproduced`` allowed max(0.005, 1/n) and ``within_noise`` 2 binomial SE, which hid a real protocol difference in apps.email_spam - see ``laya_compat.email_state``.) PYTHONPATH=src python -m macjev.eval.validate [--out runs/macjev/laya_baselines/validation] """ from __future__ import annotations import argparse import json import math from pathlib import Path from collections import Counter import numpy as np from . import laya_baselines as LB from .calibration import laya_refit from .laya_scorer import checkpoint_config, shipped_temperature_fn from .metrics import by_key, flip_rate, summarize from .suites import published_cpu_sweep, published_t4 T4_NAME = {"english": "laya", "multilingual": "laya-multilingual"} CPU_NAME = {"english": "english", "multilingual": "multilingual", "typed": "typed-decisions"} # BENCHMARKS.md "Themes" and "On the public datasets where Jev numbers exist" (accuracy, N=400). APPS_PUBLISHED = { "apps.email_spam": {"english": 0.993, "multilingual": 0.993, "typed": 0.958}, "apps.phishing": {"english": 0.980, "multilingual": 0.993, "typed": 0.940}, "apps.guardrails_jailbreak": {"english": 0.708, "multilingual": 0.755, "typed": 0.762}, "apps.moderation_toxicity": {"english": 0.530, "multilingual": 0.525, "typed": 0.530}, "apps.rag_relevance": {"english": 0.625, "multilingual": 0.657, "typed": 0.625}, "apps.support_triage": {"english": 0.502, "multilingual": 0.522, "typed": 0.505}, "apps.model_routing_domain": {"english": 0.639, "multilingual": 0.123, "typed": 0.659}, "apps.jev.ag_news": {"english": 0.950, "multilingual": 0.930, "typed": 0.953}, "apps.jev.emotion": {"english": 0.595, "multilingual": 0.530, "typed": 0.600}, "apps.jev.banking77_full": {"english": 0.425, "multilingual": 0.425, "typed": 0.492}, } APPS_PUBLISHED_EXTRA = {("apps.moderation_toxicity", "english", "macro_f1"): 0.400} # BENCHMARKS.md typed-decisions table ("Brier" there is brier_vs_soft, see cpu sweep part_b). TYPED_PUBLISHED = {"typed": {"accuracy": 0.766, "soft_accuracy": 0.471, "brier_vs_soft": 0.061, "ece": 0.213, "score_mae": 0.242}, "english": {"accuracy": 0.361, "soft_accuracy": 0.332, "brier_vs_soft": 0.316, "ece": 0.175, "score_mae": 0.694}, "multilingual": {"accuracy": 0.342, "soft_accuracy": 0.326, "brier_vs_soft": 0.439, "ece": 0.285, "score_mae": 0.687}} TYPED_WORKFLOW_PUBLISHED = {"agent_trace_observability": 0.730, "customer_service": 0.764, "invoice_processing": 0.804, "security_incidents": 0.766} BENCH_MD_HEADLINE = {"refit_ece_49": {"english": 0.081, "multilingual": 0.106}, "shipped_ece_49": {"english": 0.466, "multilingual": 0.314}} MD_DECIMALS = 3 # BENCHMARKS.md prints 3 decimals ("0.930"); the JSON results keep 4 (or full floats) def verdict(ours: float, pub: float, n: int | None, kind: str = "rate", decimals: int = 4) -> str: """``decimals``: precision the published value was printed with (4 for the JSON results, ``MD_DECIMALS`` for BENCHMARKS.md). Inferring it from the float would read "0.930" as 0.93.""" if ours is None or pub is None or (isinstance(ours, float) and math.isnan(ours)): return "missing" d = abs(float(ours) - float(pub)) h = 0.5 * 10 ** (-decimals) eps = 1e-9 if kind == "rate" and n: if d <= h + eps: return "exact" if d <= 1.0 / n + h + eps: return "reproduced" if d <= 3.0 / n + h + eps: return "within_noise" return "gap" if kind == "nll": # NLL of sharpened (T=0.1) 20-way rows is ~10-20 nats; relative return "exact" if d <= h + eps else "reproduced" if d <= max(0.005, 0.002 * abs(pub)) else "gap" if d <= h + eps: return "exact" if d <= 0.005 + eps: return "reproduced" if kind in ("ece", "f1") and d <= 0.02: # a few near-tie rows flip between T4 GPU and MPS fp32 return "within_noise" return "gap" def _cmp(ours, pub, n=None, kind="rate", decimals: int = 4) -> dict: return {"ours": None if ours is None else round(float(ours), 4), "published": pub, "diff": None if ours is None or pub is None else round(float(ours) - float(pub), 4), "n": n, "verdict": verdict(ours, pub, n, kind, decimals)} def laya_metrics(rows: list[dict], which: str) -> dict: return summarize(rows, shipped_temperature_fn(which)) def _load(which: str, suite: str) -> list[dict] | None: p = LB._suite_dir(which) / f"{suite}.jsonl" return LB.load(which, suite) if p.exists() else None def validate_t4(which: str) -> dict: rows = _load(which, "t4") pub = published_t4() name = T4_NAME.get(which) if rows is None or name is None: return {} out = {"suites": {}} per = by_key(rows, lambda r: r["meta"]["t4_suite"]) ours_sum = {} for suite, rs in per.items(): p = pub["suites"][suite][name] cal, raw = laya_metrics(rs, which), summarize(rs, 1.0) ours_sum[suite] = cal out["suites"][suite] = { "n": cal["n"], "truncated_rows": sum(bool(r["meta"].get("laya_truncated")) for r in rs), "accuracy": _cmp(cal["accuracy"], p["calibrated"]["accuracy"], cal["n"]), "ece_shipped_T": _cmp(cal["ece"], p["calibrated"]["ece"], cal["n"], "ece"), "ece_raw": _cmp(raw["ece"], p["raw"]["ece"], cal["n"], "ece"), "macro_f1": _cmp(cal["macro_f1"], p["calibrated"]["macro_f1"], cal["n"], "f1"), "nll_shipped_T": _cmp(cal["nll"], p["calibrated"]["nll"], None, "nll")} fam = {"massive_intent": [s for s in per if s.startswith("massive_intent.")], "massive_scenario": [s for s in per if s.startswith("massive_scenario.")], "xnli": [s for s in per if s.startswith("xnli.")], "english": [s for s in per if s.startswith("en.")]} out["families"] = {} for f, ss in fam.items(): p = pub["summary"][f][name] out["families"][f] = { "macro_accuracy": _cmp(np.mean([ours_sum[s]["accuracy"] for s in ss]), p["macro_accuracy"], sum(ours_sum[s]["n"] for s in ss)), "macro_ece": _cmp(np.mean([ours_sum[s]["ece"] for s in ss]), p["macro_ece"], None, "ece")} p = pub["summary"]["typed_decisions"][name] out["families"]["typed_decisions"] = {"accuracy": _cmp(ours_sum["typed_decisions"]["accuracy"], p["accuracy"], 2000)} out["english_vs_rest"] = {} for f in ("massive_intent", "massive_scenario", "xnli"): p = pub["summary"][f"{f}_english_vs_rest"] en = ours_sum[f"{f}.en"]["accuracy"] rest = np.mean([ours_sum[s]["accuracy"] for s in fam[f] if s != f"{f}.en"]) out["english_vs_rest"][f] = {"english": _cmp(en, p["english"][name], 300), "non_english": _cmp(rest, p["non_english"][name], 300 * (len(fam[f]) - 1))} rep = laya_refit(rows, checkpoint_config(which)) pub_rep = pub["calibration_repair"][name] out["calibration_repair"] = { "mean_ece_refit": _cmp(rep["mean_ece_refit"], pub_rep["mean_ece_refit"], None, "ece"), "mean_ece_shipped": _cmp(rep["mean_ece_shipped"], pub_rep["mean_ece_shipped"], None, "ece"), "benchmarks_md_refit": BENCH_MD_HEADLINE["refit_ece_49"][which], "per_suite_ece_refit_absdiff_max": float(max(abs(rep["per_suite"][s]["ece_refit"] - pub_rep["per_suite"][s]["ece_refit"]) for s in rep["per_suite"]))} return out def validate_typed(which: str) -> dict: rows = _load(which, "typed_test") if rows is None: return {} m = laya_metrics(rows, which) cpu = published_cpu_sweep()["part_b"]["by_model"].get(CPU_NAME[which], {}) # the sweep only kept "english" out = {"n": m["n"], "cpu_sweep": {k: _cmp(m.get(k), cpu.get(k), m["n"] if k == "accuracy" else None, "rate" if k == "accuracy" else "x") for k in ("accuracy", "macro_f1", "ece", "brier", "nll", "soft_accuracy", "brier_vs_soft", "score_mae", "within_1_level")}, "benchmarks_md": {k: _cmp(m.get(k), v, m["n"] if k == "accuracy" else None, "rate" if k == "accuracy" else "x", MD_DECIMALS) for k, v in TYPED_PUBLISHED[which].items()}} if which == "typed": wf = by_key(rows, lambda r: r["meta"]["workflow"]) out["by_workflow"] = {w: _cmp(laya_metrics(rs, which)["accuracy"], TYPED_WORKFLOW_PUBLISHED.get(w), len(rs), "rate", MD_DECIMALS) for w, rs in sorted(wf.items())} return out def validate_massive51(which: str) -> dict: rows = _load(which, "massive51") name = CPU_NAME[which] pub = published_cpu_sweep()["part_a"]["by_model"].get(name) if rows is None: return {} per = by_key(rows, lambda r: r["lang"]) ms = {lg: laya_metrics(rs, which) for lg, rs in per.items()} accs = [m["accuracy"] for m in ms.values()] ours = {"macro_accuracy": float(np.mean(accs)), "macro_ece": float(np.mean([m["ece"] for m in ms.values()])), "languages_above_random": int(sum(a > 3.0 / 20 for a in accs)), "n_languages": len(ms), "unsupported": sum(r["status"] != "ok" for r in rows)} if pub is None: return {"published": None, "ours": ours} out = {"macro_accuracy": _cmp(ours["macro_accuracy"], pub["macro_accuracy"], 5100), "macro_ece": _cmp(ours["macro_ece"], pub["macro_ece"], None, "ece"), "languages_above_random": {"ours": ours["languages_above_random"], "published": pub["languages_above_random"]}, "per_language": {}} n_exact = 0 for lg, m in sorted(ms.items()): p = pub["per_language"][lg] c = _cmp(m["accuracy"], p["accuracy"], m["n"]) out["per_language"][lg] = {"accuracy": c, "ece": _cmp(m["ece"], p["ece"], None, "ece"), "mean_confidence": _cmp(m["mean_confidence"], p["mean_confidence"], None, "x")} n_exact += c["verdict"] in ("exact", "reproduced") out["languages_reproduced_exactly"] = n_exact # within one row (exact or reproduced) return out def validate_apps(which: str) -> dict: rows = _load(which, "apps") if rows is None: return {} out = {} for suite, rs in sorted(by_key(rows, lambda r: r["meta"]["suite"]).items()): m = laya_metrics(rs, which) gold = Counter(r["valid"][0] for r in rs) out[suite] = {"accuracy": _cmp(m["accuracy"], APPS_PUBLISHED[suite][which], m["n"], "rate", MD_DECIMALS), "macro_f1": m["macro_f1"], "ece": m["ece"], "n": m["n"], "majority_class_accuracy": round(max(gold.values()) / len(rs), 4), "unsupported": m["n_unsupported"], "truncated_rows": sum(bool(r["meta"].get("laya_truncated")) for r in rs)} extra = APPS_PUBLISHED_EXTRA.get((suite, which, "macro_f1")) if extra is not None: out[suite]["macro_f1_vs_published"] = _cmp(m["macro_f1"], extra, m["n"], "f1", MD_DECIMALS) return out def validate_flip(which: str) -> dict: rows = _load(which, "flip") name = T4_NAME.get(which) if rows is None: return {} pub = published_t4()["option_order_robustness"].get(name, {}) if name else {} out = {} for suite, rs in sorted(by_key(rows, lambda r: r["meta"]["suite"].removeprefix("flip.")).items()): f = flip_rate(rs) out[suite] = _cmp(f["flip_rate"], pub.get(suite, {}).get("flip_rate"), f["n"]) if pub else {"ours": f["flip_rate"], "n": f["n"]} return out def validate_all() -> dict: res = {} for which in LB.WHICH: res[which] = {"t4": validate_t4(which), "typed_test": validate_typed(which), "massive51": validate_massive51(which), "apps": validate_apps(which), "flip": validate_flip(which)} return res def _needs_explanation(path: str, v: str) -> bool: """Every gap; and 2-3-row differences outside the T4 notebook comparisons (T4 GPU vs MPS is the only device difference that can flip more than one near-tie row).""" return v == "gap" or (v == "within_noise" and "/t4/" not in path and "/flip/" not in path) def explanation_for(path: str) -> str | None: return next((v for k, v in EXPLANATIONS.items() if path.startswith(k)), None) def tally(res) -> dict: c: Counter = Counter() gaps, unexplained = [], [] def walk(x, path): if isinstance(x, dict): if "verdict" in x and "published" in x: c[x["verdict"]] += 1 if _needs_explanation(path, x["verdict"]): gaps.append({"where": path, **x}) if explanation_for(path) is None: unexplained.append(path) return for k, v in x.items(): walk(v, f"{path}/{k}") walk(res, "") return {"counts": dict(c), "gaps": gaps, "unexplained": unexplained} # Explanations for every non-reproduced published number (checked by hand, see the report). EXPLANATIONS = { "/multilingual/typed_test/benchmarks_md": ( "BENCHMARKS.md's laya-multilingual typed row (0.342 / ECE 0.285 / Brier 0.439 / MAE 0.687) disagrees with " "Laya's own T4 JSON for the same checkpoint and rows (accuracy 0.3515, ECE 0.3144); our numbers equal the T4 " "JSON. The CPU sweep that probably produced the Markdown row kept only the english model in part_b, so the " "Markdown value cannot be re-derived; this is an inconsistency inside Laya's publication, not our stack."), "/english/t4/suites/": ( "Single-suite ECE / macro-F1 / NLL deviations of <= 0.02 on the T4 suites with heavy truncation or T=0.1 " "sharpening: the published run used a Tesla T4 (CUDA) and we score on MPS fp32; round-1 and our LayaScorer " "agree to 1e-4 in logits, so near-tie rows flip between devices. Accuracy, family macros and the refit ECE " "reproduce."), "/multilingual/t4/suites/": "same device-numerics explanation as for english T4 suites", "/multilingual/massive51/": ( "NOT REPRODUCED - cause not established (hypothesis only). Affects laya-multilingual only, and only Laya's " "local CPU runs (CPU sweep and bench_apps: laya 0.2.0, ~/laya_models/laya-multilingual). The same scripts, rows " "and loaders reproduce the english checkpoint (51/51 languages) and the english and typed checkpoints on all 10 " "app suites (every accuracy exact at the published precision), and the same " "multilingual weights reproduce Laya's own T4 JSON (14 languages x 3 families, flip rates, refit ECE 0.106). " "Device and padding are ruled out (multilingual/massive51_device_check.json: CPU batched, CPU unpadded and MPS " "agree to 2e-4 in logits, 400/400 argmax); so are the english default budgets (512/192 instead of the shipped " "1024/256: identical accuracies on all 10 app suites, multilingual/budget_hypothesis_check.json). With the laya-0.2.0 email cleaning the multilingual email_spam and " "phishing numbers reproduce exactly, so it is not a wholesale model mix-up. Hypothesis: Laya's local " "laya-multilingual snapshot or its local transformers version (mmBERT tokenizer / ModernBERT attention code) " "differed from the published checkpoint and from the Colab environment (transformers 5.17.0, which we match); " "not verifiable without Laya's local files. Our re-run is higher than the published MASSIVE-51 macro (0.401 vs " "0.366) and every divergent bench_apps figure (7 of 51 languages are lower, e.g. sv 0.49 vs 0.57), so the " "scoreboard, which uses our paired re-run, is the stricter target on those headline metrics."), "/multilingual/apps/": "same laya-multilingual CPU-environment explanation as for /multilingual/massive51/", } def to_markdown(res: dict, t: dict) -> str: L = ["# Laya reproduction check", "", f"Verdicts: {json.dumps(t['counts'])}", f"Entries needing an explanation: {len(t['gaps'])}; UNEXPLAINED: {len(t['unexplained'])}", "", "exact = equal at the published precision; reproduced = at most one row differs; within_noise = 2-3 rows " "(or ECE/F1 <= 0.02); gap = larger. Rows are identical and the checkpoints deterministic, so binomial " "standard errors are not used as a tolerance.", ""] L += ["| checkpoint | area | metric | ours | published | verdict |", "|---|---|---|---|---|---|"] def row(w, area, name, c): L.append(f"| {w} | {area} | {name} | {c['ours']} | {c['published']} | {c['verdict']} |") for w, r in res.items(): t4 = r.get("t4") or {} for f, x in (t4.get("families") or {}).items(): for k, c in x.items(): row(w, "T4 family", f"{f} {k}", c) for f, x in (t4.get("english_vs_rest") or {}).items(): for k, c in x.items(): row(w, "T4 en-vs-rest", f"{f} {k}", c) for k in ("mean_ece_refit", "mean_ece_shipped"): if t4.get("calibration_repair"): row(w, "49-suite calibration", k, t4["calibration_repair"][k]) for k, c in (r.get("typed_test") or {}).get("benchmarks_md", {}).items(): row(w, "typed-decisions (BENCHMARKS.md)", k, c) m = r.get("massive51") or {} for k in ("macro_accuracy", "macro_ece"): if isinstance(m.get(k), dict) and "verdict" in m[k]: row(w, "MASSIVE 51", k, m[k]) if "languages_reproduced_exactly" in m: L.append(f"| {w} | MASSIVE 51 | languages reproduced / above 3x random | " f"{m['languages_reproduced_exactly']}/51, {m['languages_above_random']['ours']} | " f"51, {m['languages_above_random']['published']} | |") for s, x in (r.get("apps") or {}).items(): row(w, "bench_apps", s, x["accuracy"]) for s, c in (r.get("flip") or {}).items(): if "verdict" in c: row(w, "flip rate", s, c) L += ["", "## Gaps and explanations", ""] groups: dict = {} for g in t["gaps"]: groups.setdefault(explanation_for(g["where"]) or "UNEXPLAINED", []).append(g) for expl, gs in groups.items(): L.append(f"**{len(gs)} entries** — {expl}") L.append("") for g in gs: L.append(f"- `{g['where']}` ({g['verdict']}): ours {g['ours']} vs published {g['published']}") L.append("") return "\n".join(L) + "\n" def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("--out", default=str(LB.OUT / "validation")) a = ap.parse_args(argv) res = validate_all() out = Path(a.out) out.mkdir(parents=True, exist_ok=True) t = tally(res) (out / "validation.json").write_text(json.dumps({"tally": t, "results": res}, indent=1) + "\n") (out / "validation.md").write_text(to_markdown(res, t)) print(json.dumps(t["counts"])) for g in t["gaps"]: flag = "" if explanation_for(g["where"]) else " UNEXPLAINED" print(f"{g['verdict'].upper()} {g['where']}: ours {g['ours']} published {g['published']} (n={g['n']}){flag}") if t["unexplained"]: raise SystemExit(f"{len(t['unexplained'])} unexplained reproduction gaps") if __name__ == "__main__": main()