File size: 4,320 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
"""Colab GPU cell driver for Trinity H3d (16_EVIDENCE/TRINITY/LB_H3D_PREREG_2026-11-22.md): unfreeze the K=64 most-used real
experts in two preregistered configurations on the train cache, choose on validation only, then a DEV evaluation on the
already-seen holdout (not confirmatory). The confirmatory evaluation on the sealed fresh holdout runs later.

    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_h3d.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, CACHE = "STAR-future/Trinity", "STAR-future/Trinity-k3cache"
W = Path("/content/k3p")
W.mkdir(parents=True, exist_ok=True)
api = HfApi(token=TOK)
CONFIGS = [("D1", 4e-4, 64, "adafactor"), ("D2", 1e-3, 64, "adafactor"), ("D3", 1e-5, 64, "adamw")]


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/h3d/{name}", repo_id=REPO,
                            commit_message=f"H3 {name}")
            return
        except Exception as e:  # noqa: BLE001
            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_unfreeze.py"):
    (W / f).write_bytes(Path(hf_hub_download(REPO, f"tools/{f}", token=TOK, force_download=True)).read_bytes())
for m, repo, folder in (("train", "STAR-future/Trinity-k3cache-train2", "train2"), ("holdout", CACHE, "holdout")):
    if not (W / f"out_{m}" / "summary.json").exists():
        snapshot_download(repo, repo_type="dataset", token=TOK, allow_patterns=[f"{folder}/*"], local_dir=str(W / "cache_dl"))
        (W / f"out_{m}").mkdir(exist_ok=True)
        for f in (W / "cache_dl" / folder).iterdir():
            f.rename(W / f"out_{m}" / f.name)
rows = []
for name, lr, kk, opt in CONFIGS:
    out = W / "h3d" / name
    if not (out / "train_record.json").exists():
        rc = subprocess.run([sys.executable, "-u", str(W / "lb_unfreeze.py"), "train", "--cache", str(W / "out_train"),
                             "--out", str(out), "--lr", str(lr), "--epochs", "2", "--k", str(kk), "--opt", opt, "--domains", "chips,space"], cwd=W).returncode
        if rc != 0:
            rows.append({"config": name, "lr": lr, "k": kk, "rc": rc})
            continue
    r = json.loads((out / "train_record.json").read_text())
    rows.append({"config": name, "lr": lr, "k": kk, "rc": 0, "rel_dom": r["rel_dom"], "rel_gen": r["rel_gen"],
                 "trained_parameters": r["trained_parameters"], "steps": r["steps"]})
    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 x["rel_gen"] is not None and math.isfinite(x["rel_dom"])
      and x["rel_gen"] <= 0.005]
ok.sort(key=lambda x: x["rel_dom"])
sel = {"prereg": "16_EVIDENCE/TRINITY/LB_H3D_PREREG_2026-11-22.md", "rows": rows,
       "choice": ok[0]["config"] if ok else None,
       "reading": None if not ok else ("PROMISING" if ok[0]["rel_dom"] <= -0.015 else
                                       "NOT_BETTER_THAN_LBB" if ok[0]["rel_dom"] > -0.006 else "BETWEEN")}
(W / "h3d" / "selection.json").write_text(json.dumps(sel, indent=1))
up(W / "h3d" / "selection.json", "selection.json")
print("SELECTION", json.dumps(sel), flush=True)
if sel["choice"]:
    d = W / "h3d" / sel["choice"]
    rc = subprocess.run([sys.executable, "-u", str(W / "lb_unfreeze.py"), "eval", "--cache", str(W / "out_holdout"),
                         "--trained", str(d / "experts.pt"), "--out", str(d / "dev")], cwd=W).returncode
    print("dev eval rc", rc, flush=True)
    for f, n in ((d / "dev" / "verdict_h2b.json", "dev_verdict_h3d.json"),
                 (d / "dev" / "verdict_h2b.raw.npz", "dev_verdict_h3d.raw.npz"),
                 (d / "experts.pt", f"{sel['choice']}_experts.pt")):
        if f.exists():
            up(f, n)