pynterest83's picture
Telasap-0.8B v1.0 (exp10yc): router model + /v1/systemone server
72c7148 verified
Raw History Blame Contribute Delete
65.6 kB
"""Scoreboard: our model vs the three official Laya checkpoints on identical rows. python -m macjev.eval.report --ours <eval.cli dir> [<dir> ...] [--temperatures temperatures.json] [--ours-heldout <seed1 dir> [...]] [--temperatures-heldout t.json] [--latency runs/macjev/latency/<run>/latency.json] [--latency-ours engine-default] [--laya runs/macjev/laya_baselines] --out <dir> [--n-boot 2000] [--template zh | <template file>] Writes scoreboard.json, scoreboard.md (English), scoreboard.zh.md and, with --template, report.zh.md. Every row carries its protocol (in-domain / held-out, ours and Laya). Two protocols for Emotion and SST-5: seed0 (in-domain) and the seed1 held-out ablation (--ours-heldout), the latter being the like-for-like comparison with Laya. MASSIVE-51 is also split into our 14 trained and 37 never-trained languages. Sections after the main table: long-context grid (controlled item accuracy, item-bootstrap CIs, paired against any Laya long_grid predictions; the preregistered long_grid 25K claim AND the amended long_grid_plus claim -- amended pre-data 2026-09-24: +96 items per 24K decile, thresholds unchanged -- each on its own rows) and latency (macjev.export.latency output, ratio of medians CI). For every metric Laya advertises (third_party/laya/BENCHMARKS.md, the T4 and CPU-sweep JSON) the report gives our value, each Laya checkpoint's value under Laya's own protocol (shipped temperatures as published), the best Laya value, and for every checkpoint the paired difference (ours - laya) with a 95% case-cluster bootstrap CI (clusters = ``group_id``, resampled within each suite so macro averages keep all suites) and, for accuracy, an exact McNemar p-value. Only rows scored ``ok`` by both sides enter a paired comparison; the number of rows either side could not score is reported (Laya's unsupported rows count as errors in ``accuracy_counting_unsupported``). Our model's probabilities use --temperatures when given. Refit-ECE (49 suites) has no CI (each replicate would refit 49 x buckets temperatures). """ from __future__ import annotations import argparse import json import math from collections import Counter from dataclasses import dataclass from pathlib import Path from typing import Callable import numpy as np from . import laya_baselines as LB from .aggregate import GRID_PLUS_AMENDMENT_LABEL, long_grid_subset, typed_long_workflow from .laya_scorer import checkpoint_config, shipped_temperature_fn from .metrics import ece, flip_rate, per_row from .predictions import read_jsonl from .stats import mcnemar @dataclass class Metric: key: str label: str suite: str # prediction file stem select: Callable[[dict], bool] # row filter stat: str # accuracy | ece | nll | brier | soft_accuracy | score_mae | macro_f1 | flip higher_better: bool strata: Callable[[dict], str] | None = None # macro over strata (e.g. languages) published_best: float | None = None note: str = "" run: str = "main" # main = seed0 predictions; heldout = seed1 ablation (--ours-heldout) def _s(prefix): return lambda r: str((r.get("meta") or {}).get("suite", "")).startswith(prefix) def _eq(name): return lambda r: (r.get("meta") or {}).get("suite") == name def _t4(names): names = set(names) return lambda r: (r.get("meta") or {}).get("t4_suite") in names XNLI_REST = ["xnli." + x for x in ("de", "fr", "es", "ru", "tr", "ar", "hi", "ur", "vi", "th", "el", "bg", "zh", "sw")] MI_REST = ["massive_intent." + x for x in ("de", "fr", "es", "pt", "ru", "tr", "ar", "hi", "ta", "zh-CN", "ja", "ko", "sw")] MS_REST = [x.replace("intent", "scenario") for x in MI_REST] ALL = lambda r: True # noqa: E731 BY_T4 = lambda r: r["meta"]["t4_suite"] # noqa: E731 BY_LANG = lambda r: r["lang"] # noqa: E731 SCOREBOARD = [ Metric("typed.accuracy", "typed-decisions accuracy (2,000)", "typed_test", ALL, "accuracy", True, None, 0.766), Metric("typed.soft_accuracy", "typed-decisions soft accuracy", "typed_test", ALL, "soft_accuracy", True, None, 0.471), Metric("typed.brier_vs_soft", "typed-decisions Brier vs soft labels", "typed_test", ALL, "brier_soft", False, None, 0.061), Metric("typed.score_mae", "typed-decisions score MAE", "typed_test", ALL, "score_mae", False, None, 0.242), Metric("typed.ece", "typed-decisions ECE", "typed_test", ALL, "ece", False, None, 0.175), *[Metric(f"typed.workflow.{wf}", f"typed-decisions accuracy, workflow {wf} (500)", "typed_test", (lambda r, wf=wf: (r.get("meta") or {}).get("workflow") == wf), "accuracy", True, None, pub) for wf, pub in (("agent_trace_observability", 0.730), ("customer_service", 0.764), ("invoice_processing", 0.804), ("security_incidents", 0.766))], Metric("ag.first400", "AG News first 400 (bench_apps)", "apps", _eq("apps.jev.ag_news"), "accuracy", True, None, 0.953), Metric("ag.first600", "AG News first 600 (T4)", "t4", _t4(["en.ag_news"]), "accuracy", True, None, 0.947), Metric("ag.full", "AG News full test (7,600)", "ag_news_full", ALL, "accuracy", True, None, 0.929, "plan value from round-1 Laya predictions"), Metric("emotion.first400", "DAIR Emotion first 400 (bench_apps)", "apps", _eq("apps.jev.emotion"), "accuracy", True, None, 0.600), Metric("emotion.first600", "DAIR Emotion first 600 (T4)", "t4", _t4(["en.emotion"]), "accuracy", True), Metric("emotion.full", "DAIR Emotion full test (2,000)", "emotion_full", ALL, "accuracy", True), Metric("banking77", "banking77 first 400, 77 labels", "apps", _eq("apps.jev.banking77_full"), "accuracy", True, None, 0.492), Metric("sst5", "SST-5 first 600 (score)", "t4", _t4(["en.sst5"]), "accuracy", True, None, 0.372), Metric("massive51.macro_accuracy", "MASSIVE 51-language intent, macro accuracy", "massive51", ALL, "accuracy", True, BY_LANG, 0.366), Metric("massive51.macro_ece", "MASSIVE 51-language intent, macro ECE", "massive51", ALL, "ece", False, BY_LANG, 0.387), Metric("massive51.languages_above_3x_random", "MASSIVE 51: languages with accuracy > 3x random (0.15)", "massive51", ALL, "strata_above_3x_random", True, BY_LANG, 45), Metric("xnli.en", "XNLI English (300)", "t4", _t4(["xnli.en"]), "accuracy", True, None, 0.860), Metric("xnli.rest", "XNLI 14 other languages, macro", "t4", _t4(XNLI_REST), "accuracy", True, BY_T4, 0.731), Metric("massive_intent.en", "MASSIVE intent English (T4, 300)", "t4", _t4(["massive_intent.en"]), "accuracy", True, None, 0.783), Metric("massive_intent.rest", "MASSIVE intent 13 other languages, macro", "t4", _t4(MI_REST), "accuracy", True, BY_T4, 0.451), Metric("massive_scenario.en", "MASSIVE scenario English (T4, 300)", "t4", _t4(["massive_scenario.en"]), "accuracy", True, None, 0.603), Metric("massive_scenario.rest", "MASSIVE scenario 13 other languages, macro", "t4", _t4(MS_REST), "accuracy", True, BY_T4, 0.439), Metric("t4.macro_ece_as_deployed", "49-suite macro ECE, as deployed", "t4", ALL, "ece", False, BY_T4, None, "ours: our temperatures; Laya: shipped"), Metric("t4.macro_nll", "49-suite macro NLL, as deployed", "t4", ALL, "nll", False, BY_T4), Metric("t4.macro_brier", "49-suite macro Brier, as deployed", "t4", ALL, "brier", False, BY_T4), ] for suite, pub in [("email_spam", 0.993), ("phishing", 0.993), ("guardrails_jailbreak", 0.762), ("moderation_toxicity", 0.530), ("rag_relevance", 0.657), ("support_triage", 0.522), ("model_routing_domain", 0.659)]: SCOREBOARD.append(Metric(f"theme.{suite}", f"theme {suite} (bench_apps, N=400)", "apps", _eq("apps." + suite), "accuracy", True, None, pub)) SCOREBOARD.append(Metric("theme.moderation_toxicity.macro_f1", "theme moderation macro-F1", "apps", _eq("apps.moderation_toxicity"), "macro_f1", True, None, 0.400)) # Imbalanced suites: accuracy alone can be beaten by a constant answer (guardrails: 309/400 "false", # i.e. 0.7725 > every published Laya guardrails accuracy), so balanced accuracy and macro-F1 are # reported too (review 2026-09-23). No published values exist for these. for suite in ("guardrails_jailbreak", "phishing", "email_spam", "support_triage", "jev.banking77_full"): SCOREBOARD.append(Metric(f"theme.{suite}.balanced_accuracy", f"{suite} balanced accuracy (mean recall)", "apps", _eq("apps." + suite), "balanced_accuracy", True)) SCOREBOARD.append(Metric("theme.guardrails_jailbreak.macro_f1", "guardrails_jailbreak macro-F1", "apps", _eq("apps.guardrails_jailbreak"), "macro_f1", True)) for suite, pub in [("massive_intent.en", 0.150), ("en.emotion", 0.040), ("xnli.en", 0.000)]: SCOREBOARD.append(Metric(f"flip.{suite}", f"option-order flip rate {suite} (200 pairs)", "flip", _eq("flip." + suite), "flip", False, None, pub)) # Macro-F1 next to balanced accuracy for every imbalanced/multi-class theme the plan names (plan 1.1). for suite in ("email_spam", "phishing", "support_triage"): SCOREBOARD.append(Metric(f"theme.{suite}.macro_f1", f"{suite} macro-F1", "apps", _eq("apps." + suite), "macro_f1", True)) SCOREBOARD.append(Metric("theme.moderation_toxicity.balanced_accuracy", "moderation_toxicity balanced accuracy " "(mean recall)", "apps", _eq("apps.moderation_toxicity"), "balanced_accuracy", True)) # MASSIVE-51 split by our training coverage: the 14 benchmark locales are trained (builders.general # MASSIVE_LOCALES), the other 37 languages never are. Laya trained on none of them. MASSIVE_TRAINED = ("en", "de", "fr", "es", "pt", "ru", "tr", "ar", "hi", "ta", "zh-CN", "ja", "ko", "sw") _M_SEEN = lambda r: r["lang"] in MASSIVE_TRAINED # noqa: E731 _M_UNSEEN = lambda r: r["lang"] not in MASSIVE_TRAINED # noqa: E731 SCOREBOARD += [ Metric("massive51.trained14.macro_accuracy", "MASSIVE 51: 14 trained languages, macro accuracy", "massive51", _M_SEEN, "accuracy", True, BY_LANG), Metric("massive51.unseen37.macro_accuracy", "MASSIVE 51: 37 never-trained languages, macro accuracy", "massive51", _M_UNSEEN, "accuracy", True, BY_LANG), Metric("massive51.unseen37.languages_above_3x_random", "MASSIVE 51: never-trained languages > 3x random " "(of 37)", "massive51", _M_UNSEEN, "strata_above_3x_random", True, BY_LANG), ] # Our own sealed suites (data/eval-v3). No Laya baseline has been run on them (typed_synth_unseen and # mac_gate_test could be; long_grid gets its own section below), so these are "ours only" rows with a # one-sample CI until Laya prediction files appear next to the others. typed_long_unseen (4K-24K versions of # typed_synth_unseen) is scored on its real-state rows only: its question_only / state_swap control rows keep # the real item's gold (aggregate.suite_metrics reports their control analysis). _WF = lambda r: str((r.get("meta") or {}).get("workflow")) # noqa: E731 _REAL = lambda r: (r.get("meta") or {}).get("control", "none") == "none" # noqa: E731 SCOREBOARD += [ Metric("typed_synth_unseen.accuracy", "typed synthetic, unseen workflows: accuracy (macro over workflows)", "typed_synth_unseen", ALL, "accuracy", True, _WF), Metric("typed_synth_unseen.brier_vs_soft", "typed synthetic, unseen workflows: Brier vs soft labels", "typed_synth_unseen", ALL, "brier_soft", False), Metric("typed_long_unseen.accuracy", "typed synthetic 4K-24K, unseen workflows: accuracy, real-state rows " "(macro over workflows)", "typed_long_unseen", _REAL, "accuracy", True, typed_long_workflow), Metric("typed_long_unseen.brier_vs_soft", "typed synthetic 4K-24K, unseen workflows: Brier vs soft labels, " "real-state rows", "typed_long_unseen", _REAL, "brier_soft", False), Metric("mac_gate_test.macro_over_labels", "Mac gate test: macro accuracy over gold labels", "mac_gate_test", ALL, "balanced_accuracy", True), Metric("mac_goal_done_test.macro_over_labels", "Mac goal-done test: macro accuracy over gold labels", "mac_goal_done_test", ALL, "balanced_accuracy", True), ] # Second protocol (user request, plan 3.1 "留出消融版 seed1"): the seed1 ablation never trains DAIR Emotion # or SST-5, so its numbers are the like-for-like comparison with Laya's held-out figures. The seed0 rows # above are in-domain for these two datasets and are NOT comparable with Laya's held-out numbers. HELDOUT_KEYS = ("emotion.first400", "emotion.first600", "emotion.full", "sst5", "flip.en.emotion") SCOREBOARD += [Metric(m.key + "@heldout", m.label + " [held-out ablation seed1]", m.suite, m.select, m.stat, m.higher_better, m.strata, m.published_best, m.note, run="heldout") for m in list(SCOREBOARD) if m.key in HELDOUT_KEYS] # ------------------------------------------------------------------------------ protocols # (ours, Laya) training status of each metric's source. Sources: plan 3.1, builders' docstrings # (general, themes, nli_intent), the pool's train sources, and docs/round2_audit/FACTBASE 2.5 + # third_party/laya/BENCHMARKS.md for Laya. Longest key prefix wins. IN, HO = "in-domain", "held-out" PROTOCOLS: dict[str, tuple[str, str]] = { "typed.": (IN, "in-domain (typed ckpt) / held-out (english, multilingual)"), "ag.": (IN, "in-domain (training mix)"), "emotion.": ("in-domain (seed0 trains DAIR Emotion) - not comparable with Laya", HO), "sst5": ("in-domain (seed0 trains SST-5) - not comparable with Laya", HO), "banking77": ("held-out (banking77 never trained; CLINC150/HWU64 intents are)", HO), "massive51.": ("mixed: 14 trained + 37 never-trained languages", HO), "massive51.trained14": ("in-domain (MASSIVE train, 14 locales)", HO), "massive51.unseen37": ("held-out (37 languages never trained)", HO), "xnli.": ("near-domain (MNLI + teacher-translated NLI; XNLI itself never trained)", HO), "massive_intent.": ("in-domain (MASSIVE train, 14 locales)", HO), "massive_scenario.": ("in-domain (MASSIVE train, 14 locales)", HO), "t4.": ("mixed (49 suites)", "mixed (49 suites)"), "theme.email_spam": ("in-domain (enron_spam train split; eval = test split)", IN), "theme.phishing": ("in-domain (same dataset, evaluated rows excluded)", IN), "theme.guardrails_jailbreak": ("held-out source (other permissive jailbreak sets + teacher)", HO), "theme.moderation_toxicity": ("held-out source (civil_comments + teacher; toxic-chat eval-only)", HO), "theme.rag_relevance": ("held-out source (SQuAD v2 pairs; MS MARCO eval-only)", IN), "theme.support_triage": ("near-domain (teacher-written tickets; the NC ticket set never trained)", IN), "theme.model_routing_domain": ("near-domain (teacher-written; gsm8k/mbpp/AG rows eval-only)", HO), "theme.jev.banking77_full": ("held-out (banking77 never trained)", HO), "flip.massive_intent.en": (IN, HO), "flip.en.emotion": ("in-domain (seed0) - not comparable with Laya", HO), "flip.xnli.en": ("near-domain (MNLI)", HO), "typed_synth_unseen": ("held-out workflows (never trained)", "not run"), "typed_long_unseen": ("held-out workflows (never trained)", "not run"), "mac_gate_test": ("in-domain task (held-out rule groups)", "not applicable"), "mac_goal_done_test": ("in-domain task (held-out test apps)", "not applicable"), "long_grid": ("in-domain task (own grid, never trained)", "budget <= 4K (8K/16K unsupported)"), } HELDOUT_PROTOCOL = "held-out (seed1 ablation: DAIR Emotion and SST-5 never trained)" def protocol(key: str) -> tuple[str, str]: base = key.split("@")[0] hit = max((p for p in PROTOCOLS if base.startswith(p)), key=len, default=None) ours, laya = PROTOCOLS[hit] if hit else ("?", "?") if key.endswith("@heldout"): ours = HELDOUT_PROTOCOL return ours, laya # ------------------------------------------------------------------------------ statistics def _arrays(pr: list[dict]) -> dict: out = {"correct": np.array([d["correct"] for d in pr]), "conf": np.array([d["conf"] for d in pr]), "nll": np.array([d["nll"] for d in pr]), "brier": np.array([d["brier"] for d in pr]), "gold": np.array([d["gold"] for d in pr]), "pred": np.array([d["pred"] for d in pr]), "gold_name": np.array([d["gold_name"] for d in pr], dtype=object), "pred_name": np.array([d["pred_name"] for d in pr], dtype=object)} edges = np.linspace(0, 1, 16) b = np.searchsorted(edges, out["conf"], side="left") - 1 # bin k <=> conf in (e_k, e_k+1] out["bin"] = np.where((b >= 0) & (b < 15), b, 15) # 15 = outside (conf == 0) for k in ("soft_acc", "brier_soft", "abs_err_score"): vals = [d.get(k) for d in pr] out[k + "_mask"] = np.array([v is not None for v in vals]) out[k] = np.array([v if v is not None else 0.0 for v in vals]) return out def _value(A: dict, w: np.ndarray, stat: str) -> float: if w.sum() <= 0: return float("nan") if stat == "accuracy": return float((w * A["correct"]).sum() / w.sum()) if stat in ("nll", "brier"): return float((w * A[stat]).sum() / w.sum()) if stat in ("soft_accuracy", "brier_soft", "score_mae"): k = {"soft_accuracy": "soft_acc", "score_mae": "abs_err_score"}.get(stat, stat) ww = w * A[k + "_mask"] return float((ww * A[k]).sum() / ww.sum()) if ww.sum() > 0 else float("nan") if stat == "ece": # == metrics.ece(conf, correct, weights=w), vectorised sc = np.bincount(A["bin"], weights=w * A["conf"], minlength=16)[:15] sa = np.bincount(A["bin"], weights=w * A["correct"], minlength=16)[:15] return float(np.abs(sc - sa).sum() / w.sum()) if stat == "balanced_accuracy": g = A["gold_name"] rec = [(w * A["correct"] * (g == c)).sum() / (w * (g == c)).sum() for c in np.unique(g) if (w * (g == c)).sum() > 0] return float(np.mean(rec)) if rec else float("nan") if stat == "macro_f1": # by option NAME: option order may differ between rows g, p = A["gold_name"], A["pred_name"] f = [] for c in sorted(set(g.tolist()) | set(p.tolist())): tp = (w * ((p == c) & (g == c))).sum() fp = (w * ((p == c) & (g != c))).sum() fn = (w * ((p != c) & (g == c))).sum() f.append(2 * tp / max(1e-12, 2 * tp + fp + fn) if (2 * tp + fp + fn) > 0 else 0.0) return float(np.mean(f)) raise KeyError(stat) def _split(A: dict, strata: np.ndarray | None) -> list[tuple[np.ndarray, dict]]: if strata is None: return [(np.arange(len(A["correct"])), A)] out = [] for s in np.unique(strata): idx = np.nonzero(strata == s)[0] out.append((idx, {k: v[idx] for k, v in A.items()})) return out def _macro(parts: list[tuple[np.ndarray, dict]], w: np.ndarray, stat: str) -> float: if stat == "strata_above_3x_random": # Laya's "languages clearing 3x random" (20 options) return float(sum(_value(sub, w[idx], "accuracy") > 3.0 / 20 for idx, sub in parts)) vals = [_value(sub, w[idx], stat) for idx, sub in parts] return float(np.nanmean(vals)) if len(vals) > 1 else vals[0] def _strata_level_boot(PA, PB, stat: str, n_boot: int, rng) -> np.ndarray: """Bootstrap by resampling whole strata. Used when every stratum is a single cluster (e.g. unseen workflows, group_id = workflow): within-stratum resampling would then return a zero-width CI.""" base = "accuracy" if stat == "strata_above_3x_random" else stat def per(parts): v = np.array([_value(sub, np.ones(len(idx)), base) for idx, sub in parts]) return (v > 3.0 / 20).astype(float) if stat == "strata_above_3x_random" else v agg = np.sum if stat == "strata_above_3x_random" else np.nanmean va = per(PA) vb = per(PB) if PB is not None else np.zeros_like(va) idx = rng.integers(0, len(va), (n_boot, len(va))) return np.array([agg(va[i]) - agg(vb[i]) for i in idx]) def paired(rows_a, rows_b, stat, temps_a, temps_b, strata_fn=None, n_boot=2000, seed=0, pra=None, prb=None) -> dict: """``pra``/``prb``: optional precomputed {id: per_row dict} (same temperatures) to avoid recomputation.""" ids_ok_a = {r["id"] for r in rows_a if r["status"] == "ok"} ids_ok_b = {r["id"] for r in rows_b if r["status"] == "ok"} common = ids_ok_a & ids_ok_b ra = sorted([r for r in rows_a if r["id"] in common], key=lambda r: r["id"]) rb = sorted([r for r in rows_b if r["id"] in common], key=lambda r: r["id"]) pa = [pra[r["id"]] for r in ra] if pra is not None else per_row(ra, temps_a) pb = [prb[r["id"]] for r in rb] if prb is not None else per_row(rb, temps_b) n_all = len({r["id"] for r in rows_a} | {r["id"] for r in rows_b}) base = {"n_paired": len(common), "unscored_a": len({r["id"] for r in rows_a}) - len(ids_ok_a), "unscored_b": len({r["id"] for r in rows_b}) - len(ids_ok_b), "n_rows": n_all} if not common: return base A, B = _arrays(pa), _arrays(pb) strata = np.array([strata_fn(r) for r in ra]) if strata_fn else None PA, PB = _split(A, strata), _split(B, strata) ones = np.ones(len(ra)) a, b = _macro(PA, ones, stat), _macro(PB, ones, stat) clusters: dict = {} cl = np.array([clusters.setdefault(r["group_id"], len(clusters)) for r in ra]) cl_stratum = {} for r, c in zip(ra, cl): cl_stratum[c] = strata_fn(r) if strata_fn else "_" by_st: dict = {} for c, s in cl_stratum.items(): by_st.setdefault(s, []).append(c) rng = np.random.default_rng(seed) diffs = [] if strata_fn and len(by_st) > 1 and all(len(cs) == 1 for cs in by_st.values()): diffs = _strata_level_boot(PA, PB, stat, n_boot, rng) for _ in range(0 if len(diffs) else n_boot): counts = np.zeros(len(clusters)) for s, cs in by_st.items(): pick = rng.integers(0, len(cs), len(cs)) np.add.at(counts, np.asarray(cs)[pick], 1) w = counts[cl] diffs.append(_macro(PA, w, stat) - _macro(PB, w, stat)) diffs = np.asarray(diffs) diffs = diffs[~np.isnan(diffs)] out = {**base, "a": a, "b": b, "diff": a - b, "ci95": [float(np.quantile(diffs, 0.025)), float(np.quantile(diffs, 0.975))] if len(diffs) else None} if stat == "accuracy": out["mcnemar"] = mcnemar(A["correct"], B["correct"]) return out def paired_flip(rows_a, rows_b, n_boot=2000, seed=0) -> dict: def pairs(rows): by: dict = {} for r in rows: m = r["meta"] by.setdefault(m["flip_pair"], {})[m["flip_kind"]] = r out = {} for k, v in by.items(): if "base" in v and "perm" in v and v["base"]["status"] == "ok" and v["perm"]["status"] == "ok": na = v["base"]["names"][int(np.argmax(v["base"]["logits"]))] nb = v["perm"]["names"][int(np.argmax(v["perm"]["logits"]))] out[k] = float(na != nb) return out fa, fb = pairs(rows_a), pairs(rows_b) keys = sorted(set(fa) & set(fb)) if not keys: return {"n_paired": 0} xa, xb = np.array([fa[k] for k in keys]), np.array([fb[k] for k in keys]) rng = np.random.default_rng(seed) idx = rng.integers(0, len(keys), (n_boot, len(keys))) d = xa[idx].mean(1) - xb[idx].mean(1) return {"n_paired": len(keys), "a": float(xa.mean()), "b": float(xb.mean()), "diff": float(xa.mean() - xb.mean()), "ci95": [float(np.quantile(d, 0.025)), float(np.quantile(d, 0.975))]} def single(rows, stat, temps, strata_fn=None, n_boot=2000, seed=0, pr=None) -> dict: """One system alone (no Laya rows): value and a 95% case-cluster bootstrap CI (same resampling as :func:`paired`).""" ok = sorted([r for r in rows if r["status"] == "ok"], key=lambda r: r["id"]) base = {"n": len(ok), "unscored": len(rows) - len(ok)} if not ok: return base p = [pr[r["id"]] for r in ok] if pr is not None else per_row(ok, temps) A = _arrays(p) strata = np.array([strata_fn(r) for r in ok]) if strata_fn else None PA = _split(A, strata) value = _macro(PA, np.ones(len(ok)), stat) clusters: dict = {} cl = np.array([clusters.setdefault(r["group_id"], len(clusters)) for r in ok]) by_st: dict = {} for r, c in zip(ok, cl): by_st.setdefault(strata_fn(r) if strata_fn else "_", set()).add(c) by_st = {k: sorted(v) for k, v in by_st.items()} rng = np.random.default_rng(seed) vals = [] if strata_fn and len(by_st) > 1 and all(len(cs) == 1 for cs in by_st.values()): vals = list(_strata_level_boot(PA, None, stat, n_boot, rng)) # PB None: values, not differences for _ in range(0 if vals else n_boot): counts = np.zeros(len(clusters)) for cs in by_st.values(): np.add.at(counts, np.asarray(cs)[rng.integers(0, len(cs), len(cs))], 1) vals.append(_macro(PA, counts[cl], stat)) vals = np.asarray(vals, float) vals = vals[~np.isnan(vals)] return {**base, "value": value, "ci95": [float(np.quantile(vals, 0.025)), float(np.quantile(vals, 0.975))] if len(vals) else None} # ------------------------------------------------------------------------------ report def _load_dir(d: Path) -> dict[str, list[dict]]: return {p.stem: read_jsonl(p) for p in sorted(d.glob("*.jsonl"))} def _load_dirs(dirs) -> dict[str, list[dict]]: """Several eval.cli output dirs (e.g. the pod's ``test`` and the Mac's ``test.mac``) -> one suite map. A suite present in two dirs is an error: each sealed suite runs exactly once (R7).""" out: dict[str, list[dict]] = {} for d in [Path(x) for x in (dirs if isinstance(dirs, (list, tuple)) else [dirs])]: for k, v in _load_dir(d).items(): if k in out: raise ValueError(f"suite {k} appears in more than one --ours dir ({d})") out[k] = v return out def _best(vals: dict, higher_better: bool): vals = {w: v for w, v in vals.items() if v is not None and not (isinstance(v, float) and math.isnan(v))} if not vals: return None return max(vals, key=vals.get) if higher_better else min(vals, key=vals.get) def _metric_entry(m: Metric, ours: dict, temps, laya: dict, n_boot: int, pr_of) -> dict: o = [r for r in ours.get(m.suite, []) if m.select(r)] po, pl_ = protocol(m.key) entry = {"label": m.label, "stat": m.stat, "higher_better": m.higher_better, "published_laya_best": m.published_best, "note": m.note, "run": m.run, "protocol_ours": po, "protocol_laya": pl_, "laya": {}} if not o: entry["status"] = "ours missing" + (" (no --ours-heldout given)" if m.run == "heldout" and not ours else "") for w, files in laya.items(): lrows = [r for r in files.get(m.suite, []) if m.select(r)] if not lrows: continue tl = shipped_temperature_fn(w) if not o: if m.stat == "flip": entry["laya"][w] = {"value": flip_rate(lrows)["flip_rate"]} else: pl = pr_of(w, m.suite, files[m.suite], tl) entry["laya"][w] = {"value": paired(lrows, lrows, m.stat, tl, tl, m.strata, n_boot=1, pra=pl, prb=pl)["a"]} continue if m.stat == "flip": entry["laya"][w] = paired_flip(o, lrows, n_boot) else: entry["laya"][w] = paired(o, lrows, m.stat, temps, tl, m.strata, n_boot, pra=pr_of(("ours", m.run), m.suite, ours[m.suite], temps), prb=pr_of(w, m.suite, files[m.suite], tl)) entry["laya"][w]["value"] = entry["laya"][w].get("b") ref_rows = o or next((([r for r in f.get(m.suite, []) if m.select(r)]) for f in laya.values() if any(m.select(r) for r in f.get(m.suite, []))), []) # only meaningful when every row asks the same question over the same options if m.stat == "accuracy" and ref_rows and m.strata is None and \ len({(r["qtype"], tuple(sorted(r["names"]))) for r in ref_rows}) == 1: gold = Counter(r["valid"][0] for r in ref_rows) entry["constant_label_accuracy"] = max(gold.values()) / len(ref_rows) vals = {w: v.get("value") for w, v in entry["laya"].items()} best = _best(vals, m.higher_better) if best is not None: entry["laya_best"] = {"checkpoint": best, "value": vals[best]} if o: cmp = entry["laya"][best] entry["ours_value"] = cmp.get("a") lo, hi = (cmp.get("ci95") or [float("nan")] * 2) sign = 1 if m.higher_better else -1 entry["beats_best"] = bool(sign * cmp["diff"] > 0) entry["beats_best_ci"] = bool((sign * lo > 0) if sign > 0 else (sign * hi > 0)) elif o: # ours only: value with its own CI if m.stat == "flip": entry["ours_value"] = flip_rate(o)["flip_rate"] else: s1 = single(o, m.stat, temps, m.strata, n_boot, pr=pr_of(("ours", m.run), m.suite, ours[m.suite], temps)) entry["ours_value"], entry["ours_ci95"] = s1.get("value"), s1.get("ci95") entry["status"] = "ours only (no Laya predictions for this suite)" return entry # ------------------------------------------------------------------------------ long grid def _boot_mean(x: np.ndarray, n_boot: int, rng) -> list[float] | None: if len(x) == 0: return None idx = rng.integers(0, len(x), (n_boot, len(x))) m = x[idx].mean(1) return [float(np.quantile(m, 0.025)), float(np.quantile(m, 0.975))] LONG_GRID_FROM_PLUS = ("long_grid rows of the long_grid_plus predictions (rows without meta.amendment = the " "6,720 long_grid rows, copied unchanged)") def _long_grid_rows(files: dict[str, list[dict]]) -> list[dict] | None: """long_grid predictions of one system; when only long_grid_plus was scored, its long_grid subset (identical rows, so the preregistered claim is computed on exactly the preregistered items).""" if files.get("long_grid"): return files["long_grid"] return long_grid_subset(files["long_grid_plus"]) if files.get("long_grid_plus") else None def long_grid_section(ours_rows: list[dict] | None, laya_rows: dict[str, list[dict]], temps, n_boot: int = 2000, seed: int = 0) -> dict: """Controlled long-context accuracy (aggregate.long_control_analysis) for ours and every Laya checkpoint that has long_grid predictions, with item-bootstrap CIs and paired differences on common items. Rows: overall, per length bin, per item group (noul_gold_false / noul_gold_true / choice / score), per language. An item enters a pairing only when both systems scored its real row and the same controls.""" from .aggregate import long_control_analysis, long_item_outcomes systems = {} if ours_rows: systems["ours"] = (ours_rows, temps) for w, rows in laya_rows.items(): if rows: systems[w] = (rows, shipped_temperature_fn(w)) if not systems: return {"status": "no long_grid predictions"} rng = np.random.default_rng(seed) out = {"systems": {}, "rows": {}} outcomes = {} for name, (rows, t) in systems.items(): a = long_control_analysis(rows, t) outcomes[name] = {o["pair_id"]: o for o in long_item_outcomes(rows, t)} out["systems"][name] = {k: a.get(k) for k in ("by_length", "controlled_item_accuracy", "credited_accuracy", "controlled_item_accuracy_by_group", "controls_pooled_by_length", "gap_4k_minus_8k", "claim_8k_gap_ok", "claim_8k_controls_ok", "claim_8k_ok", "controlled_item_rule", "claim_25k", "claim_25k_ok", "verified_length_bin")} out["systems"][name]["n_items"] = len(outcomes[name]) out["systems"][name]["unscored_rows"] = sum(r["status"] != "ok" for r in rows) ref = outcomes.get("ours") or next(iter(outcomes.values())) slices = [("overall", lambda o: True)] slices += [(f"length {L}", (lambda o, L=L: o["length_bin"] == L)) for L in sorted({o["length_bin"] for o in ref.values()}, key=lambda x: x or 0)] slices += [(f"group {g}", (lambda o, g=g: o["group"] == g)) for g in sorted({o["group"] for o in ref.values()})] slices += [(f"lang {lg}", (lambda o, lg=lg: o["lang"] == lg)) for lg in sorted({str(o["lang"]) for o in ref.values()})] for sname, sel in slices: row = {} for name, oc in outcomes.items(): its = [o for o in oc.values() if sel(o)] x = np.array([o["controlled"] for o in its]) row[name] = {"n": len(its), "controlled": float(x.mean()) if len(x) else None, "raw_accuracy": float(np.mean([o["correct"] for o in its])) if its else None, "controlled_ci95": _boot_mean(x, n_boot, rng)} if "ours" in outcomes: for w in [k for k in outcomes if k != "ours"]: common = [k for k, o in outcomes["ours"].items() if sel(o) and k in outcomes[w] and outcomes[w][k]["controls"] == o["controls"]] if not common: row[w]["paired"] = {"n_paired": 0} continue xa = np.array([outcomes["ours"][k]["controlled"] for k in common]) xb = np.array([outcomes[w][k]["controlled"] for k in common]) idx = rng.integers(0, len(common), (n_boot, len(common))) d = xa[idx].mean(1) - xb[idx].mean(1) row[w]["paired"] = {"n_paired": len(common), "a": float(xa.mean()), "b": float(xb.mean()), "diff": float(xa.mean() - xb.mean()), "ci95": [float(np.quantile(d, 0.025)), float(np.quantile(d, 0.975))]} pv = {w: row[w]["paired"]["b"] for w in row if w != "ours" and row[w].get("paired", {}).get("n_paired")} best = _best(pv, True) if best is not None: p = row[best]["paired"] row["laya_best"] = {"checkpoint": best, "value": p["b"], "n_paired": p["n_paired"], "diff": p["diff"], "ci95": p["ci95"], "beats_best": p["diff"] > 0, "beats_best_ci": p["ci95"][0] > 0} out["rows"][sname] = row return out # ------------------------------------------------------------------------------ latency def latency_section(lat: dict, ours_key: str | None = None, n_boot: int = 2000, seed: int = 0, source: str = "") -> dict: """``macjev.export.latency`` result (latency.json) -> per cell (tokens x questions) p50 of ours vs each Laya system, ratio ours/Laya with a bootstrap CI of the ratio of medians (from ``raw_ms``) and the plan 1.1 target (single question under 1K tokens: within 1.5x of Laya; 1K+ tokens or several questions: faster).""" res = lat.get("results") or {} laya_keys = [k for k in res if k.startswith("laya")] if ours_key is None: ours_key = next((k for k in ("engine-default", "llamacpp-f16") if k in res), next((k for k in res if k not in laya_keys), None)) out = {"source": source, "ours_system": ours_key, "laya_systems": laya_keys, "machine": (lat.get("system_before") or {}).get("chip"), "load_avg_before": (lat.get("system_before") or {}).get("load_avg"), "cells": {}} if ours_key is None or ours_key not in res: out["status"] = "ours system missing" return out rng = np.random.default_rng(seed) cells = [c for c in res[ours_key] if not c.startswith("_")] for c in cells: o = res[ours_key][c] tok, q = (int(x) for x in c.split("x")) target = "within 1.5x of Laya" if (q == 1 and tok < 1024) else "faster than Laya" e = {"tokens": tok, "questions": q, "target": target, "ours_p50_ms": o.get("p50_ms"), "ours_status": o.get("status"), "nonfinite_outputs": o.get("nonfinite_outputs"), "laya": {}} for lk in laya_keys: lc = res[lk].get(c) or {} if lc.get("status") != "ok": e["laya"][lk] = {"status": lc.get("status", "missing"), "note": "Laya cannot run this input" if lc.get("status") == "unsupported" else ""} continue le = {"status": "ok", "p50_ms": lc["p50_ms"]} if o.get("status") == "ok" and o.get("p50_ms"): le["ratio"] = o["p50_ms"] / lc["p50_ms"] ra, rb = np.asarray(o.get("raw_ms") or [], float), np.asarray(lc.get("raw_ms") or [], float) if len(ra) >= 3 and len(rb) >= 3: ia = rng.integers(0, len(ra), (n_boot, len(ra))) ib = rng.integers(0, len(rb), (n_boot, len(rb))) r = np.median(ra[ia], 1) / np.median(rb[ib], 1) le["ratio_ci95"] = [float(np.quantile(r, 0.025)), float(np.quantile(r, 0.975))] limit = 1.5 if target.startswith("within") else 1.0 le["meets_target"] = le["ratio"] <= limit if limit > 1 else le["ratio"] < 1.0 ci = le.get("ratio_ci95") le["meets_target_ci"] = bool(ci and (ci[1] <= limit if limit > 1 else ci[1] < 1.0)) e["laya"][lk] = le if not laya_keys or all(v.get("status") == "unsupported" for v in e["laya"].values()): e["only_ours_supports"] = o.get("status") == "ok" and bool(laya_keys) out["cells"][c] = e return out def build_report(ours_dir, temps: dict | None, laya_dir: Path = LB.OUT, n_boot: int = 2000, ours_name: str = "ours", heldout_dir=None, temps_heldout: dict | None = None, latency: dict | None = None, latency_ours: str | None = None, latency_source: str = "") -> dict: """``ours_dir`` / ``heldout_dir``: one eval.cli output dir or a list of them (pod ``test`` + Mac ``test.mac``). ``heldout_dir``: the seed1 ablation model's predictions (second protocol for Emotion / SST-5).""" ours = _load_dirs(ours_dir) heldout = _load_dirs(heldout_dir) if heldout_dir else {} laya = {w: _load_dir(laya_dir / w) for w in LB.WHICH if (laya_dir / w).exists()} cache: dict = {} def pr_of(who, suite, rows, temps_): if (who, suite) not in cache: cache[(who, suite)] = {d["id"]: d for d in per_row(rows, temps_)} return cache[(who, suite)] rep = {"ours": ours_name, "ours_dir": [str(x) for x in (ours_dir if isinstance(ours_dir, (list, tuple)) else [ours_dir])], "heldout_dir": [str(x) for x in (heldout_dir if isinstance(heldout_dir, (list, tuple)) else [heldout_dir])] if heldout_dir else None, "temperatures": bool(temps), "temperatures_heldout": bool(temps_heldout), "n_boot": n_boot, "metrics": {}} for m in SCOREBOARD: src, t = (ours, temps) if m.run == "main" else (heldout, temps_heldout) rep["metrics"][m.key] = _metric_entry(m, src, t, laya, n_boot, pr_of) # 49-suite refit ECE (Laya's advertised calibration number), no CI from .calibration import laya_refit refit = {} if "t4" in ours and all(r["status"] == "ok" for r in ours["t4"]): refit["ours"] = laya_refit(ours["t4"])["mean_ece_refit"] for w, files in laya.items(): if "t4" in files: refit[w] = laya_refit(files["t4"], checkpoint_config(w))["mean_ece_refit"] po, pl_ = protocol("t4.") entry = {"label": "49-suite macro ECE after Laya's half/half refit", "higher_better": False, "published_laya_best": 0.0815, "values": refit, "run": "main", "protocol_ours": po, "protocol_laya": pl_, "note": "point estimates only: a CI would refit 49 x buckets temperatures per replicate"} lb = _best({k: v for k, v in refit.items() if k != "ours"}, False) if lb is not None: entry["laya_best"] = {"checkpoint": lb, "value": refit[lb]} if "ours" in refit: entry["ours_value"] = refit["ours"] entry["beats_best"] = bool(refit["ours"] < refit[lb]) entry["beats_best_ci"] = None rep["metrics"]["t4.refit_ece_49"] = entry # long-context grid (controlled accuracy) and latency rep["long_grid"] = long_grid_section(_long_grid_rows(ours), {w: _long_grid_rows(f) for w, f in laya.items()}, temps, n_boot) if "long_grid" not in ours and ours.get("long_grid_plus"): rep["long_grid"]["rows_source"] = LONG_GRID_FROM_PLUS rep["long_grid_plus"] = long_grid_section(ours.get("long_grid_plus"), {w: f.get("long_grid_plus") for w, f in laya.items()}, temps, n_boot) if "rows" not in rep["long_grid_plus"]: rep["long_grid_plus"]["status"] = "no long_grid_plus predictions" rep["long_grid_plus"]["amendment"] = GRID_PLUS_AMENDMENT_LABEL rep["latency"] = latency_section(latency, latency_ours, n_boot, source=latency_source) if latency else \ {"status": "no latency.json given (--latency)"} # context: rows each scorer could not score, per suite file rep["unsupported"] = {"ours": {k: sum(r["status"] != "ok" for r in v) for k, v in ours.items()}, **({"ours_heldout": {k: sum(r["status"] != "ok" for r in v) for k, v in heldout.items()}} if heldout else {}), **{w: {k: sum(r["status"] != "ok" for r in v) for k, v in f.items()} for w, f in laya.items()}} return rep # ------------------------------------------------------------------------------ rendering (en / zh) TEXT = { "en": {"title": "Scoreboard: {ours} vs Laya (paired, identical rows)", "cols": ["metric", "protocol: ours / Laya", "ours", "laya english", "laya typed", "laya multilingual", "best Laya", "ours - best (95% CI)", "beats best", "constant-label acc."], "yes_ci": "yes (CI)", "yes": "yes", "no": "no", "missing": "missing", "only": "ours only", "two": "## Two protocols (Emotion, SST-5): in-domain seed0 vs held-out seed1 ablation", "two_cols": ["metric", "best Laya (held-out)", "ours seed0 (in-domain)", "ours seed1 (held-out)", "held-out: ours - best (95% CI)", "beats best (held-out, the comparable one)"], "long": "## Long-context grid: controlled item accuracy (real row correct AND controls pass)", "long_cols": ["slice", "ours n", "ours raw acc.", "ours controlled (95% CI)", "best Laya controlled " "(paired n)", "ours - best (95% CI)", "beats best"], "long_claim": "8K claim (plan 2): 4K-8K gap {gap} (ok: {gok}); pooled controls at chance: {cok}; " "claim_8k_ok: {ok}", "long_claim_25k": "25K claim (preregistered 2026-09-24): 24K controlled {a24} vs 2K-4K {ref} (gap {gap}, " "|gap| <= 0.05: {aok}); every depth decile within 0.10: {bok}; controls at chance in " "every bin: {cok}; claim_25k_ok: {ok}; verified length bin: {vl}", "long_plus": "## Long-context grid, amended (long_grid_plus; " + GRID_PLUS_AMENDMENT_LABEL + ")", "long_claim_25k_plus": "25K claim (" + GRID_PLUS_AMENDMENT_LABEL + "; long_grid_plus, {n24} 24K items): 24K " "controlled {a24} vs 2K-4K {ref} (gap {gap}, |gap| <= 0.05: {aok}); every depth " "decile within 0.10: {bok}; controls at chance in every bin: {cok}; claim_25k_ok: " "{ok}; verified length bin: {vl}. The preregistered long_grid claim above stays " "reported.", "lat": "## Latency (warm p50, end-to-end; same inputs; {src})", "lat_cols": ["tokens x questions", "ours p50 ms", "Laya p50 ms", "ours / Laya (95% CI)", "plan target", "met"], "unsup": "Laya unsupported", "only_ours": "only ours", "foot": ( "Laya values use each checkpoint's shipped temperatures as in the published runs; ours use the " "supplied deployment temperatures. CIs: case-cluster bootstrap within suites (ours-only rows: " "one-sample CI of our value). 'constant-label acc.' is the accuracy of always answering the most " "frequent gold label: an accuracy at or below it is not evidence of skill (e.g. guardrails: 309/400 " "rows are 'false'). Protocol: whether the metric's source dataset (or language) was in the " "training data of our model / of Laya; only rows with the same protocol on both sides are " "like-for-like.")}, "zh": {"title": "对比总表:{ours} vs Laya(同一批样本行,配对比较)", "cols": ["指标", "口径:我们 / Laya", "我们", "Laya 英文", "Laya typed", "Laya 多语", "Laya 最好", "我们 − 最好(95% CI)", "超过最好", "常数答案准确率"], "yes_ci": "是(CI 显著)", "yes": "是(点估计)", "no": "否", "missing": "缺", "only": "仅我们", "two": "## 两种口径(Emotion、SST-5):seed0 域内 vs seed1 留出消融", "two_cols": ["指标", "Laya 最好(留出)", "我们 seed0(域内)", "我们 seed1(留出)", "留出:我们 − 最好(95% CI)", "超过最好(留出,可比的一栏)"], "long": "## 长输入网格:受控题目准确率(真实题答对且所有对照都通过)", "long_cols": ["切片", "我们题数", "我们原始准确率", "我们受控准确率(95% CI)", "Laya 最好受控(配对题数)", "我们 − 最好(95% CI)", "超过最好"], "long_claim": "8K 宣称(§2):4K 与 8K 段差距 {gap}(达标:{gok});合并对照在随机水平:{cok};" "claim_8k_ok:{ok}", "long_claim_25k": "25K 宣称(2026-09-24 预注册):24K 段受控准确率 {a24},2K–4K 段 {ref}(差 {gap}," "|差| ≤ 5pp:{aok});每个证据深度十分位都在 10pp 内:{bok};所有长度段对照在随机水平:{cok};" "claim_25k_ok:{ok};已验证长度段:{vl}", "long_plus": "## 长输入网格(修订版 long_grid_plus;数据前修订 2026-09-24:24K 每个十分位 +96 题,阈值不变)", "long_claim_25k_plus": "25K 宣称(修订版:2026-09-24 数据前修订,24K 每个十分位 +96 题,阈值不变;" "long_grid_plus,24K 段 {n24} 题):24K 段受控准确率 {a24},2K–4K 段 {ref}(差 {gap}," "|差| ≤ 5pp:{aok});每个证据深度十分位都在 10pp 内:{bok};所有长度段对照在随机水平:" "{cok};claim_25k_ok:{ok};已验证长度段:{vl}。上面的预注册版照常报告。", "lat": "## 延迟(热启动 p50,端到端,同样输入;{src})", "lat_cols": ["token 数 × 题数", "我们 p50 ms", "Laya p50 ms", "我们 / Laya(95% CI)", "计划目标", "达标"], "unsup": "Laya 不支持", "only_ours": "只有我们能跑", "foot": ( "Laya 用各检查点自带的温度(与公布结果一致);我们用部署温度。CI:套件内按案例簇 bootstrap" "(只有我们的行:我们自身数值的单样本 CI)。“常数答案准确率”= 永远回答最常见金标的准确率," "不高于它就不能说明有能力(例如越狱防护 400 行里 309 行是“否”)。口径:该指标的数据源(或语种)" "是否进过我们 / Laya 的训练数据;只有两边口径相同的行才是同口径比较。")}, } ZH_PROTO = {"in-domain": "域内", "held-out": "留出", "near-domain": "近域", "mixed": "混合", "not run": "未跑", "not applicable": "不适用"} # Full Chinese wording of every PROTOCOLS string (the report is read in Chinese); unknown strings fall back to # the word-level ZH_PROTO replacement below. tests/macjev/eval/test_report_readiness.py checks the coverage. PROTOCOLS_ZH = { IN: "域内", HO: "留出", "in-domain (typed ckpt) / held-out (english, multilingual)": "域内(typed 检查点);留出(英文、多语检查点)", "in-domain (training mix)": "域内(训练集进过训练)", "in-domain (seed0 trains DAIR Emotion) - not comparable with Laya": "域内(seed0 训练了 DAIR Emotion),不能和 Laya 直接比", "in-domain (seed0 trains SST-5) - not comparable with Laya": "域内(seed0 训练了 SST-5),不能和 Laya 直接比", "held-out (banking77 never trained; CLINC150/HWU64 intents are)": "留出(banking77 从不训练;训练过 CLINC150/HWU64 意图)", "mixed: 14 trained + 37 never-trained languages": "混合:14 个训练过的语种 + 37 个从不训练的语种", "in-domain (MASSIVE train, 14 locales)": "域内(MASSIVE 训练集,14 个语种)", "held-out (37 languages never trained)": "留出(37 个语种从不训练)", "near-domain (MNLI + teacher-translated NLI; XNLI itself never trained)": "近域(训练了 MNLI 和老师翻译的 NLI;XNLI 本身从不训练)", "mixed (49 suites)": "混合(49 个套件)", "in-domain (enron_spam train split; eval = test split)": "域内(enron_spam 训练切分;评测用测试切分)", "in-domain (same dataset, evaluated rows excluded)": "域内(同一数据集,评测行已剔除)", "held-out source (other permissive jailbreak sets + teacher)": "留出来源(其他许可宽松的越狱数据 + 老师合成)", "held-out source (civil_comments + teacher; toxic-chat eval-only)": "留出来源(civil_comments + 老师合成;toxic-chat 只做评测)", "held-out source (SQuAD v2 pairs; MS MARCO eval-only)": "留出来源(SQuAD v2 段落对;MS MARCO 只做评测)", "near-domain (teacher-written tickets; the NC ticket set never trained)": "近域(老师写的工单;NC 许可的工单集从不训练)", "near-domain (teacher-written; gsm8k/mbpp/AG rows eval-only)": "近域(老师合成;gsm8k/mbpp/AG 行只做评测)", "held-out (banking77 never trained)": "留出(banking77 从不训练)", "in-domain (seed0) - not comparable with Laya": "域内(seed0),不能和 Laya 直接比", "near-domain (MNLI)": "近域(MNLI)", "held-out workflows (never trained)": "留出工作流(从不训练)", "not run": "未跑", "in-domain task (held-out rule groups)": "域内任务(留出规则组)", "not applicable": "不适用", "in-domain task (held-out test apps)": "域内任务(留出测试应用)", "in-domain task (own grid, never trained)": "域内任务(自建网格,从不训练)", "budget <= 4K (8K/16K unsupported)": "输入预算 ≤4K(8K/16K 不支持)", HELDOUT_PROTOCOL: "留出(seed1 消融:DAIR Emotion 和 SST-5 从不训练)", } def _zh_proto(s: str) -> str: if s in PROTOCOLS_ZH: return PROTOCOLS_ZH[s] for k, v in ZH_PROTO.items(): s = s.replace(k, v) return s.replace("not comparable with Laya", "不能和 Laya 直接比").replace("never trained", "从不训练") def _f(x, nd=3): return "—" if x is None or (isinstance(x, float) and math.isnan(x)) else f"{x:.{nd}f}" def _beats(e, T): if "beats_best" not in e: return "" if e.get("beats_best_ci"): return T["yes_ci"] return T["yes"] if e["beats_best"] else T["no"] def _nd(e) -> int: return 0 if e.get("stat") == "strata_above_3x_random" else 3 def _diff_ci(e): best = e.get("laya_best", {}) if not best or e.get("ours_value") is None or "laya" not in e: return "" c = e["laya"][best["checkpoint"]] nd = _nd(e) return f"{c['diff']:+.{nd}f} [{c['ci95'][0]:+.{nd}f}, {c['ci95'][1]:+.{nd}f}]" if c.get("ci95") else \ f"{c['diff']:+.{nd}f}" def table_main(rep: dict, lang: str = "en") -> list[str]: T = TEXT[lang] lines = ["| " + " | ".join(T["cols"]) + " |", "|" + "---|" * len(T["cols"])] for key, e in rep["metrics"].items(): po, pl_ = e.get("protocol_ours", "?"), e.get("protocol_laya", "?") if lang == "zh": po, pl_ = _zh_proto(po), _zh_proto(pl_) proto = f"{po} / {pl_}" if "values" in e: v = e["values"] best = e.get("laya_best", {}) lines.append(f"| {e['label']} | {proto} | {_f(v.get('ours'))} | {_f(v.get('english'))} | " f"{_f(v.get('typed'))} | {_f(v.get('multilingual'))} | {_f(best.get('value'))} " f"({best.get('checkpoint', '')}) | " f"{format(v['ours'] - best['value'], '+.3f') if best and 'ours' in v else '—'} " f"(no CI) | {_beats(e, T)} | — |") continue nd = _nd(e) lv = {w: _f(e["laya"].get(w, {}).get("value"), nd) for w in ("english", "typed", "multilingual")} best = e.get("laya_best", {}) ours = _f(e.get("ours_value"), nd) if e.get("ours_ci95"): ours += f" [{e['ours_ci95'][0]:.{nd}f}, {e['ours_ci95'][1]:.{nd}f}] ({T['only']})" elif e.get("ours_value") is None: ours = T["missing"] bestc = f"{_f(best.get('value'), nd)} ({best.get('checkpoint', '')})" if best else "—" lines.append(f"| {e['label']} | {proto} | {ours} | {lv['english']} | {lv['typed']} | " f"{lv['multilingual']} | {bestc} | {_diff_ci(e)} | {_beats(e, T)} " f"| {_f(e.get('constant_label_accuracy'))} |") return lines def table_protocols(rep: dict, lang: str = "en") -> list[str]: T = TEXT[lang] lines = ["| " + " | ".join(T["two_cols"]) + " |", "|" + "---|" * len(T["two_cols"])] for k in HELDOUT_KEYS: a, h = rep["metrics"].get(k, {}), rep["metrics"].get(k + "@heldout", {}) best = h.get("laya_best") or a.get("laya_best") or {} lines.append(f"| {a.get('label', k)} | {_f(best.get('value'))} ({best.get('checkpoint', '')}) | " f"{_f(a.get('ours_value'))} | {_f(h.get('ours_value')) if h.get('ours_value') is not None else T['missing']} | " f"{_diff_ci(h)} | {_beats(h, T)} |") return lines ZH_SLICE = {"overall": "全部", "length": "长度", "group": "题组", "lang": "语言"} ZH_TARGET = {"within 1.5x of Laya": "在 Laya 的 1.5 倍以内", "faster than Laya": "比 Laya 快"} def _slice_name(sname: str, lang: str) -> str: if lang != "zh": return sname head, _, tail = sname.partition(" ") return (ZH_SLICE.get(head, head) + (" " + tail if tail else "")) def _target(t: str, lang: str) -> str: return ZH_TARGET.get(t, t) if lang == "zh" else t def table_long(rep: dict, lang: str = "en", key: str = "long_grid") -> list[str]: """``key`` = long_grid (preregistered claim) or long_grid_plus (amended claim, its own label).""" T = TEXT[lang] lg = rep.get(key) or {} if "rows" not in lg: return [f"({lg.get('status', f'no {key} section')})"] lines = ["| " + " | ".join(T["long_cols"]) + " |", "|" + "---|" * len(T["long_cols"])] for sname, row in lg["rows"].items(): o = row.get("ours") or {} ci = o.get("controlled_ci95") b = row.get("laya_best") lines.append(f"| {_slice_name(sname, lang)} | {o.get('n', '—')} | {_f(o.get('raw_accuracy'))} | {_f(o.get('controlled'))}" f"{f' [{ci[0]:.3f}, {ci[1]:.3f}]' if ci else ''} | " + (f"{_f(b['value'])} ({b['checkpoint']}, {b['n_paired']}) | {b['diff']:+.3f} " f"[{b['ci95'][0]:+.3f}, {b['ci95'][1]:+.3f}] | " f"{T['yes_ci'] if b['beats_best_ci'] else T['yes'] if b['beats_best'] else T['no']} |" if b else f"{T['unsup'] if o else '—'} | | |")) s = (lg.get("systems") or {}).get("ours") or {} if s: b_ = _zh_bool if lang == "zh" else str lines += ["", T["long_claim"].format(gap=_f(s.get("gap_4k_minus_8k")), gok=b_(s.get("claim_8k_gap_ok")), cok=b_(s.get("claim_8k_controls_ok")), ok=b_(s.get("claim_8k_ok")))] c25 = s.get("claim_25k") or {} if c25: top = (c25.get("bins") or {}).get("24576") or {} tpl = T["long_claim_25k_plus"] if key == "long_grid_plus" else T["long_claim_25k"] lines += [tpl.format(a24=_f(top.get("controlled")), ref=_f(c25.get("reference_controlled")), gap=_f(top.get("gap_vs_2k_4k")), aok=b_(c25.get("a_gap_ok")), bok=b_(c25.get("b_deciles_ok")), cok=b_(c25.get("c_controls_ok")), ok=b_(c25.get("ok")), vl=c25.get("verified_length_bin"), n24=top.get("items"))] if lg.get("rows_source"): lines += ["", f"(rows: {lg['rows_source']})"] return lines def table_latency(rep: dict, lang: str = "en") -> list[str]: T = TEXT[lang] la = rep.get("latency") or {} if "cells" not in la: return [f"({la.get('status', 'no latency section')})"] lines = [T["lat"].format(src=f"{la.get('machine')}, ours = {la.get('ours_system')}, source {la.get('source')}"), "", "| " + " | ".join(T["lat_cols"]) + " |", "|" + "---|" * len(T["lat_cols"])] for c, e in la["cells"].items(): for lk, le in (e["laya"] or {"—": {"status": "missing"}}).items(): if le.get("status") != "ok": lines.append(f"| {c} | {_f(e.get('ours_p50_ms'), 0)} | {T['unsup'] if le.get('status') == 'unsupported' else '—'} " f"| — | {_target(e['target'], lang)} | {T['only_ours'] if e.get('only_ours_supports') else '—'} |") continue ci = le.get("ratio_ci95") met = "—" if "meets_target" not in le else (T["yes_ci"] if le["meets_target_ci"] else T["yes"] if le["meets_target"] else T["no"]) lines.append(f"| {c} | {_f(e.get('ours_p50_ms'), 0)} | {_f(le['p50_ms'], 0)} | {_f(le.get('ratio'), 2)}" f"{f' [{ci[0]:.2f}, {ci[1]:.2f}]' if ci else ''} | {_target(e['target'], lang)} | {met} |") return lines def to_markdown(rep: dict, lang: str = "en") -> str: T = TEXT[lang] lines = [f"# {T['title'].format(ours=rep['ours'])}", ""] + table_main(rep, lang) lines += ["", T["foot"], "", T["two"], ""] + table_protocols(rep, lang) lines += ["", T["long"], ""] + table_long(rep, lang) lines += ["", T["long_plus"], ""] + table_long(rep, lang, "long_grid_plus") lines += [""] + table_latency(rep, lang) return "\n".join(lines) + "\n" # ------------------------------------------------------------------------------ template filling def _metric_field(rep: dict, key: str, field: str): e = rep["metrics"].get(key) if e is None: return None best = e.get("laya_best") or {} nd = _nd(e) if field == "ours": return _f(e.get("ours_value"), nd) if field == "ours_ci": # one-sample CI of an ours-only row ci = e.get("ours_ci95") return f"[{ci[0]:.{nd}f}, {ci[1]:.{nd}f}]" if ci else None if field == "best": return _f(best.get("value"), nd) if field == "best_ckpt": return best.get("checkpoint") if field in ("diff", "ci"): c = (e.get("laya") or {}).get(best.get("checkpoint"), {}) if field == "diff": return f"{c['diff']:+.{nd}f}" if "diff" in c else None return f"[{c['ci95'][0]:+.{nd}f}, {c['ci95'][1]:+.{nd}f}]" if c.get("ci95") else None if field == "beats": return _beats(e, TEXT["zh"]) or None if field == "published": return _f(e.get("published_laya_best")) if field == "proto_ours": return _zh_proto(e.get("protocol_ours", "")) if field == "proto_laya": return _zh_proto(e.get("protocol_laya", "")) return None def _zh_bool(v) -> str: return {True: "是", False: "否"}.get(v, str(v)) if isinstance(v, bool) else str(v) def fill_template(text: str, rep: dict, missing: str = "(缺)") -> str: """Replace ``{{table:main|protocols|long|latency}}``, ``{{m:<metric key>:<ours|best|best_ckpt|diff|ci|beats| published|proto_ours|proto_laya>}}``, ``{{long:<gap|claim_8k_ok|claim_8k_gap_ok|claim_8k_controls_ok|claim_25k_ok|verified_length_bin|gap_25k>}}`` (``{{long_plus:...}}``: the same fields of the amended long_grid_plus claim; ``{{table:long_plus}}``) and ``{{meta:<ours|ours_dir|heldout_dir|n_boot>}}``; field ``ours_ci`` = one-sample CI of an ours-only row. Other ``{{...}}`` (e.g. ``{{填写:...}}``) are left for a human.""" import re def rep_fn(mo): ns, _, rest = mo.group(1).partition(":") v = None if ns == "table": fn = {"main": table_main, "protocols": table_protocols, "long": table_long, "latency": table_latency, "long_plus": lambda r, lg: table_long(r, lg, "long_grid_plus")}.get(rest) v = "\n".join(fn(rep, "zh")) if fn else None if v and rest == "latency": # the template has its own section heading v = v.replace("## ", "", 1) elif ns == "m": key, _, field = rest.rpartition(":") v = _metric_field(rep, key, field) elif ns in ("long", "long_plus"): # long_plus: the amended long_grid_plus claim s = ((rep.get("long_grid" if ns == "long" else "long_grid_plus") or {}).get("systems") or {}).get("ours") or {} if rest == "gap": v = _f(s.get("gap_4k_minus_8k")) elif rest == "gap_25k": v = _f((((s.get("claim_25k") or {}).get("bins") or {}).get("24576") or {}).get("gap_vs_2k_4k")) else: v = s.get(rest) v = None if v is None else _zh_bool(v) elif ns == "meta": v = rep.get(rest) v = None if v is None else "、".join(f"`{x}`" for x in v) if isinstance(v, list) else str(v) else: return mo.group(0) return missing if v in (None, "—", "") else str(v) return re.sub(r"\{\{([a-z_]+:[^{}]*)\}\}", rep_fn, text) def main(argv=None): ap = argparse.ArgumentParser() ap.add_argument("--ours", required=True, nargs="+", help="eval.cli output dir(s), e.g. pod test + Mac test.mac") ap.add_argument("--temperatures", default=None) ap.add_argument("--ours-heldout", nargs="+", default=None, help="seed1 ablation eval.cli output dir(s)") ap.add_argument("--temperatures-heldout", default=None) ap.add_argument("--latency", default=None, help="macjev.export.latency latency.json") ap.add_argument("--latency-ours", default=None, help="system key in latency.json (default engine-default)") ap.add_argument("--laya", default=str(LB.OUT)) ap.add_argument("--out", required=True) ap.add_argument("--n-boot", type=int, default=2000) ap.add_argument("--name", default="ours") ap.add_argument("--template", default=None, help="'zh' (macjev.eval.report_template_zh.TEMPLATE) or a template " "file to fill -> <out>/report.zh.md") a = ap.parse_args(argv) rd = lambda p: json.loads(Path(p).read_text()) if p else None # noqa: E731 rep = build_report([Path(x) for x in a.ours], rd(a.temperatures), Path(a.laya), a.n_boot, a.name, heldout_dir=[Path(x) for x in a.ours_heldout] if a.ours_heldout else None, temps_heldout=rd(a.temperatures_heldout), latency=rd(a.latency), latency_ours=a.latency_ours, latency_source=a.latency or "") out = Path(a.out) out.mkdir(parents=True, exist_ok=True) (out / "scoreboard.json").write_text(json.dumps(rep, indent=1, allow_nan=True) + "\n") (out / "scoreboard.md").write_text(to_markdown(rep, "en")) (out / "scoreboard.zh.md").write_text(to_markdown(rep, "zh")) if a.template: if a.template == "zh": from .report_template_zh import TEMPLATE else: TEMPLATE = Path(a.template).read_text() (out / "report.zh.md").write_text(fill_template(TEMPLATE, rep)) print(str(out / "scoreboard.md")) if __name__ == "__main__": main()
"""Scoreboard: our model vs the three official Laya checkpoints on identical rows.
python -m macjev.eval.report --ours <eval.cli dir> [<dir> ...] [--temperatures temperatures.json]
[--ours-heldout <seed1 dir> [...]] [--temperatures-heldout t.json]
[--latency runs/macjev/latency/<run>/latency.json] [--latency-ours engine-default]
[--laya runs/macjev/laya_baselines] --out <dir> [--n-boot 2000]
[--template zh | <template file>]
Writes scoreboard.json, scoreboard.md (English), scoreboard.zh.md and, with --template, report.zh.md.
Every row carries its protocol (in-domain / held-out, ours and Laya). Two protocols for Emotion and SST-5:
seed0 (in-domain) and the seed1 held-out ablation (--ours-heldout), the latter being the like-for-like
comparison with Laya. MASSIVE-51 is also split into our 14 trained and 37 never-trained languages.
Sections after the main table: long-context grid (controlled item accuracy, item-bootstrap CIs, paired
against any Laya long_grid predictions; the preregistered long_grid 25K claim AND the amended long_grid_plus
claim -- amended pre-data 2026-09-24: +96 items per 24K decile, thresholds unchanged -- each on its own rows) and
latency (macjev.export.latency output, ratio of medians CI).
For every metric Laya advertises (third_party/laya/BENCHMARKS.md, the T4 and CPU-sweep JSON)
the report gives our value, each Laya checkpoint's value under Laya's own protocol (shipped
temperatures as published), the best Laya value, and for every checkpoint the paired
difference (ours - laya) with a 95% case-cluster bootstrap CI (clusters = ``group_id``,
resampled within each suite so macro averages keep all suites) and, for accuracy, an exact
McNemar p-value. Only rows scored ``ok`` by both sides enter a paired comparison; the number
of rows either side could not score is reported (Laya's unsupported rows count as errors in
``accuracy_counting_unsupported``). Our model's probabilities use --temperatures when given.
Refit-ECE (49 suites) has no CI (each replicate would refit 49 x buckets temperatures).
"""
from __future__ import annotations
import argparse
import json
import math
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
import numpy as np
from . import laya_baselines as LB
from .aggregate import GRID_PLUS_AMENDMENT_LABEL, long_grid_subset, typed_long_workflow
from .laya_scorer import checkpoint_config, shipped_temperature_fn
from .metrics import ece, flip_rate, per_row
from .predictions import read_jsonl
from .stats import mcnemar
@dataclass
class Metric:
key: str
label: str
suite: str # prediction file stem
select: Callable[[dict], bool] # row filter
stat: str # accuracy | ece | nll | brier | soft_accuracy | score_mae | macro_f1 | flip
higher_better: bool
strata: Callable[[dict], str] | None = None # macro over strata (e.g. languages)
published_best: float | None = None
note: str = ""
run: str = "main" # main = seed0 predictions; heldout = seed1 ablation (--ours-heldout)
def _s(prefix):
return lambda r: str((r.get("meta") or {}).get("suite", "")).startswith(prefix)
def _eq(name):
return lambda r: (r.get("meta") or {}).get("suite") == name
def _t4(names):
names = set(names)
return lambda r: (r.get("meta") or {}).get("t4_suite") in names
XNLI_REST = ["xnli." + x for x in ("de", "fr", "es", "ru", "tr", "ar", "hi", "ur", "vi", "th", "el", "bg", "zh", "sw")]
MI_REST = ["massive_intent." + x for x in ("de", "fr", "es", "pt", "ru", "tr", "ar", "hi", "ta", "zh-CN", "ja", "ko", "sw")]
MS_REST = [x.replace("intent", "scenario") for x in MI_REST]
ALL = lambda r: True # noqa: E731
BY_T4 = lambda r: r["meta"]["t4_suite"] # noqa: E731
BY_LANG = lambda r: r["lang"] # noqa: E731
SCOREBOARD = [
Metric("typed.accuracy", "typed-decisions accuracy (2,000)", "typed_test", ALL, "accuracy", True, None, 0.766),
Metric("typed.soft_accuracy", "typed-decisions soft accuracy", "typed_test", ALL, "soft_accuracy", True, None, 0.471),
Metric("typed.brier_vs_soft", "typed-decisions Brier vs soft labels", "typed_test", ALL, "brier_soft", False, None, 0.061),
Metric("typed.score_mae", "typed-decisions score MAE", "typed_test", ALL, "score_mae", False, None, 0.242),
Metric("typed.ece", "typed-decisions ECE", "typed_test", ALL, "ece", False, None, 0.175),
*[Metric(f"typed.workflow.{wf}", f"typed-decisions accuracy, workflow {wf} (500)", "typed_test",
(lambda r, wf=wf: (r.get("meta") or {}).get("workflow") == wf), "accuracy", True, None, pub)
for wf, pub in (("agent_trace_observability", 0.730), ("customer_service", 0.764),
("invoice_processing", 0.804), ("security_incidents", 0.766))],
Metric("ag.first400", "AG News first 400 (bench_apps)", "apps", _eq("apps.jev.ag_news"), "accuracy", True, None, 0.953),
Metric("ag.first600", "AG News first 600 (T4)", "t4", _t4(["en.ag_news"]), "accuracy", True, None, 0.947),
Metric("ag.full", "AG News full test (7,600)", "ag_news_full", ALL, "accuracy", True, None, 0.929,
"plan value from round-1 Laya predictions"),
Metric("emotion.first400", "DAIR Emotion first 400 (bench_apps)", "apps", _eq("apps.jev.emotion"), "accuracy",
True, None, 0.600),
Metric("emotion.first600", "DAIR Emotion first 600 (T4)", "t4", _t4(["en.emotion"]), "accuracy", True),
Metric("emotion.full", "DAIR Emotion full test (2,000)", "emotion_full", ALL, "accuracy", True),
Metric("banking77", "banking77 first 400, 77 labels", "apps", _eq("apps.jev.banking77_full"), "accuracy", True,