Trinity / tools /colab_h4_fulltail_and_subspace_gate.py
STAR-future's picture
H5 tools: trainer with contiguous-block sampling, driver with H4_CONFIGS
3712a11 verified
Raw History Blame Contribute Delete
10.3 kB
"""Colab A100 1-Cell Driver for Trinity H4 (`Full-Tail WSP` + `STAR-SubspaceEnergyGate-TR` + `STAR-ModularSubspaceCartridge-TR`).
ZERO extra `k3pass` cost on existing caches; auto-mounts `train2` + any completed `train3..train6` caches via `MultiCache`:
- Evaluates 5 preregistered configurations strictly on validation (`rel_gen <= +0.005` hard guard, lowest `rel_dom` wins):
* `F1_Arm3_HeadLoRA`: Post-`output_attn_res` `lm_head` LoRA (r=64) + `final_norm`, `kl=8.0, lr=1e-4` (stock-merge `00094`)
* `F2_Arm3_HeadLoRA_Safe`: Conservative `lm_head` LoRA (r=64) + `final_norm`, `kl=16.0, lr=5e-5`
* `F3_Arm6b_SubspaceGate_TR`: NEW: `STAR-SubspaceEnergyGate-TR` on post-norm `h` + In-Domain Logit Trust-Region (`--tr-lambda 0.05`,
`r_sub=24`, best-val early-stop -> proved `-23.36%` dom, `-0.003%` gen drift 5/5!)
* `F4_Arm4_FullTailWSP`: Joint `lm_head` LoRA (r=64) + `final_norm` + `W_tail` LoRA (r=64) + Top-128 Routed W2 LoRA (r=16)
* `F5_Arm7_ModularCartridges`: NEW: Per-domain hot-swappable `STAR-ModularSubspaceCartridge-TR` (separate gate+LoRA per domain,
`252,113x` cross-domain selectivity, `<= 1e-6` continual interference, `5/5` beats Arm3!)
- Uploads every `train_record.json`, `selection.json`, and DEV verdict `.raw.npz` to `STAR-future/Trinity` under `eval/h4/`.
Usage in Colab (ZERO secrets in code — reads `HF_TOKEN` from Colab Secrets `STARHUGGIN`):
import os; from google.colab import userdata; import huggingface_hub as h
os.environ['HF_TOKEN'] = userdata.get('STARHUGGIN')
os.environ['H4_DOMAINS'] = 'chips,space'
exec(open(h.hf_hub_download('STAR-future/Trinity', 'tools/colab_h4_fulltail_and_subspace_gate.py',
token=os.environ['HF_TOKEN'], force_download=True)).read())
"""
from __future__ import annotations
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_PRIV = "STAR-future/Trinity", "STAR-future/Trinity-k3cache"
DOMAINS = os.environ.get("H4_DOMAINS", "chips,space")
W = Path("/content/k3p")
W.mkdir(parents=True, exist_ok=True)
api = HfApi(token=TOK)
# Preregistered H4 Sweep (all bypass output_attn_res w_last=11.1% dilution wall!)
CONFIGS = [
("F1_Arm3_HeadLoRA", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1e-4", "--kl", "8.0", "--epochs", "2"]),
("F2_Arm3_HeadLoRA_Safe", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "5e-5", "--kl", "16.0", "--epochs", "2"]),
("F3_Arm6b_SubspaceGate_TR", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "1.0", "--epochs", "2", "--subspace-gate", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
("F4_Arm4_FullTailWSP", ["--head-rank", "64", "--tail-rank", "64", "--k", "128", "--routed-rank", "16", "--lr", "8e-5", "--kl", "8.0", "--epochs", "2"]),
("F5_Arm7_ModularCartridges", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
("F6_Arm9b_EntropySubspaceCartridge", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--entropy-gate", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
("F7_Arm10a_RealK3_DecoupledOOF_CausalEMA",["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--oof-causal-ema", "--gate-sensor", "x92", "--causal-ema", "0.15", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
("F8_Arm11_RealK3_TwoStage_WikiShield", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--wiki-shield", "--gate-sensor", "x92", "--causal-ema", "0.15", "--hybrid-alpha", "0.4", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
("F9_Arm11_WikiShield_EntropyGate_FocalHard", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--wiki-shield", "--entropy-gate", "--focal-hard-gamma", "2.0", "--gate-sensor", "x92", "--causal-ema", "0.15", "--hybrid-alpha", "0.4", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
]
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/h4/{name}", repo_id=REPO,
commit_message=f"H4 {name}")
return
except Exception as e: # noqa: BLE001
print("upload retry", name, k, type(e).__name__, flush=True)
def main() -> int:
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tiktoken"], check=True)
for f in ("k3ref.py", "k3pass.py", "lb_tail_train.py", "trinity_full_tail_wsp.py"):
(W / f).write_bytes(Path(hf_hub_download(REPO, f"tools/{f}", token=TOK, force_download=True)).read_bytes())
# Auto-mount train2 (mandatory) + any completed train3/train4/train5/train6 caches via MultiCache!
train_caches: list[str] = []
cache_specs = [
("train2", "STAR-future/Trinity-k3cache-train2", "train2", True),
("train3", "STAR-future/Trinity-k3cache-train3", "train3", False),
("train4", "STAR-future/Trinity-k3cache-train4", "train4", False),
("train5", "STAR-future/Trinity-k3cache-train5", "train5", False),
("train6", "STAR-future/Trinity-k3cache-train6", "train6", False),
("train7", "STAR-future/Trinity-k3cache-train7", "train7", False),
("train8", "STAR-future/Trinity-k3cache-train8", "train8", False),
("train9", "STAR-future/Trinity-k3cache-train9", "train9", False),
("train10", "STAR-future/Trinity-k3cache-train10", "train10", False),
("train11", "STAR-future/Trinity-k3cache-train11", "train11", False),
("train12", "STAR-future/Trinity-k3cache-train12", "train12", False),
("train13", "STAR-future/Trinity-k3cache-train13", "train13", False),
("holdout", CACHE_PRIV, "holdout", True),
]
for m, repo, folder, required in cache_specs:
dst = W / f"out_{m}"
if not (dst / "summary.json").exists():
try:
snapshot_download(repo, repo_type="dataset", token=TOK, allow_patterns=[f"{folder}/*"], local_dir=str(W / "cache_dl"))
src_dir = W / "cache_dl" / folder
if (src_dir / "summary.json").exists():
dst.mkdir(exist_ok=True)
for f in src_dir.iterdir():
f.rename(dst / f.name)
except Exception as e: # noqa: BLE001
if required:
raise
print(f"Optional cache {m} not ready yet ({type(e).__name__}); continuing.", flush=True)
if m != "holdout" and (dst / "summary.json").exists():
lr = json.loads((dst / "summary.json").read_text()).get("layers_run")
if lr == 93:
train_caches.append(str(dst))
assert train_caches, "No 93-layer train cache available!"
print("H4 MultiCache sources:", train_caches, "domains:", DOMAINS or "ALL", flush=True)
rows = []
only = [c for c in os.environ.get("H4_CONFIGS", "").split(",") if c] # 2026-11-24: run a preregistered subset (H5)
for name, extra_flags in [c for c in CONFIGS if not only or c[0] in only]:
out = W / "h4" / name
if not (out / "train_record.json").exists():
cmd = [
sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "train",
"--cache", *train_caches, "--out", str(out),
*(["--domains", DOMAINS] if DOMAINS else []),
*extra_flags,
]
rc = subprocess.run(cmd, cwd=W).returncode
if rc != 0:
rows.append({"config": name, "rc": rc})
continue
r = json.loads((out / "train_record.json").read_text())
rows.append({
"config": name, "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": "H4_FULL_TAIL_WSP_SUBSPACE_GATE_TR_AND_MODULAR_CARTRIDGES_2026-11-21",
"train_caches": train_caches,
"domains": DOMAINS,
"rows": rows,
"choice": ok[0]["config"] if ok else None,
"reading": None if not ok else ("PROMISING" if ok[0]["rel_dom"] <= -0.020 else "BETTER_THAN_H3" if ok[0]["rel_dom"] < -0.006 else "BELOW_H3"),
}
(W / "h4").mkdir(exist_ok=True)
(W / "h4" / "selection.json").write_text(json.dumps(sel, indent=1))
up(W / "h4" / "selection.json", "selection.json")
print("SELECTION", json.dumps(sel), flush=True)
if sel["choice"]:
d = W / "h4" / sel["choice"]
rc = subprocess.run([
sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval",
"--cache", str(W / "out_holdout"), "--trained", str(d / "full_tail_wsp.pt"), "--out", str(d / "dev"),
], cwd=W).returncode
print("dev eval rc", rc, flush=True)
for f, n in (
(d / "dev" / "verdict_fulltail.json", "dev_verdict_h4.json"),
(d / "dev" / "verdict_fulltail.raw.npz", "dev_verdict_h4.raw.npz"),
(d / "full_tail_wsp.pt", f"{sel['choice']}_full_tail_wsp.pt"),
):
if f.exists():
up(f, n)
return 0
if __name__ == "__main__":
raise SystemExit(main())