Trinity / tools /colab_h3.py
STAR-future's picture
Trinity: public release (history squashed)
f80e81a
Raw History Blame Contribute Delete
4.28 kB
"""Colab GPU cell driver for Trinity H3 (16_EVIDENCE/TRINITY/LB_H3_PREREG_2026-11-21.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_h3.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 = [("A1", 1e-5, 16, "adamw"), ("A2", 3e-5, 16, "adamw"), ("B1", 3e-5, 64, "adafactor")]
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/h3/{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 / "h3" / 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], 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_H3_PREREG_2026-11-21.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 / "h3" / "selection.json").write_text(json.dumps(sel, indent=1))
up(W / "h3" / "selection.json", "selection.json")
print("SELECTION", json.dumps(sel), flush=True)
if sel["choice"]:
d = W / "h3" / 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_h3.json"),
(d / "dev" / "verdict_h2b.raw.npz", "dev_verdict_h3.raw.npz"),
(d / "experts.pt", f"{sel['choice']}_experts.pt")):
if f.exists():
up(f, n)