File size: 7,253 Bytes
f80e81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LittleBoy gate LB-B evaluation on the holdout, from the k3pass cache (PREREG_LB_B.md).



For every holdout set it reports mean next-token NLL of

  base      Kimi K3.1-Pro (experts >= 896 masked), from the pass itself (nll.npy, base streams);

  lb        LittleBoy as released, recomputed from the cache (must equal the pass within 1e-3: consistency check);

  lb_tuned  LittleBoy with the trained layer-92 BF16 weights (layer92_trained.pt).

Acceptance (preregistered): lb_tuned vs base <= -2 % on >= 2 of the 3 domain holdout sets, and on the general

holdout (wikipedia) lb_tuned vs base <= +0.5 %. Paired per-sequence differences give a bootstrap 95 % interval.



Verdict, one of four (2026-11-20, after Gemini's audit ORD-20261120-CLAUDE-07, checked against PREREG_LB_B.md):

  STOPPED_AT_VALIDATION  the training record says the validation NLL did not improve: the holdout is not opened

                         (PREREG "If the validation NLL does not improve, the run stops there");

  INVALID                gate LB-A failed (base perplexity on the general holdout >= 15: the reference implementation is

                         wrong and nothing is concluded) or the cache is inconsistent with the pass;

  PASS / FAIL            the preregistered acceptance above.

The rule of the 20/11 plan (a block enters a release only if the interval excludes zero) is reported as

"plan_ci_rule" for information: it binds the tiers after LB-B, not LB-B, whose criteria were fixed on 19/11.



    python lb_tail_eval.py --cache DIR --trained DIR/layer92_trained.pt --out verdict.json

"""
from __future__ import annotations

import argparse
import json
import math
import os
from pathlib import Path

import numpy as np
import torch

import k3ref as K
import lb_tail_train as TT

DOMAIN_MIN = -0.02
GENERAL_MAX = 0.005
LBA_MAX_PPL = 15.0


def boot_ci(diff: np.ndarray, n: int = 2000, seed: int = 20261119) -> list:
    rng = np.random.default_rng(seed)
    means = [diff[rng.integers(0, len(diff), len(diff))].mean() for _ in range(n)]
    return [float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))]


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--cache", required=True)
    ap.add_argument("--trained", required=True)
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    rec_path = Path(a.trained).with_name("train_record.json")
    if rec_path.exists():
        tr = json.loads(rec_path.read_text())
        if tr.get("val_after") is not None and tr.get("val_before") is not None and tr["val_after"] >= tr["val_before"]:
            res = {"acceptance": {"verdict": "STOPPED_AT_VALIDATION", "PASS": False,
                                  "val_before": tr["val_before"], "val_after": tr["val_after"]},
                   "note": "validation NLL did not improve: holdout not opened (PREREG_LB_B.md)"}
            Path(a.out).write_text(json.dumps(res, indent=1))
            print(json.dumps(res))
            return 0
    dev = torch.device("cuda")
    c = K.Cfg(json.loads(Path(TT.hf_hub_download(TT.BASE, "config.json")).read_text())["text_config"])
    cache = TT.Cache(Path(a.cache))
    W0, Wf, lm_head = TT.load_tail(dev, os.environ.get("HF_TOKEN"))
    Wt = {k: v.to(dev) for k, v in torch.load(a.trained, weights_only=True).items()}
    s = json.loads((Path(a.cache) / "streams.json").read_text())
    pass_nll = np.load(Path(a.cache) / "nll.npy")
    streams = s["streams"]
    T = s["seq"]
    res = {"per_set": {}, "consistency_max_abs": 0.0}
    raw = {}             # per-token NLL of every arm, for an independent recomputation (V8 §4.2.7, NEXUS WP-G3)
    for sname in sorted({m["set"] for m in cache.meta if m["role"] == "holdout"}):
        seqs = [i for i, m in enumerate(cache.meta) if m["role"] == "holdout" and m["set"] == sname]
        per = {"lb": [], "lb_tuned": [], "base": []}
        for i in seqs:
            rows = np.arange(i * T, (i + 1) * T - 1)
            lb = TT.nll_rows(cache, rows, W0, Wf, lm_head, c, dev).numpy()
            tu = TT.nll_rows(cache, rows, Wt, Wf, lm_head, c, dev).numpy()
            raw[f"{sname}/{i}/lb"] = lb.astype(np.float32)
            raw[f"{sname}/{i}/lb_tuned"] = tu.astype(np.float32)
            if [i, "base"] in streams:
                raw[f"{sname}/{i}/base"] = np.asarray(pass_nll[streams.index([i, "base"])], dtype=np.float32)
            s_lb = streams.index([i, "littleboy"])
            res["consistency_max_abs"] = max(res["consistency_max_abs"], float(abs(lb.mean() - pass_nll[s_lb].mean())))
            per["lb"].append(lb.mean())
            per["lb_tuned"].append(tu.mean())
            if [i, "base"] in streams:
                per["base"].append(pass_nll[streams.index([i, "base"])].mean())
        r = {k: float(np.mean(v)) for k, v in per.items() if v}
        if per["base"]:
            b = np.array(per["base"])
            for k in ("lb", "lb_tuned"):
                d = (np.array(per[k]) - b) / b
                r[f"{k}_vs_base_rel"] = float(d.mean())
                r[f"{k}_vs_base_ci95"] = boot_ci(d)
        r["n_seqs"] = len(seqs)
        res["per_set"][sname] = r
    dom = {k: v for k, v in res["per_set"].items() if k != "wikipedia" and not k.startswith("general")}
    gen_keys = [k for k in sorted(res["per_set"]) if k == "wikipedia" or k.startswith("general")]
    gen_key = "wikipedia" if "wikipedia" in res["per_set"] else (gen_keys[0] if gen_keys else None)
    gen = res["per_set"].get(gen_key) if gen_key else None
    wins = sum(1 for v in dom.values() if v.get("lb_tuned_vs_base_rel", 1) <= DOMAIN_MIN)
    ci_wins = sum(1 for v in dom.values() if v.get("lb_tuned_vs_base_rel", 1) <= DOMAIN_MIN
                  and v.get("lb_tuned_vs_base_ci95", [0.0, 1.0])[1] < 0.0)
    base_ppl = math.exp(gen["base"]) if gen and "base" in gen else None
    lba_ok = base_ppl is not None and base_ppl < LBA_MAX_PPL
    consistency_ok = res["consistency_max_abs"] < 1e-3
    passed = bool(wins >= 2 and gen and gen.get("lb_tuned_vs_base_rel", 1) <= GENERAL_MAX)
    verdict = "INVALID" if not (lba_ok and consistency_ok) else ("PASS" if passed else "FAIL")
    res["acceptance"] = {
        "verdict": verdict,
        "gate_LBA_base_wiki_ppl": None if base_ppl is None else round(base_ppl, 4),
        "gate_LBA_ok": lba_ok,
        "domain_sets_meeting_-2%": f"{wins}/{len(dom)}",
        "general_set": gen_key,
        "general_rel": None if not gen else gen.get("lb_tuned_vs_base_rel"),
        "consistency_ok": consistency_ok,
        "plan_ci_rule_domain_sets_-2%_and_ci_below_0": f"{ci_wins}/{len(dom)} (informative for LB-B)",
        "PASS": verdict == "PASS"}
    np.savez_compressed(Path(a.out).with_suffix(".raw.npz"), **raw)
    res["raw_arrays"] = {"file": Path(a.out).with_suffix(".raw.npz").name, "keys": len(raw),
                         "layout": "<set>/<sequence index>/<arm>, per-token NLL in nats (arm base from the pass nll.npy)"}
    Path(a.out).write_text(json.dumps(res, indent=1))
    print(json.dumps(res["acceptance"]), json.dumps(res["per_set"], indent=1))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())