"""Colab GPU cell driver for the LB-A / LB-B passes (k3pass.py) and the LB-B training/eval. import os; os.environ['K3P'] = 'holdout' # or 'train', 'tail' (train + eval on existing caches) 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_k3pass.py', token=os.environ['HF_TOKEN'], force_download=True)).read()) holdout: Gemini's domain holdout pack (68 sequences) + Wikipedia articles 1-16, both models, cache of LittleBoy. train: domain training corpus packed to >= 12,500 characters + Wikipedia articles 17-48, LittleBoy only, cache. Caches and summaries are uploaded to the private LittleBoy repo under eval/ (NLL arrays, summaries, logs); the per-token caches go to the private dataset STAR-future/Trinity-k3cache. Since 2026-11-19 (two runtimes lost mid-pass, nothing saved): the log is uploaded every 10 minutes while the pass runs, and the pass checkpoints its state every K3_CKPT layers to STAR-future/Trinity-k3ckpt-, so running the same cell again on a fresh runtime resumes where the last checkpoint left off. tail refuses caches from passes that did not run all 93 layers (the 5-layer smoke cache of 2026-11-19 must never feed a verdict). """ import json import os import subprocess import sys import threading from pathlib import Path from huggingface_hub import HfApi, hf_hub_download TOK = os.environ["HF_TOKEN"] REPO = "STAR-future/Trinity" CACHE = "STAR-future/Trinity-k3cache" MODE = os.environ.get("K3P", "holdout") V3_PARTS = tuple(f"train{i}" for i in range(4, 4 + int(os.environ.get("K3_V3_SLICES", "7")))) # 7 slices fits 3-dom v3+physics in 368 GiB PUBLIC_TRAIN = ("train2", "train3") + V3_PARTS if MODE in PUBLIC_TRAIN: # 2026-11-21: private quota is full; these caches are of public CC0 text, so they go public CACHE = f"STAR-future/Trinity-k3cache-{MODE}" W = Path("/content/k3p") W.mkdir(parents=True, exist_ok=True) # FAIL-0089: the boot disk (236 GB) cannot hold the work files (214 GB + shards) and the final cache (~94 GB per 1.3 M # tokens). Colab A100 runtimes mount a 368 GB /mnt/local-scratch: put work and output there when it exists. if Path("/mnt/local-scratch").exists() and MODE in ("train",) + PUBLIC_TRAIN: for _n in (f"work_{MODE}", f"out_{MODE}"): _t, _l = Path("/mnt/local-scratch") / _n, W / _n _t.mkdir(parents=True, exist_ok=True) if not _l.exists() and not _l.is_symlink(): _l.symlink_to(_t) api = HfApi(token=TOK) subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tiktoken", "datasets"], 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()) (W / "train_corpus_v1.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v1.jsonl", token=TOK, force_download=True)).read_bytes()) if MODE in ("train2", "train3"): # domain corpus v2 (~10x v1, arXiv CC0 abstracts submitted before 2026-10-01) (W / "train_corpus_v2.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v2b.jsonl" if MODE == "train3" else "eval/data/train_corpus_v2.jsonl", token=TOK, force_download=True)).read_bytes()) if MODE in V3_PARTS: (W / "train_corpus_v3.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v3.jsonl", token=TOK, force_download=True)).read_bytes()) # the holdout lives only in the PRIVATE cache dataset: holdouts are never published (moved there 2026-11-19) (W / "k3stream_holdout_pack.jsonl").write_bytes(Path(hf_hub_download("STAR-future/Trinity-k3cache", "eval-data/k3stream_holdout_pack.jsonl", repo_type="dataset", token=TOK, force_download=True)).read_bytes()) def wiki(start, n): from datasets import load_dataset rows, k = [], 0 for r in load_dataset("wikimedia/wikipedia", "20231101.en", split="train", streaming=True): if len(r["text"]) > 16000: if k >= start: rows.append(r) k += 1 if len(rows) >= n: return rows return rows def run(cmd, logname): print(" ".join(cmd), flush=True) log = W / logname env = dict(os.environ, PYTHONPATH=str(W), PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True", HF_HUB_DISABLE_PROGRESS_BARS="1") stop = threading.Event() def pusher(): # the log reaches the repo even if the runtime is lost while not stop.wait(600): try: api.upload_file(path_or_fileobj=str(log), path_in_repo=f"eval/{logname}", repo_id=REPO, commit_message=f"{logname} (running)") except Exception as e: # noqa: BLE001 print("log upload failed", type(e).__name__, flush=True) th = threading.Thread(target=pusher, daemon=True) with subprocess.Popen(cmd, cwd=W, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1) as p, open(log, "w") as fo: th.start() for line in p.stdout: print(line, end="", flush=True) fo.write(line) fo.flush() stop.set() api.upload_file(path_or_fileobj=str(log), path_in_repo=f"eval/{logname}", repo_id=REPO, commit_message=logname) return p.returncode def up(path, name): if Path(path).exists(): api.upload_file(path_or_fileobj=str(path), path_in_repo=f"eval/{name}", repo_id=REPO, commit_message=name) if MODE in ("holdout", "train") + PUBLIC_TRAIN: rows = [] if MODE == "holdout": for r in map(json.loads, (W / "k3stream_holdout_pack.jsonl").read_text(encoding="utf-8").splitlines()): rows.append({"id": r["id"], "text": r["text"], "set": r["set"], "role": "holdout", "base": True}) for r in wiki(0, 16): rows.append({"id": r["title"], "text": r["text"], "set": "wikipedia", "role": "holdout", "base": True}) else: cfile = "train_corpus_v3.jsonl" if MODE in V3_PARTS else "train_corpus_v2.jsonl" if MODE in ("train2", "train3") else "train_corpus_v1.jsonl" docs = [json.loads(x) for x in (W / cfile).read_text(encoding="utf-8").splitlines() if x.strip()] ktok_pack = None if MODE in V3_PARTS: from transformers import AutoTokenizer ktok_pack = AutoTokenizer.from_pretrained("moonshotai/Kimi-K3.1-Pro", trust_remote_code=True) for dom in sorted({d["domain"] for d in docs}): buf, k, est_tok = [], 0, 0 for d in sorted((d for d in docs if d["domain"] == dom), key=lambda d: d["id"]): txt = d["text"].strip() buf.append(txt) if ktok_pack is not None: est_tok += len(ktok_pack.encode(txt)) + (2 if len(buf) > 1 else 0) ready = est_tok >= 2064 and len(ktok_pack.encode("\n\n".join(buf))) >= 2048 else: ready = sum(len(b) for b in buf) >= 12500 if ready: rows.append({"id": f"{MODE}_{dom}_{k:04d}", "text": "\n\n".join(buf), "set": f"train_{dom}", "role": "train", "base": False}) buf, k, est_tok = [], k + 1, 0 if MODE in V3_PARTS: # stratified stride slice across chips+space+physics so train4 alone covers all 3 domains! rows = rows[V3_PARTS.index(MODE)::len(V3_PARTS)] for r in (wiki(176 + 32 * V3_PARTS.index(MODE), 32) if MODE in V3_PARTS else wiki(112, 64) if MODE == "train3" else wiki(48, 64) if MODE == "train2" else wiki(16, 32)): rows.append({"id": r["title"], "text": r["text"], "set": "general_wiki", "role": "train", "base": False}) texts = W / f"streams_{MODE}.jsonl" texts.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8") out = W / f"out_{MODE}" import torch gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30 if gpu_gb < 39 and not os.environ.get("K3P_ALLOW_SMALL_GPU"): # 2026-11-23: Colab falls back to a T4 when no A100 is free raise SystemExit(f"GPU with {gpu_gb:.0f} GB: this pass needs an A100 (40/80 GB). Disconnect and retry later.") import shutil as _sh _work_dir = W / f"work_{MODE}" _work_dir.mkdir(parents=True, exist_ok=True) _n_streams = len(rows) * (2 if MODE == "holdout" else 1) _req_gib = (_n_streams * 2048 * (232000 if MODE != "holdout" else 195000)) / (2 ** 30) + 46.0 _free_gib = _sh.disk_usage(os.path.realpath(_work_dir)).free / (2 ** 30) if _free_gib < _req_gib and not os.environ.get("K3P_SKIP_DISK_GUARD"): raise SystemExit(f"Insufficient scratch disk for {MODE}: free={_free_gib:.1f} GiB < required={_req_gib:.1f} GiB (check /mnt/local-scratch)!") batch = os.environ.get("K3_BATCH", "12" if gpu_gb > 60 else ("8" if gpu_gb > 20 else "4")) rc = run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(_work_dir), "--out", str(out), "--batch", batch, "--layers", os.environ.get("K3_LAYERS", "-1"), "--ckpt-repo", f"STAR-future/Trinity-k3ckpt-{MODE}", "--ckpt-every", os.environ.get("K3_CKPT", "6")], f"k3pass_{MODE}.log") print("exit", rc, flush=True) up(out / "summary.json", f"k3pass_{MODE}_summary.json") up(out / "nll.npy", f"k3pass_{MODE}_nll.npy") up(out / "streams.json", f"k3pass_{MODE}_streams.json") if rc == 0 and (out / "summary.json").exists(): # keep the per-token cache durable: private dataset api.create_repo(CACHE, repo_type="dataset", private=MODE not in PUBLIC_TRAIN, exist_ok=True) # FAIL-0092: one 98 GB upload_folder commit never finished before the Colab VM was recycled (24 h). One commit # per file, retried, skipping what is already there, so every finished file survives a lost runtime. have = set(api.list_repo_files(CACHE, repo_type="dataset")) for f in sorted(p for p in out.iterdir() if p.suffix in (".npy", ".json")): if f"{MODE}/{f.name}" in have: continue for attempt in range(5): try: api.upload_file(path_or_fileobj=str(f), path_in_repo=f"{MODE}/{f.name}", repo_id=CACHE, repo_type="dataset", commit_message=f"k3pass cache {MODE}: {f.name}") print("uploaded", f.name, round(f.stat().st_size / 2 ** 30, 2), "GiB", flush=True) break except Exception as e: # noqa: BLE001 print("upload retry", f.name, attempt, type(e).__name__, str(e)[:120], flush=True) elif MODE == "tail": from huggingface_hub import snapshot_download 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} comes from a pass of {lr} layers, not 93: refusing to train or judge on it") rc = run([sys.executable, "-u", str(W / "lb_tail_train.py"), "--cache", str(W / "out_train"), "--out", str(W / "tail")], "lb_tail_train.log") if rc == 0: rc = run([sys.executable, "-u", str(W / "lb_tail_eval.py"), "--cache", str(W / "out_holdout"), "--trained", str(W / "tail" / "layer92_trained.pt"), "--out", str(W / "tail" / "verdict.json")], "lb_tail_eval.log") up(W / "tail" / "verdict.json", "lb_tail_verdict.json") up(W / "tail" / "verdict.raw.npz", "lb_tail_verdict.raw.npz") up(W / "tail" / "train_record.json", "lb_tail_train_record.json") up(W / "tail" / "layer92_trained.pt", "layer92_trained.pt") # 2026-11-24: confirmatory evaluation of a trained specialisation on the SEALED holdout (61 sequences, Gemini custody, # sha256 9d174d3f...). The texts come only from the private dataset; Trinity and the base model both run (base=True); # no checkpoints and no cache upload (private quota is full and the cache stays on this VM); only aggregate verdict # and per-token losses (numbers, no text) are published under eval/h5_sealed/. if MODE == "sealed": import torch gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30 if gpu_gb < 39 and not os.environ.get("K3P_ALLOW_SMALL_GPU"): raise SystemExit(f"GPU with {gpu_gb:.0f} GB: this pass needs an A100 (40/80 GB). Disconnect and retry later.") src = Path(hf_hub_download("STAR-future/Trinity-k3cache", "eval-data/sealed_h2_holdout_61.jsonl", repo_type="dataset", token=TOK, force_download=True)) import hashlib as _h if _h.sha256(src.read_bytes()).hexdigest() != "9d174d3fc71accb0001cdab2a4293cfdd44663ff573362735cbe8956d2580dad": raise SystemExit("sealed holdout file does not match its sealed sha256") rows = [] for r in map(json.loads, src.read_text(encoding="utf-8").splitlines()): st = "wikipedia" if r["set"].startswith("general") else r["set"].replace("h2_", "") rows.append({"id": r["id"], "text": r["text"], "set": st, "role": "holdout", "base": True}) texts = W / "streams_sealed.jsonl" texts.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8") out = W / "out_sealed" if not (out / "summary.json").exists(): rc = run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(W / "work_sealed"), "--out", str(out), "--batch", "12" if gpu_gb > 60 else "8", "--layers", "-1", "--ckpt-repo", "STAR-future/Trinity-k3ckpt-sealed", "--ckpt-every", "999"], "k3pass_sealed.log") print("pass exit", rc, flush=True) if json.loads((out / "summary.json").read_text()).get("layers_run") != 93: raise SystemExit("sealed pass did not run all 93 layers: no verdict") trained = os.environ.get("K3P_TRAINED", "eval/h4/F1_Arm3_HeadLoRA_full_tail_wsp.pt") tp = Path(hf_hub_download(REPO, trained, token=TOK, force_download=True)) (W / "trinity_full_tail_wsp.py").write_bytes(Path(hf_hub_download(REPO, "tools/trinity_full_tail_wsp.py", token=TOK, force_download=True)).read_bytes()) rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval", "--cache", str(out), "--trained", str(tp), "--out", str(W / "h5_sealed")], "h5_sealed_eval.log") for f in (W / "h5_sealed").glob("*"): if f.is_file(): api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h5_sealed/{f.name}", repo_id=REPO, commit_message=f"H5 sealed holdout: {f.name}") up(out / "summary.json", "h5_sealed/k3pass_sealed_summary.json") print("sealed eval exit", rc, flush=True) if rc == 0 and os.environ.get("K3P_BPB", "1") != "0": # bits-per-byte comparison with open models, same VM exec(open(hf_hub_download(REPO, "tools/colab_bpb_compare.py", token=TOK, force_download=True)).read()) # 2026-11-24: H6 on the SAME VM that ran K3P=sealed and K3P=train4 (out_sealed and out_train4 are local). # Trains a larger specialisation than F1 (head LoRA r256 + layer-92 tail LoRA r128 + LoRA on the 128 hottest routed # experts, incl. new ones when they are hot) on caches train2 + train3 + train4 (~3.2 M tokens), then judges it on the # sealed holdout against Trinity and the base model. Prereg: 16_EVIDENCE/TRINITY/H6_PREREG_2026-11-24.md. if MODE == "h6": import shutil from huggingface_hub import snapshot_download if not (W / "out_sealed" / "summary.json").exists(): raise SystemExit("H6 needs out_sealed on this VM (run K3P=sealed first)") for wtmp in ("work_train4", "work_sealed"): # free BOTH scratch (~172 GiB) AND boot disk (~38 GiB)! if (W / wtmp).exists() or (W / wtmp).is_symlink(): shutil.rmtree((W / wtmp).resolve(), ignore_errors=True) if (W / wtmp).is_symlink(): (W / wtmp).unlink(missing_ok=True) scratch = Path("/mnt/local-scratch") if Path("/mnt/local-scratch").exists() else W xet_tmp = scratch / "hf_xet_tmp" # prevent hf-xet from filling 236 GiB boot disk ~/.cache! os.environ["HF_XET_CACHE"] = str(xet_tmp) extra = [str(W / "out_train4")] if (W / "out_train4" / "summary.json").exists() else [] # train4 if this VM built it print("H6 caches: train2, train3" + (", train4" if extra else ""), flush=True) for m in ("train2", "train3"): dst = W / f"out_{m}" if not (dst / "summary.json").exists(): dl = scratch / f"dl_{m}" snapshot_download(f"STAR-future/Trinity-k3cache-{m}", repo_type="dataset", token=TOK, allow_patterns=[f"{m}/*"], local_dir=str(dl), cache_dir=str(scratch / "hf_cache"), max_workers=8) shutil.rmtree(xet_tmp, ignore_errors=True) if dst.is_symlink(): dst.unlink() if not dst.exists(): dst.symlink_to(dl / m) if json.loads((dst / "summary.json").read_text()).get("layers_run") != 93: raise SystemExit(f"cache {m} is not a 93-layer pass") (W / "trinity_full_tail_wsp.py").write_bytes(Path(hf_hub_download(REPO, "tools/trinity_full_tail_wsp.py", token=TOK, force_download=True)).read_bytes()) h6 = W / "h6" h6_doms = os.environ.get("H6_DOMAINS", "chips,space,physics") import torch _h6_gpu = torch.cuda.get_device_properties(0).total_memory / 2 ** 30 # 2026-11-24 (prereg Amendment 3): 384 routed experts (w1+w3 ~58 MB each, ~22 GB) do not fit a 24 GB L4. Below # 39 GB the run is "H6-lite": head r256 + tail r128 + final norm, no routed-expert LoRA. Recorded in h6_variant.json. h6_routed = ["--k", "128", "--include-new-experts"] if _h6_gpu >= 39 else ["--k", "0"] h6.mkdir(parents=True, exist_ok=True) (h6 / "h6_variant.json").write_text(json.dumps({"gpu_gib": round(_h6_gpu, 1), "variant": "full" if _h6_gpu >= 39 else "lite", "routed_args": h6_routed, "domains": h6_doms})) if not (h6 / "full_tail_wsp.pt").exists(): rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "train", "--cache", str(W / "out_train2"), str(W / "out_train3"), *extra, "--out", str(h6), "--domains", h6_doms, "--head-rank", "256", "--head-alpha", "256", "--tail-rank", "128", "--tail-alpha", "128", *h6_routed, "--routed-rank", "16", "--routed-alpha", "16", "--skip-prefix-tokens", "2", "--lr", "1.5e-4", "--epochs", "3.0", "--kl", "6.0", "--block-size", "256"], "h6_train.log") if rc != 0: raise SystemExit(f"H6 training failed ({rc})") for f in h6.glob("*"): if f.is_file(): api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h6/{f.name}", repo_id=REPO, commit_message=f"H6 trained specialisation: {f.name}") rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval", "--cache", str(W / "out_sealed"), "--trained", str(h6 / "full_tail_wsp.pt"), "--out", str(W / "h6_sealed")], "h6_sealed_eval.log") for f in (W / "h6_sealed").glob("*"): if f.is_file(): api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h6_sealed/{f.name}", repo_id=REPO, commit_message=f"H6 sealed holdout: {f.name}") print("h6 sealed eval exit", rc, flush=True) if rc == 0 and os.environ.get("K3P_BPB", "1") != "0": os.environ["BPB_DIR"] = "h6_sealed" exec(open(hf_hub_download(REPO, "tools/colab_bpb_compare.py", token=TOK, force_download=True)).read())