File size: 4,979 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
"""Colab GPU cell driver for LB-B2 (preregistered in 16_EVIDENCE/TRINITY/LB_B2_PREREG_2026-11-20.md): a small sweep of
the layer-92 tail training on the existing train cache, choice by a fixed validation rule (never the holdout), then ONE
evaluation of the chosen configuration on the holdout cache with the unchanged lb_tail_eval.py.

    import os; from google.colab import userdata; import huggingface_hub as h
    os.environ['HF_TOKEN'] = userdata.get('STARHUGGIN')
    exec(open(h.hf_hub_download('STAR-future/Trinity', 'tools/colab_lbb2_sweep.py', token=os.environ['HF_TOKEN'],
                                force_download=True)).read())
"""
import json
import math
import os
import subprocess
import sys
from pathlib import Path

from huggingface_hub import HfApi, hf_hub_download, snapshot_download

TOK = os.environ["HF_TOKEN"]
REPO = "STAR-future/Trinity"
CACHE = "STAR-future/Trinity-k3cache"
W = Path("/content/k3p")
W.mkdir(parents=True, exist_ok=True)
api = HfApi(token=TOK)
CONFIGS = [("C0", 2e-5, 2.0), ("C1", 1e-4, 4.0), ("C2", 1e-4, 8.0), ("C3", 3e-4, 4.0), ("C4", 3e-4, 8.0)]
GEN_MAX, H1_YES, H1_NO = 0.005, -0.015, -0.010


def up(path: Path, name: str) -> None:
    for k in range(3):
        try:
            api.upload_file(path_or_fileobj=str(path), path_in_repo=f"eval/lbb2/{name}", repo_id=REPO,
                            commit_message=f"LB-B2 {name}")
            return
        except Exception as e:  # noqa: BLE001 - a failed upload must not lose the run: retry
            print("upload retry", name, k, type(e).__name__, flush=True)


subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tiktoken"], check=True)
for f in ("k3ref.py", "k3pass.py", "lb_tail_train.py", "lb_tail_eval.py"):
    (W / f).write_bytes(Path(hf_hub_download(REPO, f"tools/{f}", token=TOK, force_download=True)).read_bytes())
for m in ("train", "holdout"):
    if not (W / f"out_{m}" / "summary.json").exists():
        snapshot_download(CACHE, repo_type="dataset", token=TOK, allow_patterns=[f"{m}/*"], local_dir=str(W / "cache_dl"))
        (W / f"out_{m}").mkdir(exist_ok=True)
        for f in (W / "cache_dl" / m).iterdir():
            f.rename(W / f"out_{m}" / f.name)
    lr_ = json.loads((W / f"out_{m}" / "summary.json").read_text()).get("layers_run")
    if lr_ != 93:
        raise SystemExit(f"cache {m} from a pass of {lr_} layers, not 93")

rows = []
for name, lr, ep in CONFIGS:
    out = W / "lbb2" / name
    out.mkdir(parents=True, exist_ok=True)
    if not (out / "train_record.json").exists():
        rc = subprocess.run([sys.executable, "-u", str(W / "lb_tail_train.py"), "--cache", str(W / "out_train"), "--out",
                             str(out), "--lr", str(lr), "--epochs", str(ep)], cwd=W).returncode
        if rc != 0:
            rows.append({"config": name, "lr": lr, "epochs": ep, "rc": rc})
            continue
    r = json.loads((out / "train_record.json").read_text())
    rel_dom = (r["val_after"] - r["val_before"]) / r["val_before"]
    rel_gen = ((r["val_gen_after"] - r["val_gen_before"]) / r["val_gen_before"]
               if r.get("val_gen_before") else float("nan"))
    rows.append({"config": name, "lr": lr, "epochs": ep, "rc": 0, "steps": r.get("steps"), "rel_dom": rel_dom,
                 "rel_gen": rel_gen, "val_before": r["val_before"], "val_after": r["val_after"]})
    up(out / "train_record.json", f"{name}_train_record.json")
    print(json.dumps(rows[-1]), flush=True)

ok = [x for x in rows if x.get("rc") == 0 and math.isfinite(x["rel_dom"]) and math.isfinite(x["rel_gen"])
      and x["rel_gen"] <= GEN_MAX]
ok.sort(key=lambda x: (x["rel_dom"], x["epochs"], x["lr"]))
sel = {"prereg": "16_EVIDENCE/TRINITY/LB_B2_PREREG_2026-11-20.md", "rows": rows, "eligible": [x["config"] for x in ok]}
if not ok:
    sel["choice"] = None
    sel["H1_on_validation"] = "INCONCLUSIVE (no eligible configuration)"
else:
    best = ok[0]
    sel["choice"] = best["config"]
    sel["H1_on_validation"] = ("CONFIRMED" if best["rel_dom"] <= H1_YES else "FALSIFIED" if best["rel_dom"] > H1_NO
                               else "INCONCLUSIVE")
(W / "lbb2" / "selection.json").write_text(json.dumps(sel, indent=1))
up(W / "lbb2" / "selection.json", "selection.json")
print("SELECTION", json.dumps(sel), flush=True)

if sel["choice"]:
    d = W / "lbb2" / sel["choice"]
    rc = subprocess.run([sys.executable, "-u", str(W / "lb_tail_eval.py"), "--cache", str(W / "out_holdout"), "--trained",
                         str(d / "layer92_trained.pt"), "--out", str(d / "verdict.json")], cwd=W).returncode
    print("eval rc", rc, flush=True)
    for f, n in ((d / "verdict.json", "verdict.json"), (d / "verdict.raw.npz", "verdict.raw.npz"),
                 (d / "layer92_trained.pt", f"{sel['choice']}_layer92_trained.pt")):
        if f.exists():
            up(f, n)
    if (d / "verdict.json").exists():
        print("VERDICT", json.dumps(json.loads((d / "verdict.json").read_text())["acceptance"]), flush=True)