STAR-future commited on
Commit
e02fe52
·
verified ·
1 Parent(s): 0a3b313

H6: all 256 new experts, 3 domains, skip prefix tokens, disk-safe downloads (Gemini patches 35b/35c, reviewed)

Browse files
Files changed (1) hide show
  1. tools/colab_k3pass.py +304 -276
tools/colab_k3pass.py CHANGED
@@ -1,276 +1,304 @@
1
- """Colab GPU cell driver for the LB-A / LB-B passes (k3pass.py) and the LB-B training/eval.
2
-
3
- import os; os.environ['K3P'] = 'holdout' # or 'train', 'tail' (train + eval on existing caches)
4
- from google.colab import userdata; import huggingface_hub as h; os.environ['HF_TOKEN'] = userdata.get('STARHUGGIN')
5
- exec(open(h.hf_hub_download('STAR-future/Trinity', 'tools/colab_k3pass.py', token=os.environ['HF_TOKEN'],
6
- force_download=True)).read())
7
-
8
- holdout: Gemini's domain holdout pack (68 sequences) + Wikipedia articles 1-16, both models, cache of LittleBoy.
9
- train: domain training corpus packed to >= 12,500 characters + Wikipedia articles 17-48, LittleBoy only, cache.
10
- Caches and summaries are uploaded to the private LittleBoy repo under eval/ (NLL arrays, summaries, logs); the
11
- per-token caches go to the private dataset STAR-future/Trinity-k3cache.
12
- Since 2026-11-19 (two runtimes lost mid-pass, nothing saved): the log is uploaded every 10 minutes while the pass
13
- runs, and the pass checkpoints its state every K3_CKPT layers to STAR-future/Trinity-k3ckpt-<mode>, so running the
14
- same cell again on a fresh runtime resumes where the last checkpoint left off. tail refuses caches from passes that
15
- did not run all 93 layers (the 5-layer smoke cache of 2026-11-19 must never feed a verdict).
16
- """
17
- import json
18
- import os
19
- import subprocess
20
- import sys
21
- import threading
22
- from pathlib import Path
23
-
24
- from huggingface_hub import HfApi, hf_hub_download
25
-
26
- TOK = os.environ["HF_TOKEN"]
27
- REPO = "STAR-future/Trinity"
28
- CACHE = "STAR-future/Trinity-k3cache"
29
- MODE = os.environ.get("K3P", "holdout")
30
- PUBLIC_TRAIN = ("train2", "train3", "train4", "train5", "train6", "train7")
31
- V3_PARTS = ("train4", "train5", "train6", "train7") # 2026-11-24: corpus v3 (arXiv CC0 + NASA PD), 4 slices
32
- if MODE in PUBLIC_TRAIN: # 2026-11-21: private quota is full; these caches are of public CC0 text, so they go public
33
- CACHE = f"STAR-future/Trinity-k3cache-{MODE}"
34
- W = Path("/content/k3p")
35
- W.mkdir(parents=True, exist_ok=True)
36
- # 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
37
- # tokens). Colab A100 runtimes mount a 368 GB /mnt/local-scratch: put work and output there when it exists.
38
- if Path("/mnt/local-scratch").exists() and MODE in ("train",) + PUBLIC_TRAIN:
39
- for _n in (f"work_{MODE}", f"out_{MODE}"):
40
- _t, _l = Path("/mnt/local-scratch") / _n, W / _n
41
- _t.mkdir(parents=True, exist_ok=True)
42
- if not _l.exists() and not _l.is_symlink():
43
- _l.symlink_to(_t)
44
- api = HfApi(token=TOK)
45
- subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tiktoken", "datasets"], check=True)
46
- for f in ("k3ref.py", "k3pass.py", "lb_tail_train.py", "lb_tail_eval.py"):
47
- (W / f).write_bytes(Path(hf_hub_download(REPO, f"tools/{f}", token=TOK, force_download=True)).read_bytes())
48
- (W / "train_corpus_v1.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v1.jsonl", token=TOK,
49
- force_download=True)).read_bytes())
50
- if MODE in ("train2", "train3"): # domain corpus v2 (~10x v1, arXiv CC0 abstracts submitted before 2026-10-01)
51
- (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,
52
- force_download=True)).read_bytes())
53
- if MODE in V3_PARTS:
54
- (W / "train_corpus_v3.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v3.jsonl", token=TOK,
55
- force_download=True)).read_bytes())
56
- # the holdout lives only in the PRIVATE cache dataset: holdouts are never published (moved there 2026-11-19)
57
- (W / "k3stream_holdout_pack.jsonl").write_bytes(Path(hf_hub_download("STAR-future/Trinity-k3cache", "eval-data/k3stream_holdout_pack.jsonl",
58
- repo_type="dataset", token=TOK,
59
- force_download=True)).read_bytes())
60
-
61
-
62
- def wiki(start, n):
63
- from datasets import load_dataset
64
- rows, k = [], 0
65
- for r in load_dataset("wikimedia/wikipedia", "20231101.en", split="train", streaming=True):
66
- if len(r["text"]) > 16000:
67
- if k >= start:
68
- rows.append(r)
69
- k += 1
70
- if len(rows) >= n:
71
- return rows
72
- return rows
73
-
74
-
75
- def run(cmd, logname):
76
- print(" ".join(cmd), flush=True)
77
- log = W / logname
78
- env = dict(os.environ, PYTHONPATH=str(W), PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True",
79
- HF_HUB_DISABLE_PROGRESS_BARS="1")
80
- stop = threading.Event()
81
-
82
- def pusher(): # the log reaches the repo even if the runtime is lost
83
- while not stop.wait(600):
84
- try:
85
- api.upload_file(path_or_fileobj=str(log), path_in_repo=f"eval/{logname}", repo_id=REPO,
86
- commit_message=f"{logname} (running)")
87
- except Exception as e: # noqa: BLE001
88
- print("log upload failed", type(e).__name__, flush=True)
89
- th = threading.Thread(target=pusher, daemon=True)
90
- with subprocess.Popen(cmd, cwd=W, env=env, stdout=subprocess.PIPE,
91
- stderr=subprocess.STDOUT, text=True, bufsize=1) as p, open(log, "w") as fo:
92
- th.start()
93
- for line in p.stdout:
94
- print(line, end="", flush=True)
95
- fo.write(line)
96
- fo.flush()
97
- stop.set()
98
- api.upload_file(path_or_fileobj=str(log), path_in_repo=f"eval/{logname}", repo_id=REPO, commit_message=logname)
99
- return p.returncode
100
-
101
-
102
- def up(path, name):
103
- if Path(path).exists():
104
- api.upload_file(path_or_fileobj=str(path), path_in_repo=f"eval/{name}", repo_id=REPO, commit_message=name)
105
-
106
-
107
- if MODE in ("holdout", "train") + PUBLIC_TRAIN:
108
- rows = []
109
- if MODE == "holdout":
110
- for r in map(json.loads, (W / "k3stream_holdout_pack.jsonl").read_text(encoding="utf-8").splitlines()):
111
- rows.append({"id": r["id"], "text": r["text"], "set": r["set"], "role": "holdout", "base": True})
112
- for r in wiki(0, 16):
113
- rows.append({"id": r["title"], "text": r["text"], "set": "wikipedia", "role": "holdout", "base": True})
114
- else:
115
- 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"
116
- docs = [json.loads(x) for x in (W / cfile).read_text(encoding="utf-8").splitlines() if x.strip()]
117
- for dom in sorted({d["domain"] for d in docs}):
118
- buf, k = [], 0
119
- for d in sorted((d for d in docs if d["domain"] == dom), key=lambda d: d["id"]):
120
- buf.append(d["text"].strip())
121
- if sum(len(b) for b in buf) >= 12500:
122
- rows.append({"id": f"{MODE}_{dom}_{k:03d}", "text": "\n\n".join(buf), "set": f"train_{dom}",
123
- "role": "train", "base": False})
124
- buf, k = [], k + 1
125
- if MODE in V3_PARTS: # slice i of 4 (by row order), so each pass fits the 368 GB scratch disk (~640 rows)
126
- rows = rows[V3_PARTS.index(MODE)::4]
127
- 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)):
128
- rows.append({"id": r["title"], "text": r["text"], "set": "general_wiki", "role": "train", "base": False})
129
- texts = W / f"streams_{MODE}.jsonl"
130
- texts.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
131
- out = W / f"out_{MODE}"
132
- import torch
133
- gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
134
- 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
135
- raise SystemExit(f"GPU with {gpu_gb:.0f} GB: this pass needs an A100 (40/80 GB). Disconnect and retry later.")
136
- batch = os.environ.get("K3_BATCH", "12" if gpu_gb > 60 else ("8" if gpu_gb > 20 else "4"))
137
- rc = run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(W / f"work_{MODE}"),
138
- "--out", str(out), "--batch", batch, "--layers", os.environ.get("K3_LAYERS", "-1"),
139
- "--ckpt-repo", f"STAR-future/Trinity-k3ckpt-{MODE}", "--ckpt-every", os.environ.get("K3_CKPT", "6")],
140
- f"k3pass_{MODE}.log")
141
- print("exit", rc, flush=True)
142
- up(out / "summary.json", f"k3pass_{MODE}_summary.json")
143
- up(out / "nll.npy", f"k3pass_{MODE}_nll.npy")
144
- up(out / "streams.json", f"k3pass_{MODE}_streams.json")
145
- if rc == 0 and (out / "summary.json").exists(): # keep the per-token cache durable: private dataset
146
- api.create_repo(CACHE, repo_type="dataset", private=MODE not in PUBLIC_TRAIN, exist_ok=True)
147
- # FAIL-0092: one 98 GB upload_folder commit never finished before the Colab VM was recycled (24 h). One commit
148
- # per file, retried, skipping what is already there, so every finished file survives a lost runtime.
149
- have = set(api.list_repo_files(CACHE, repo_type="dataset"))
150
- for f in sorted(p for p in out.iterdir() if p.suffix in (".npy", ".json")):
151
- if f"{MODE}/{f.name}" in have:
152
- continue
153
- for attempt in range(5):
154
- try:
155
- api.upload_file(path_or_fileobj=str(f), path_in_repo=f"{MODE}/{f.name}", repo_id=CACHE, repo_type="dataset",
156
- commit_message=f"k3pass cache {MODE}: {f.name}")
157
- print("uploaded", f.name, round(f.stat().st_size / 2 ** 30, 2), "GiB", flush=True)
158
- break
159
- except Exception as e: # noqa: BLE001
160
- print("upload retry", f.name, attempt, type(e).__name__, str(e)[:120], flush=True)
161
- elif MODE == "tail":
162
- from huggingface_hub import snapshot_download
163
- for m in ("train", "holdout"):
164
- if not (W / f"out_{m}" / "summary.json").exists():
165
- snapshot_download(CACHE, repo_type="dataset", token=TOK, allow_patterns=[f"{m}/*"], local_dir=str(W / "cache_dl"))
166
- (W / f"out_{m}").mkdir(exist_ok=True)
167
- for f in (W / "cache_dl" / m).iterdir():
168
- f.rename(W / f"out_{m}" / f.name)
169
- lr = json.loads((W / f"out_{m}" / "summary.json").read_text()).get("layers_run")
170
- if lr != 93:
171
- raise SystemExit(f"cache {m} comes from a pass of {lr} layers, not 93: refusing to train or judge on it")
172
- rc = run([sys.executable, "-u", str(W / "lb_tail_train.py"), "--cache", str(W / "out_train"),
173
- "--out", str(W / "tail")], "lb_tail_train.log")
174
- if rc == 0:
175
- rc = run([sys.executable, "-u", str(W / "lb_tail_eval.py"), "--cache", str(W / "out_holdout"),
176
- "--trained", str(W / "tail" / "layer92_trained.pt"), "--out", str(W / "tail" / "verdict.json")],
177
- "lb_tail_eval.log")
178
- up(W / "tail" / "verdict.json", "lb_tail_verdict.json")
179
- up(W / "tail" / "verdict.raw.npz", "lb_tail_verdict.raw.npz")
180
- up(W / "tail" / "train_record.json", "lb_tail_train_record.json")
181
- up(W / "tail" / "layer92_trained.pt", "layer92_trained.pt")
182
-
183
-
184
- # 2026-11-24: confirmatory evaluation of a trained specialisation on the SEALED holdout (61 sequences, Gemini custody,
185
- # sha256 9d174d3f...). The texts come only from the private dataset; Trinity and the base model both run (base=True);
186
- # no checkpoints and no cache upload (private quota is full and the cache stays on this VM); only aggregate verdict
187
- # and per-token losses (numbers, no text) are published under eval/h5_sealed/.
188
- if MODE == "sealed":
189
- import torch
190
- gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
191
- if gpu_gb < 39 and not os.environ.get("K3P_ALLOW_SMALL_GPU"):
192
- raise SystemExit(f"GPU with {gpu_gb:.0f} GB: this pass needs an A100 (40/80 GB). Disconnect and retry later.")
193
- src = Path(hf_hub_download("STAR-future/Trinity-k3cache", "eval-data/sealed_h2_holdout_61.jsonl", repo_type="dataset",
194
- token=TOK, force_download=True))
195
- import hashlib as _h
196
- if _h.sha256(src.read_bytes()).hexdigest() != "9d174d3fc71accb0001cdab2a4293cfdd44663ff573362735cbe8956d2580dad":
197
- raise SystemExit("sealed holdout file does not match its sealed sha256")
198
- rows = []
199
- for r in map(json.loads, src.read_text(encoding="utf-8").splitlines()):
200
- st = "wikipedia" if r["set"].startswith("general") else r["set"].replace("h2_", "")
201
- rows.append({"id": r["id"], "text": r["text"], "set": st, "role": "holdout", "base": True})
202
- texts = W / "streams_sealed.jsonl"
203
- texts.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
204
- out = W / "out_sealed"
205
- if not (out / "summary.json").exists():
206
- rc = run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(W / "work_sealed"),
207
- "--out", str(out), "--batch", "12" if gpu_gb > 60 else "8", "--layers", "-1",
208
- "--ckpt-repo", "STAR-future/Trinity-k3ckpt-sealed", "--ckpt-every", "999"], "k3pass_sealed.log")
209
- print("pass exit", rc, flush=True)
210
- if json.loads((out / "summary.json").read_text()).get("layers_run") != 93:
211
- raise SystemExit("sealed pass did not run all 93 layers: no verdict")
212
- trained = os.environ.get("K3P_TRAINED", "eval/h4/F1_Arm3_HeadLoRA_full_tail_wsp.pt")
213
- tp = Path(hf_hub_download(REPO, trained, token=TOK, force_download=True))
214
- (W / "trinity_full_tail_wsp.py").write_bytes(Path(hf_hub_download(REPO, "tools/trinity_full_tail_wsp.py", token=TOK,
215
- force_download=True)).read_bytes())
216
- rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval", "--cache", str(out), "--trained", str(tp),
217
- "--out", str(W / "h5_sealed")], "h5_sealed_eval.log")
218
- for f in (W / "h5_sealed").glob("*"):
219
- if f.is_file():
220
- api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h5_sealed/{f.name}", repo_id=REPO,
221
- commit_message=f"H5 sealed holdout: {f.name}")
222
- up(out / "summary.json", "h5_sealed/k3pass_sealed_summary.json")
223
- print("sealed eval exit", rc, flush=True)
224
- if rc == 0 and os.environ.get("K3P_BPB", "1") != "0": # bits-per-byte comparison with open models, same VM
225
- exec(open(hf_hub_download(REPO, "tools/colab_bpb_compare.py", token=TOK, force_download=True)).read())
226
-
227
-
228
- # 2026-11-24: H6 on the SAME VM that ran K3P=sealed and K3P=train4 (out_sealed and out_train4 are local).
229
- # Trains a larger specialisation than F1 (head LoRA r256 + layer-92 tail LoRA r128 + LoRA on the 128 hottest routed
230
- # experts, incl. new ones when they are hot) on caches train2 + train3 + train4 (~3.2 M tokens), then judges it on the
231
- # sealed holdout against Trinity and the base model. Prereg: 16_EVIDENCE/TRINITY/H6_PREREG_2026-11-24.md.
232
- if MODE == "h6":
233
- import shutil
234
- from huggingface_hub import snapshot_download
235
- if not (W / "out_sealed" / "summary.json").exists():
236
- raise SystemExit("H6 needs out_sealed on this VM (run K3P=sealed first)")
237
- extra = [str(W / "out_train4")] if (W / "out_train4" / "summary.json").exists() else [] # train4 if this VM built it
238
- print("H6 caches: train2, train3" + (", train4" if extra else ""), flush=True)
239
- if (W / "work_train4").exists(): # regenerable work files: free the scratch disk
240
- shutil.rmtree((W / "work_train4").resolve(), ignore_errors=True)
241
- scratch = Path("/mnt/local-scratch") if Path("/mnt/local-scratch").exists() else W
242
- for m in ("train2", "train3"):
243
- dst = W / f"out_{m}"
244
- if not (dst / "summary.json").exists():
245
- dl = scratch / f"dl_{m}"
246
- snapshot_download(f"STAR-future/Trinity-k3cache-{m}", repo_type="dataset", token=TOK, allow_patterns=[f"{m}/*"],
247
- local_dir=str(dl), max_workers=8)
248
- if not dst.exists():
249
- dst.symlink_to(dl / m)
250
- if json.loads((dst / "summary.json").read_text()).get("layers_run") != 93:
251
- raise SystemExit(f"cache {m} is not a 93-layer pass")
252
- (W / "trinity_full_tail_wsp.py").write_bytes(Path(hf_hub_download(REPO, "tools/trinity_full_tail_wsp.py", token=TOK,
253
- force_download=True)).read_bytes())
254
- h6 = W / "h6"
255
- if not (h6 / "full_tail_wsp.pt").exists():
256
- rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "train", "--cache", str(W / "out_train2"),
257
- str(W / "out_train3"), *extra, "--out", str(h6), "--domains", "chips,space",
258
- "--head-rank", "256", "--head-alpha", "256", "--tail-rank", "128", "--tail-alpha", "128",
259
- "--k", "128", "--routed-rank", "16", "--routed-alpha", "16", "--lr", "1.5e-4", "--epochs", "3.0",
260
- "--kl", "6.0", "--block-size", "256"], "h6_train.log")
261
- if rc != 0:
262
- raise SystemExit(f"H6 training failed ({rc})")
263
- for f in h6.glob("*"):
264
- if f.is_file():
265
- api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h6/{f.name}", repo_id=REPO,
266
- commit_message=f"H6 trained specialisation: {f.name}")
267
- rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval", "--cache", str(W / "out_sealed"),
268
- "--trained", str(h6 / "full_tail_wsp.pt"), "--out", str(W / "h6_sealed")], "h6_sealed_eval.log")
269
- for f in (W / "h6_sealed").glob("*"):
270
- if f.is_file():
271
- api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h6_sealed/{f.name}", repo_id=REPO,
272
- commit_message=f"H6 sealed holdout: {f.name}")
273
- print("h6 sealed eval exit", rc, flush=True)
274
- if rc == 0 and os.environ.get("K3P_BPB", "1") != "0":
275
- os.environ["BPB_DIR"] = "h6_sealed"
276
- exec(open(hf_hub_download(REPO, "tools/colab_bpb_compare.py", token=TOK, force_download=True)).read())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Colab GPU cell driver for the LB-A / LB-B passes (k3pass.py) and the LB-B training/eval.
2
+
3
+ import os; os.environ['K3P'] = 'holdout' # or 'train', 'tail' (train + eval on existing caches)
4
+ from google.colab import userdata; import huggingface_hub as h; os.environ['HF_TOKEN'] = userdata.get('STARHUGGIN')
5
+ exec(open(h.hf_hub_download('STAR-future/Trinity', 'tools/colab_k3pass.py', token=os.environ['HF_TOKEN'],
6
+ force_download=True)).read())
7
+
8
+ holdout: Gemini's domain holdout pack (68 sequences) + Wikipedia articles 1-16, both models, cache of LittleBoy.
9
+ train: domain training corpus packed to >= 12,500 characters + Wikipedia articles 17-48, LittleBoy only, cache.
10
+ Caches and summaries are uploaded to the private LittleBoy repo under eval/ (NLL arrays, summaries, logs); the
11
+ per-token caches go to the private dataset STAR-future/Trinity-k3cache.
12
+ Since 2026-11-19 (two runtimes lost mid-pass, nothing saved): the log is uploaded every 10 minutes while the pass
13
+ runs, and the pass checkpoints its state every K3_CKPT layers to STAR-future/Trinity-k3ckpt-<mode>, so running the
14
+ same cell again on a fresh runtime resumes where the last checkpoint left off. tail refuses caches from passes that
15
+ did not run all 93 layers (the 5-layer smoke cache of 2026-11-19 must never feed a verdict).
16
+ """
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ import threading
22
+ from pathlib import Path
23
+
24
+ from huggingface_hub import HfApi, hf_hub_download
25
+
26
+ TOK = os.environ["HF_TOKEN"]
27
+ REPO = "STAR-future/Trinity"
28
+ CACHE = "STAR-future/Trinity-k3cache"
29
+ MODE = os.environ.get("K3P", "holdout")
30
+ 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
31
+ PUBLIC_TRAIN = ("train2", "train3") + V3_PARTS
32
+ if MODE in PUBLIC_TRAIN: # 2026-11-21: private quota is full; these caches are of public CC0 text, so they go public
33
+ CACHE = f"STAR-future/Trinity-k3cache-{MODE}"
34
+ W = Path("/content/k3p")
35
+ W.mkdir(parents=True, exist_ok=True)
36
+ # 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
37
+ # tokens). Colab A100 runtimes mount a 368 GB /mnt/local-scratch: put work and output there when it exists.
38
+ if Path("/mnt/local-scratch").exists() and MODE in ("train",) + PUBLIC_TRAIN:
39
+ for _n in (f"work_{MODE}", f"out_{MODE}"):
40
+ _t, _l = Path("/mnt/local-scratch") / _n, W / _n
41
+ _t.mkdir(parents=True, exist_ok=True)
42
+ if not _l.exists() and not _l.is_symlink():
43
+ _l.symlink_to(_t)
44
+ api = HfApi(token=TOK)
45
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tiktoken", "datasets"], check=True)
46
+ for f in ("k3ref.py", "k3pass.py", "lb_tail_train.py", "lb_tail_eval.py"):
47
+ (W / f).write_bytes(Path(hf_hub_download(REPO, f"tools/{f}", token=TOK, force_download=True)).read_bytes())
48
+ (W / "train_corpus_v1.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v1.jsonl", token=TOK,
49
+ force_download=True)).read_bytes())
50
+ if MODE in ("train2", "train3"): # domain corpus v2 (~10x v1, arXiv CC0 abstracts submitted before 2026-10-01)
51
+ (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,
52
+ force_download=True)).read_bytes())
53
+ if MODE in V3_PARTS:
54
+ (W / "train_corpus_v3.jsonl").write_bytes(Path(hf_hub_download(REPO, "eval/data/train_corpus_v3.jsonl", token=TOK,
55
+ force_download=True)).read_bytes())
56
+ # the holdout lives only in the PRIVATE cache dataset: holdouts are never published (moved there 2026-11-19)
57
+ (W / "k3stream_holdout_pack.jsonl").write_bytes(Path(hf_hub_download("STAR-future/Trinity-k3cache", "eval-data/k3stream_holdout_pack.jsonl",
58
+ repo_type="dataset", token=TOK,
59
+ force_download=True)).read_bytes())
60
+
61
+
62
+ def wiki(start, n):
63
+ from datasets import load_dataset
64
+ rows, k = [], 0
65
+ for r in load_dataset("wikimedia/wikipedia", "20231101.en", split="train", streaming=True):
66
+ if len(r["text"]) > 16000:
67
+ if k >= start:
68
+ rows.append(r)
69
+ k += 1
70
+ if len(rows) >= n:
71
+ return rows
72
+ return rows
73
+
74
+
75
+ def run(cmd, logname):
76
+ print(" ".join(cmd), flush=True)
77
+ log = W / logname
78
+ env = dict(os.environ, PYTHONPATH=str(W), PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True",
79
+ HF_HUB_DISABLE_PROGRESS_BARS="1")
80
+ stop = threading.Event()
81
+
82
+ def pusher(): # the log reaches the repo even if the runtime is lost
83
+ while not stop.wait(600):
84
+ try:
85
+ api.upload_file(path_or_fileobj=str(log), path_in_repo=f"eval/{logname}", repo_id=REPO,
86
+ commit_message=f"{logname} (running)")
87
+ except Exception as e: # noqa: BLE001
88
+ print("log upload failed", type(e).__name__, flush=True)
89
+ th = threading.Thread(target=pusher, daemon=True)
90
+ with subprocess.Popen(cmd, cwd=W, env=env, stdout=subprocess.PIPE,
91
+ stderr=subprocess.STDOUT, text=True, bufsize=1) as p, open(log, "w") as fo:
92
+ th.start()
93
+ for line in p.stdout:
94
+ print(line, end="", flush=True)
95
+ fo.write(line)
96
+ fo.flush()
97
+ stop.set()
98
+ api.upload_file(path_or_fileobj=str(log), path_in_repo=f"eval/{logname}", repo_id=REPO, commit_message=logname)
99
+ return p.returncode
100
+
101
+
102
+ def up(path, name):
103
+ if Path(path).exists():
104
+ api.upload_file(path_or_fileobj=str(path), path_in_repo=f"eval/{name}", repo_id=REPO, commit_message=name)
105
+
106
+
107
+ if MODE in ("holdout", "train") + PUBLIC_TRAIN:
108
+ rows = []
109
+ if MODE == "holdout":
110
+ for r in map(json.loads, (W / "k3stream_holdout_pack.jsonl").read_text(encoding="utf-8").splitlines()):
111
+ rows.append({"id": r["id"], "text": r["text"], "set": r["set"], "role": "holdout", "base": True})
112
+ for r in wiki(0, 16):
113
+ rows.append({"id": r["title"], "text": r["text"], "set": "wikipedia", "role": "holdout", "base": True})
114
+ else:
115
+ 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"
116
+ docs = [json.loads(x) for x in (W / cfile).read_text(encoding="utf-8").splitlines() if x.strip()]
117
+ ktok_pack = None
118
+ if MODE in V3_PARTS:
119
+ from transformers import AutoTokenizer
120
+ ktok_pack = AutoTokenizer.from_pretrained("moonshotai/Kimi-K3.1-Pro", trust_remote_code=True)
121
+ for dom in sorted({d["domain"] for d in docs}):
122
+ buf, k, est_tok = [], 0, 0
123
+ for d in sorted((d for d in docs if d["domain"] == dom), key=lambda d: d["id"]):
124
+ txt = d["text"].strip()
125
+ buf.append(txt)
126
+ if ktok_pack is not None:
127
+ est_tok += len(ktok_pack.encode(txt)) + (2 if len(buf) > 1 else 0)
128
+ ready = est_tok >= 2064 and len(ktok_pack.encode("\n\n".join(buf))) >= 2048
129
+ else:
130
+ ready = sum(len(b) for b in buf) >= 12500
131
+ if ready:
132
+ rows.append({"id": f"{MODE}_{dom}_{k:04d}", "text": "\n\n".join(buf), "set": f"train_{dom}",
133
+ "role": "train", "base": False})
134
+ buf, k, est_tok = [], k + 1, 0
135
+ if MODE in V3_PARTS: # stratified stride slice across chips+space+physics so train4 alone covers all 3 domains!
136
+ rows = rows[V3_PARTS.index(MODE)::len(V3_PARTS)]
137
+ 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)):
138
+ rows.append({"id": r["title"], "text": r["text"], "set": "general_wiki", "role": "train", "base": False})
139
+ texts = W / f"streams_{MODE}.jsonl"
140
+ texts.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
141
+ out = W / f"out_{MODE}"
142
+ import torch
143
+ gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
144
+ 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
145
+ raise SystemExit(f"GPU with {gpu_gb:.0f} GB: this pass needs an A100 (40/80 GB). Disconnect and retry later.")
146
+ import shutil as _sh
147
+ _work_dir = W / f"work_{MODE}"
148
+ _work_dir.mkdir(parents=True, exist_ok=True)
149
+ _n_streams = len(rows) * (2 if MODE == "holdout" else 1)
150
+ _req_gib = (_n_streams * 2048 * (232000 if MODE != "holdout" else 195000)) / (2 ** 30) + 46.0
151
+ _free_gib = _sh.disk_usage(os.path.realpath(_work_dir)).free / (2 ** 30)
152
+ if _free_gib < _req_gib and not os.environ.get("K3P_SKIP_DISK_GUARD"):
153
+ raise SystemExit(f"Insufficient scratch disk for {MODE}: free={_free_gib:.1f} GiB < required={_req_gib:.1f} GiB (check /mnt/local-scratch)!")
154
+ batch = os.environ.get("K3_BATCH", "12" if gpu_gb > 60 else ("8" if gpu_gb > 20 else "4"))
155
+ rc = run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(_work_dir),
156
+ "--out", str(out), "--batch", batch, "--layers", os.environ.get("K3_LAYERS", "-1"),
157
+ "--ckpt-repo", f"STAR-future/Trinity-k3ckpt-{MODE}", "--ckpt-every", os.environ.get("K3_CKPT", "6")],
158
+ f"k3pass_{MODE}.log")
159
+ print("exit", rc, flush=True)
160
+ up(out / "summary.json", f"k3pass_{MODE}_summary.json")
161
+ up(out / "nll.npy", f"k3pass_{MODE}_nll.npy")
162
+ up(out / "streams.json", f"k3pass_{MODE}_streams.json")
163
+ if rc == 0 and (out / "summary.json").exists(): # keep the per-token cache durable: private dataset
164
+ api.create_repo(CACHE, repo_type="dataset", private=MODE not in PUBLIC_TRAIN, exist_ok=True)
165
+ # FAIL-0092: one 98 GB upload_folder commit never finished before the Colab VM was recycled (24 h). One commit
166
+ # per file, retried, skipping what is already there, so every finished file survives a lost runtime.
167
+ have = set(api.list_repo_files(CACHE, repo_type="dataset"))
168
+ for f in sorted(p for p in out.iterdir() if p.suffix in (".npy", ".json")):
169
+ if f"{MODE}/{f.name}" in have:
170
+ continue
171
+ for attempt in range(5):
172
+ try:
173
+ api.upload_file(path_or_fileobj=str(f), path_in_repo=f"{MODE}/{f.name}", repo_id=CACHE, repo_type="dataset",
174
+ commit_message=f"k3pass cache {MODE}: {f.name}")
175
+ print("uploaded", f.name, round(f.stat().st_size / 2 ** 30, 2), "GiB", flush=True)
176
+ break
177
+ except Exception as e: # noqa: BLE001
178
+ print("upload retry", f.name, attempt, type(e).__name__, str(e)[:120], flush=True)
179
+ elif MODE == "tail":
180
+ from huggingface_hub import snapshot_download
181
+ for m in ("train", "holdout"):
182
+ if not (W / f"out_{m}" / "summary.json").exists():
183
+ snapshot_download(CACHE, repo_type="dataset", token=TOK, allow_patterns=[f"{m}/*"], local_dir=str(W / "cache_dl"))
184
+ (W / f"out_{m}").mkdir(exist_ok=True)
185
+ for f in (W / "cache_dl" / m).iterdir():
186
+ f.rename(W / f"out_{m}" / f.name)
187
+ lr = json.loads((W / f"out_{m}" / "summary.json").read_text()).get("layers_run")
188
+ if lr != 93:
189
+ raise SystemExit(f"cache {m} comes from a pass of {lr} layers, not 93: refusing to train or judge on it")
190
+ rc = run([sys.executable, "-u", str(W / "lb_tail_train.py"), "--cache", str(W / "out_train"),
191
+ "--out", str(W / "tail")], "lb_tail_train.log")
192
+ if rc == 0:
193
+ rc = run([sys.executable, "-u", str(W / "lb_tail_eval.py"), "--cache", str(W / "out_holdout"),
194
+ "--trained", str(W / "tail" / "layer92_trained.pt"), "--out", str(W / "tail" / "verdict.json")],
195
+ "lb_tail_eval.log")
196
+ up(W / "tail" / "verdict.json", "lb_tail_verdict.json")
197
+ up(W / "tail" / "verdict.raw.npz", "lb_tail_verdict.raw.npz")
198
+ up(W / "tail" / "train_record.json", "lb_tail_train_record.json")
199
+ up(W / "tail" / "layer92_trained.pt", "layer92_trained.pt")
200
+
201
+
202
+ # 2026-11-24: confirmatory evaluation of a trained specialisation on the SEALED holdout (61 sequences, Gemini custody,
203
+ # sha256 9d174d3f...). The texts come only from the private dataset; Trinity and the base model both run (base=True);
204
+ # no checkpoints and no cache upload (private quota is full and the cache stays on this VM); only aggregate verdict
205
+ # and per-token losses (numbers, no text) are published under eval/h5_sealed/.
206
+ if MODE == "sealed":
207
+ import torch
208
+ gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
209
+ if gpu_gb < 39 and not os.environ.get("K3P_ALLOW_SMALL_GPU"):
210
+ raise SystemExit(f"GPU with {gpu_gb:.0f} GB: this pass needs an A100 (40/80 GB). Disconnect and retry later.")
211
+ src = Path(hf_hub_download("STAR-future/Trinity-k3cache", "eval-data/sealed_h2_holdout_61.jsonl", repo_type="dataset",
212
+ token=TOK, force_download=True))
213
+ import hashlib as _h
214
+ if _h.sha256(src.read_bytes()).hexdigest() != "9d174d3fc71accb0001cdab2a4293cfdd44663ff573362735cbe8956d2580dad":
215
+ raise SystemExit("sealed holdout file does not match its sealed sha256")
216
+ rows = []
217
+ for r in map(json.loads, src.read_text(encoding="utf-8").splitlines()):
218
+ st = "wikipedia" if r["set"].startswith("general") else r["set"].replace("h2_", "")
219
+ rows.append({"id": r["id"], "text": r["text"], "set": st, "role": "holdout", "base": True})
220
+ texts = W / "streams_sealed.jsonl"
221
+ texts.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
222
+ out = W / "out_sealed"
223
+ if not (out / "summary.json").exists():
224
+ rc = run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(W / "work_sealed"),
225
+ "--out", str(out), "--batch", "12" if gpu_gb > 60 else "8", "--layers", "-1",
226
+ "--ckpt-repo", "STAR-future/Trinity-k3ckpt-sealed", "--ckpt-every", "999"], "k3pass_sealed.log")
227
+ print("pass exit", rc, flush=True)
228
+ if json.loads((out / "summary.json").read_text()).get("layers_run") != 93:
229
+ raise SystemExit("sealed pass did not run all 93 layers: no verdict")
230
+ trained = os.environ.get("K3P_TRAINED", "eval/h4/F1_Arm3_HeadLoRA_full_tail_wsp.pt")
231
+ tp = Path(hf_hub_download(REPO, trained, token=TOK, force_download=True))
232
+ (W / "trinity_full_tail_wsp.py").write_bytes(Path(hf_hub_download(REPO, "tools/trinity_full_tail_wsp.py", token=TOK,
233
+ force_download=True)).read_bytes())
234
+ rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval", "--cache", str(out), "--trained", str(tp),
235
+ "--out", str(W / "h5_sealed")], "h5_sealed_eval.log")
236
+ for f in (W / "h5_sealed").glob("*"):
237
+ if f.is_file():
238
+ api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h5_sealed/{f.name}", repo_id=REPO,
239
+ commit_message=f"H5 sealed holdout: {f.name}")
240
+ up(out / "summary.json", "h5_sealed/k3pass_sealed_summary.json")
241
+ print("sealed eval exit", rc, flush=True)
242
+ if rc == 0 and os.environ.get("K3P_BPB", "1") != "0": # bits-per-byte comparison with open models, same VM
243
+ exec(open(hf_hub_download(REPO, "tools/colab_bpb_compare.py", token=TOK, force_download=True)).read())
244
+
245
+
246
+ # 2026-11-24: H6 on the SAME VM that ran K3P=sealed and K3P=train4 (out_sealed and out_train4 are local).
247
+ # Trains a larger specialisation than F1 (head LoRA r256 + layer-92 tail LoRA r128 + LoRA on the 128 hottest routed
248
+ # experts, incl. new ones when they are hot) on caches train2 + train3 + train4 (~3.2 M tokens), then judges it on the
249
+ # sealed holdout against Trinity and the base model. Prereg: 16_EVIDENCE/TRINITY/H6_PREREG_2026-11-24.md.
250
+ if MODE == "h6":
251
+ import shutil
252
+ from huggingface_hub import snapshot_download
253
+ if not (W / "out_sealed" / "summary.json").exists():
254
+ raise SystemExit("H6 needs out_sealed on this VM (run K3P=sealed first)")
255
+ for wtmp in ("work_train4", "work_sealed"): # free BOTH scratch (~172 GiB) AND boot disk (~38 GiB)!
256
+ if (W / wtmp).exists() or (W / wtmp).is_symlink():
257
+ shutil.rmtree((W / wtmp).resolve(), ignore_errors=True)
258
+ if (W / wtmp).is_symlink():
259
+ (W / wtmp).unlink(missing_ok=True)
260
+ scratch = Path("/mnt/local-scratch") if Path("/mnt/local-scratch").exists() else W
261
+ xet_tmp = scratch / "hf_xet_tmp" # prevent hf-xet from filling 236 GiB boot disk ~/.cache!
262
+ os.environ["HF_XET_CACHE"] = str(xet_tmp)
263
+ extra = [str(W / "out_train4")] if (W / "out_train4" / "summary.json").exists() else [] # train4 if this VM built it
264
+ print("H6 caches: train2, train3" + (", train4" if extra else ""), flush=True)
265
+ for m in ("train2", "train3"):
266
+ dst = W / f"out_{m}"
267
+ if not (dst / "summary.json").exists():
268
+ dl = scratch / f"dl_{m}"
269
+ snapshot_download(f"STAR-future/Trinity-k3cache-{m}", repo_type="dataset", token=TOK, allow_patterns=[f"{m}/*"],
270
+ local_dir=str(dl), cache_dir=str(scratch / "hf_cache"), max_workers=8)
271
+ shutil.rmtree(xet_tmp, ignore_errors=True)
272
+ if dst.is_symlink():
273
+ dst.unlink()
274
+ if not dst.exists():
275
+ dst.symlink_to(dl / m)
276
+ if json.loads((dst / "summary.json").read_text()).get("layers_run") != 93:
277
+ raise SystemExit(f"cache {m} is not a 93-layer pass")
278
+ (W / "trinity_full_tail_wsp.py").write_bytes(Path(hf_hub_download(REPO, "tools/trinity_full_tail_wsp.py", token=TOK,
279
+ force_download=True)).read_bytes())
280
+ h6 = W / "h6"
281
+ h6_doms = os.environ.get("H6_DOMAINS", "chips,space,physics")
282
+ if not (h6 / "full_tail_wsp.pt").exists():
283
+ rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "train", "--cache", str(W / "out_train2"),
284
+ str(W / "out_train3"), *extra, "--out", str(h6), "--domains", h6_doms,
285
+ "--head-rank", "256", "--head-alpha", "256", "--tail-rank", "128", "--tail-alpha", "128",
286
+ "--k", "128", "--include-new-experts", "--routed-rank", "16", "--routed-alpha", "16",
287
+ "--skip-prefix-tokens", "2", "--lr", "1.5e-4", "--epochs", "3.0",
288
+ "--kl", "6.0", "--block-size", "256"], "h6_train.log")
289
+ if rc != 0:
290
+ raise SystemExit(f"H6 training failed ({rc})")
291
+ for f in h6.glob("*"):
292
+ if f.is_file():
293
+ api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h6/{f.name}", repo_id=REPO,
294
+ commit_message=f"H6 trained specialisation: {f.name}")
295
+ rc = run([sys.executable, "-u", str(W / "trinity_full_tail_wsp.py"), "eval", "--cache", str(W / "out_sealed"),
296
+ "--trained", str(h6 / "full_tail_wsp.pt"), "--out", str(W / "h6_sealed")], "h6_sealed_eval.log")
297
+ for f in (W / "h6_sealed").glob("*"):
298
+ if f.is_file():
299
+ api.upload_file(path_or_fileobj=str(f), path_in_repo=f"eval/h6_sealed/{f.name}", repo_id=REPO,
300
+ commit_message=f"H6 sealed holdout: {f.name}")
301
+ print("h6 sealed eval exit", rc, flush=True)
302
+ if rc == 0 and os.environ.get("K3P_BPB", "1") != "0":
303
+ os.environ["BPB_DIR"] = "h6_sealed"
304
+ exec(open(hf_hub_download(REPO, "tools/colab_bpb_compare.py", token=TOK, force_download=True)).read())