AbstractPhil commited on
Commit
fcb613e
Β·
verified Β·
1 Parent(s): b3d3979

Create trainer_v2.py

Browse files
Files changed (1) hide show
  1. trainer_v2.py +1361 -0
trainer_v2.py ADDED
@@ -0,0 +1,1361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # CAPTIONBERT-8192-v2 β€” CONSENSUS DISTILLATION AT CC12M SCALE
3
+ #
4
+ # v2 vs the shipped 500k model, per Phil's 2026-07-31 guidance:
5
+ # - NO ALIGNMENT BANK. v1's bank was additive and experimental; measured on real
6
+ # embeddings its expert-consistency block varied 0.2% across samples and took
7
+ # 0.23% of geo_proj energy while anchor distances took 98.7%. Banks in this
8
+ # format are content extensions β€” an AMOE-LORA is the right carrier, attached
9
+ # as a separate finetune pass on the prefitted core. Not here.
10
+ # - LEGROOM. d 384->512, 6L->12L, ff 1536->2048, heads 6->8. 26.0M -> 58.3M
11
+ # (0.53x bert-base, so the compression story survives). Sized for many
12
+ # overlapping sources at ~36M features/teacher, not one 500k census.
13
+ # - CHAMPION OBJECTIVE. InfoNCE + per-sample MSE against the consensus β€” the
14
+ # consensus_nce_mse form that won the CC12M vision matrix on every task gauge,
15
+ # both seeds. NO shipped rotation needed here: that line aligns to a running
16
+ # mean (frame free), this one aligns to a REFERENCE MEMBER (bert), so the frame
17
+ # is pinned by construction. A frame-fit gauge runs anyway to confirm it.
18
+ # - CULL-PROOF. Colab kills the VM every 24h and takes local disk with it.
19
+ # Full state (model/opt/sched/scaler/step/epoch/chunk-order/RNG) checkpoints on
20
+ # a TIME cadence, and pushes to HF so a cull costs minutes, not the run.
21
+ # - FULL TENSORBOARD. per-step losses + lr + grad-norm, per-eval gauges
22
+ # (mimicry, cos, isotropy, effective rank, CV), histograms, and the alignment
23
+ # report as text.
24
+ #
25
+ # STAGES (each resumable, each gated) β€” carried from the cc12m pipeline:
26
+ # 0 PARITY which caption field was embedded + row alignment. Hard gate.
27
+ # 1 FIT one global whitened-Procrustes map per expert -> bert, stratified
28
+ # random fit, reported OUT-OF-SAMPLE on held-out chunks.
29
+ # 2 TARGETS per-chunk consensus -> fp16, ledgered, expert shards deleted after.
30
+ # 3 TRAIN streams (captions, consensus) pairs, dynamic padding.
31
+ #
32
+ # Colab-cell-safe. HF_TOKEN from Colab secrets (key icon) or env.
33
+ # ============================================================================
34
+
35
+ import dataclasses, gc, json, math, os, random, sys, time, subprocess, shutil
36
+ import dataclasses
37
+ from dataclasses import dataclass, asdict
38
+ from typing import Any, Dict, List, Optional, Tuple
39
+
40
+ for _p in ("datasets", "transformers", "huggingface_hub", "tensorboard", "safetensors"):
41
+ try:
42
+ __import__(_p)
43
+ except ImportError:
44
+ subprocess.run([sys.executable, "-m", "pip", "install", "-q", _p], check=False)
45
+
46
+ # Variable-length batches fragment the caching allocator badly; this is the
47
+ # documented mitigation and must be set BEFORE torch initialises CUDA.
48
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
49
+
50
+ import numpy as np
51
+ import torch
52
+ import torch.nn as nn
53
+ import torch.nn.functional as F
54
+ from huggingface_hub import hf_hub_download, HfApi, create_repo
55
+ from torch.utils.tensorboard import SummaryWriter
56
+
57
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
58
+
59
+
60
+ # ══════════════════════════════════════════════════════════════════
61
+ # BASE CONFIG
62
+ # ══════════════════════════════════════════════════════════════════
63
+
64
+ @dataclass
65
+ class BaseConfig:
66
+ # ================= EDIT THESE THREE, THEN PASTE =================
67
+ # The cell AUTO-RUNS on paste, so the stage flags below are DERIVED from
68
+ # this profile inside run() -- they are not yours to set by hand, and
69
+ # setting them after pasting is too late.
70
+ # "full" everything from scratch, including the alignment fit
71
+ # "retrain" NEW trunk on an EXISTING corpus: reuse maps + targets,
72
+ # train from step 0 <-- the -b shape
73
+ # "continue" pick up an interrupted run of the SAME job
74
+ # "targets" rebuild consensus targets only
75
+ profile: str = "retrain"
76
+ run_name: str = "captionbert-8192-b"
77
+ hf_repo: str = "AbstractPhil/captionbert-8192-v2-B"
78
+ # ================================================================
79
+
80
+ # ── sources ── (list so overlapping datasets can be added later)
81
+ sources: Tuple[Dict[str, Any], ...] = (
82
+ {"repo": "AbstractPhil/conceptual-captions-12m-webdataset-berts",
83
+ "n_chunks": 66, "chunk_rows": 500_000,
84
+ # REPAIRED 2026-08-02 and gate-verified: the 10 chunks ModernBERT was
85
+ # missing now reproduce at cos 1.00000 / min 1.00000 against a re-embed
86
+ # (same field, row order, mean pooling, truncation). 66/66 complete,
87
+ # so nothing is excluded. Repopulate this only if a gate FAILS.
88
+ "missing": {}},
89
+ )
90
+ experts: Tuple[str, ...] = ("bert", "modern", "roberta", "albert", "distil")
91
+ ref_expert: str = "bert"
92
+ ref_hf_name: str = "google-bert/bert-base-uncased"
93
+ require_all_experts: bool = True
94
+ caption_field: Optional[str] = None
95
+ caption_field_candidates: Tuple[str, ...] = (
96
+ "caption_llava", "caption", "caption_llava_short")
97
+
98
+ work_dir: str = "/content/cbv2"
99
+ keep_expert_shards: bool = False
100
+
101
+ # ── hardware allowance (Colab Pro+ / RTX 6000 Pro, measured 2026-07-31) ──
102
+ # disk 235.7GB (~176 free) | RAM 176.9GB | GPU 95.6GB | 401.5 units @ 8.9/h = 45.1h
103
+ # The expert shards are 507GB β€” 2.1x the WHOLE DISK. They are streamed one chunk
104
+ # at a time and deleted; only the 43GB consensus is kept.
105
+ disk_floor_gb: float = 25.0 # abort a chunk if free disk drops below
106
+ ram_resident: bool = True # hold tokens+targets in RAM (48.8GB)
107
+ preflight: bool = True
108
+
109
+ # ── backup (Colab culls at 24h; local disk dies with the VM) ──
110
+ # where SKIPPED stages fetch their outputs from. Distinct from hf_repo:
111
+ # a new run publishes somewhere new but still reads the ORIGINAL maps.
112
+ artifact_repo: str = "AbstractPhil/captionbert-8192-v2"
113
+ targets_repo: str = "AbstractPhil/captionbert-8192-v2-consensus"
114
+ push_targets: bool = True # 43GB; re-derivable only from a 507GB pull
115
+ hf_push: bool = True
116
+ push_every_min: float = 30.0
117
+ keep_local_ckpts: int = 3
118
+
119
+ # ── stage 0 ──
120
+ parity_chunk: int = 0
121
+ parity_n: int = 64
122
+ parity_min_cos: float = 0.999
123
+
124
+ # ── stage 1 ──
125
+ fit_chunks: Tuple[int, ...] = (0, 11, 22, 33, 44, 55)
126
+ fit_rows_per_chunk: int = 4000 # 24k vs d=768 -> N/d = 31
127
+ holdout_chunks: Tuple[int, ...] = (60, 61)
128
+ fit_seed: int = 0
129
+
130
+ # ── student (LEGROOM) ──
131
+ d_model: int = 512 # was 384
132
+ n_heads: int = 8 # was 6
133
+ n_layers: int = 12 # was 6
134
+ d_ff: int = 2048 # was 1536
135
+ max_len: int = 8192 # name-bearing; costs 4.2M params
136
+ output_dim: int = 768 # consensus space = teacher dim
137
+ dropout: float = 0.1
138
+ pooling: str = "mean" # arm: "cls". teachers are mean-pooled
139
+ max_tokens: int = 256 # dynamic pad ceiling
140
+ # OOM FIX (2026-07-31, observed at B=2048): dynamic padding pads to the BATCH
141
+ # max, and with 2048 draws the max is essentially always the ceiling. The corpus
142
+ # mean is 48 tokens but every batch ran at L=256 -- attention memory goes as L^2,
143
+ # so 12 layers needed ~120 GB against 95 available.
144
+ # length_bucketing sorts within a shuffled window so a batch is length-
145
+ # homogeneous: L tracks the corpus mean (~48-64) instead of
146
+ # the ceiling. ~5x less memory AND ~5x less compute.
147
+ # grad_checkpointing bounds the worst case. The longest bucket IS a full batch
148
+ # at L=256; checkpointing puts that at ~19 GB instead of
149
+ # ~148 GB, for about 30% more compute.
150
+ length_bucketing: bool = True
151
+ bucket_window: int = 64 # batches per sort window
152
+ grad_checkpointing: bool = True
153
+ vram_probe: bool = True # forward+backward at worst case first
154
+
155
+ # ── training (sized for 95.6GB GPU: batch size IS the InfoNCE negative count) ──
156
+ epochs: int = 4 # 13.7k steps/ep at 2048 -> ~55k total
157
+ batch_size: int = 2048 # was 512; ~19GB activations, 4x negatives
158
+ lr: float = 6e-4 # sqrt-scaled from 3e-4 @ 512
159
+ min_lr: float = 1e-6
160
+ warmup_steps: int = 2000
161
+ grad_clip: float = 1.0
162
+ seed: int = 42
163
+ amp: bool = True
164
+ num_workers: int = 0 # RAM-resident: no workers needed
165
+ log_every: int = 50
166
+ eval_every: int = 1000
167
+ ckpt_every_min: float = 20.0 # TIME-based: culls are wall-clock
168
+
169
+ # ---- RESUME SAFETY ----
170
+ # fresh_start=True: never look for a checkpoint, never pull one from the hub,
171
+ # start at step 0. Set it whenever the CORPUS or the ARCHITECTURE changed.
172
+ # Why this exists: a completed run's state.pt carries epoch=epochs, so
173
+ # `for ep in range(ep0, cfg.epochs)` is an EMPTY RANGE -- the job builds the
174
+ # whole RamStore, trains ZERO steps, prints the previous run's final metrics
175
+ # and pushes them as if they were new. It then uploads that state to the new
176
+ # repo, so the next attempt inherits it too. Measured on 2026-08-02.
177
+ fresh_start: bool = False
178
+ # even with resume on, a checkpoint is REJECTED when the row count or the
179
+ # run name disagrees with the current job. Set True only to override.
180
+ allow_mismatched_resume: bool = False
181
+
182
+ # ── loss: the champion form ──
183
+ nce_weight: float = 1.0
184
+ mse_weight: float = 1.0
185
+ nce_temperature: float = 0.07
186
+ cv_weight: float = 0.0 # arm: 0.1 reproduces the v1 stack
187
+ cv_target: float = 0.084
188
+
189
+ # ── stages ──
190
+ run_stage0: bool = True
191
+ run_stage1: bool = True
192
+ run_stage2: bool = True
193
+ run_stage3: bool = True
194
+ resume: bool = True
195
+
196
+
197
+ CFG = BaseConfig()
198
+
199
+
200
+ # ══════════════════════════════════════════════════════════════════
201
+ # HELPERS
202
+ # ══════════════════════════════════════════════════════════════════
203
+
204
+ def line(t=""):
205
+ print("─" * 78 if not t else f"── {t} " + "─" * max(0, 74 - len(t)))
206
+
207
+
208
+ def paths(cfg) -> Dict[str, str]:
209
+ w = cfg.work_dir
210
+ d = {"root": w, "targets": f"{w}/targets", "maps": f"{w}/maps",
211
+ "ckpt": f"{w}/checkpoints", "tb": f"{w}/tensorboard", "shards": f"{w}/shards",
212
+ "config": f"{w}/config"}
213
+ for p in d.values():
214
+ os.makedirs(p, exist_ok=True)
215
+ return d
216
+
217
+
218
+ def src0(cfg) -> Dict[str, Any]:
219
+ return cfg.sources[0]
220
+
221
+
222
+ def usable_chunks(cfg) -> List[int]:
223
+ s = src0(cfg)
224
+ c = set(range(s["n_chunks"]))
225
+ if cfg.require_all_experts:
226
+ for miss in s.get("missing", {}).values():
227
+ c -= set(miss)
228
+ return sorted(c - set(cfg.holdout_chunks))
229
+
230
+
231
+ def fetch(cfg, fname: str) -> str:
232
+ return hf_hub_download(src0(cfg)["repo"], fname, repo_type="dataset",
233
+ local_dir=paths(cfg)["shards"])
234
+
235
+
236
+ def load_captions_chunk(cfg, c: int) -> List[str]:
237
+ raw = json.load(open(fetch(cfg, f"captions_{c:03d}.json")))
238
+ f = cfg.caption_field
239
+ if isinstance(raw, dict):
240
+ return list(raw[f])
241
+ if raw and isinstance(raw[0], dict):
242
+ return [r[f] for r in raw]
243
+ return list(raw)
244
+
245
+
246
+ def load_expert_chunk(cfg, expert: str, c: int) -> torch.Tensor:
247
+ return torch.load(fetch(cfg, f"{expert}_{c:03d}.pt"),
248
+ weights_only=True, map_location="cpu")
249
+
250
+
251
+ def drop_shard(cfg, fname: str):
252
+ if cfg.keep_expert_shards:
253
+ return
254
+ p = os.path.join(paths(cfg)["shards"], fname)
255
+ if os.path.exists(p):
256
+ os.remove(p)
257
+
258
+
259
+ def free_gb(path: str) -> float:
260
+ st = os.statvfs(path)
261
+ return st.f_bavail * st.f_frsize / 1e9
262
+
263
+
264
+ def purge_hf_cache(cfg):
265
+ """
266
+ The expert shards total 507GB against a 235.7GB disk. hf_hub_download with
267
+ local_dir does not populate the global cache on modern hub versions, but a
268
+ stale HF_HOME cache or an older version WILL duplicate every shard and blow
269
+ the disk mid-run. Purge both, every chunk.
270
+ """
271
+ for d in (os.path.join(paths(cfg)["shards"], ".cache"),
272
+ os.environ.get("HF_HUB_CACHE", ""),
273
+ os.path.expanduser("~/.cache/huggingface/hub")):
274
+ if d and os.path.isdir(d):
275
+ for entry in os.listdir(d):
276
+ if entry.startswith("datasets--"):
277
+ shutil.rmtree(os.path.join(d, entry), ignore_errors=True)
278
+
279
+
280
+ PROFILES = {
281
+ # sentinel: the profile has already been applied, do not re-derive
282
+ "_applied": {},
283
+ # everything from scratch, including the alignment fit
284
+ "full": dict(run_stage0=True, run_stage1=True, run_stage2=True,
285
+ run_stage3=True, fresh_start=True),
286
+ # NEW TRUNK on an EXISTING corpus: reuse the maps and the consensus targets,
287
+ # train from step 0. This is the captionbert-8192-b shape.
288
+ "retrain": dict(run_stage0=False, run_stage1=False, run_stage2=False,
289
+ run_stage3=True, fresh_start=True,
290
+ caption_field="caption_llava"),
291
+ # pick up an interrupted run of the SAME job
292
+ "continue": dict(run_stage0=False, run_stage1=False, run_stage2=False,
293
+ run_stage3=True, fresh_start=False,
294
+ caption_field="caption_llava"),
295
+ # rebuild targets only (e.g. after repairing missing expert shards)
296
+ "targets": dict(run_stage0=False, run_stage1=False, run_stage2=True,
297
+ run_stage3=False, fresh_start=True,
298
+ caption_field="caption_llava"),
299
+ }
300
+
301
+
302
+ def configure(cfg, profile, **over):
303
+ """Apply a coherent flag set, validate, return. '_applied' is a no-op."""
304
+ """
305
+ One call that sets a COHERENT set of flags, then applies overrides.
306
+ Validates the result and raises rather than starting a run that cannot work.
307
+ """
308
+ import dataclasses
309
+ if profile not in PROFILES:
310
+ raise ValueError(f"profile must be one of {sorted(PROFILES)}")
311
+ if profile == "_applied":
312
+ return dataclasses.replace(cfg, **over) if over else cfg
313
+ cfg = dataclasses.replace(cfg, **{**PROFILES[profile], **over})
314
+ line(f"PROFILE '{profile}'")
315
+ for k in ("run_name", "hf_repo", "artifact_repo", "targets_repo",
316
+ "caption_field", "fresh_start"):
317
+ print(f" {k:16s} {getattr(cfg, k)}")
318
+ print(f" stages 0:{cfg.run_stage0} 1:{cfg.run_stage1} "
319
+ f"2:{cfg.run_stage2} 3:{cfg.run_stage3}")
320
+ bad = []
321
+ if not cfg.run_stage0 and not cfg.caption_field:
322
+ bad.append("stage0 off but caption_field is unset")
323
+ if cfg.run_stage1 and not cfg.run_stage2:
324
+ bad.append("REFITTING the maps while REUSING targets built with the old "
325
+ "map -- the targets would sit in a different frame")
326
+ if cfg.run_stage3 and not (cfg.run_stage2 or cfg.targets_repo):
327
+ bad.append("stage3 needs targets: build them or set targets_repo")
328
+ if cfg.hf_repo == cfg.artifact_repo and cfg.fresh_start and cfg.run_stage3:
329
+ print(f" !! publishing to the SAME repo the artifacts come from. Fine")
330
+ print(f" !! for a continuation; for a NEW trunk set hf_repo elsewhere.")
331
+ if bad:
332
+ raise RuntimeError("incoherent config:\n - " + "\n - ".join(bad))
333
+ print(" config coherent")
334
+ return cfg
335
+
336
+
337
+ def ensure_artifacts(cfg):
338
+ """
339
+ Skipping a stage means its outputs come from the hub, NOT from local disk.
340
+
341
+ Colab wipes local disk every session, so `run_stage1=False` cannot mean
342
+ "the maps are already in /content" -- it has to mean "fetch the maps".
343
+ Same for the consensus targets. Without this, skipping a stage either
344
+ crashes on a missing file or, worse, silently re-derives an artifact that
345
+ must NOT be re-derived: a refit alignment map lands in a different frame
346
+ than the 66 target files that were built with the original, and nothing in
347
+ the loss reveals it.
348
+ """
349
+ P = paths(cfg)
350
+ line("ARTIFACTS")
351
+
352
+ if not cfg.run_stage1:
353
+ mp = f"{P['maps']}/alignment_maps.pt"
354
+ if os.path.exists(mp):
355
+ print(f" maps: local {mp}")
356
+ else:
357
+ src = hf_hub_download(cfg.artifact_repo, "maps/alignment_maps.pt")
358
+ shutil.copy(src, mp)
359
+ print(f" maps: fetched {cfg.artifact_repo}/maps/alignment_maps.pt")
360
+ try:
361
+ fr = hf_hub_download(cfg.artifact_repo, "maps/fit_report.json")
362
+ shutil.copy(fr, f"{P['maps']}/fit_report.json")
363
+ except Exception:
364
+ pass
365
+ print(" (NOT refitting: every consensus target was built with THIS map;")
366
+ print(" a new fit would sit in a different frame with no loss signal.)")
367
+
368
+ if not cfg.run_stage2:
369
+ want = sorted(set(usable_chunks(cfg)) | set(cfg.holdout_chunks))
370
+ have, pulled, miss = [], [], []
371
+ for c in want:
372
+ dst = f"{P['targets']}/consensus_{c:03d}.pt"
373
+ if os.path.exists(dst):
374
+ have.append(c); continue
375
+ try:
376
+ src = hf_hub_download(cfg.targets_repo, f"consensus_{c:03d}.pt",
377
+ repo_type="dataset")
378
+ if os.path.islink(dst) or os.path.exists(dst):
379
+ os.remove(dst)
380
+ os.symlink(src, dst) # no second 49GB copy
381
+ pulled.append(c)
382
+ except Exception:
383
+ miss.append(c)
384
+ if (len(pulled) % 10 == 0) and pulled:
385
+ print(f" targets: {len(have)+len(pulled)}/{len(want)} ...")
386
+ print(f" targets: {len(have)} local + {len(pulled)} fetched "
387
+ f"from {cfg.targets_repo}")
388
+ if miss:
389
+ raise RuntimeError(
390
+ f"targets missing for chunks {miss} in {cfg.targets_repo}. "
391
+ f"Either build them (run_stage2=True, which needs the expert "
392
+ f"shards) or drop those chunks from the run.")
393
+ print()
394
+
395
+
396
+ def preflight(cfg):
397
+ """Hard-check the allowance before anything expensive starts."""
398
+ line("PREFLIGHT β€” disk / RAM / GPU vs the plan")
399
+ P = paths(cfg)
400
+ disk = free_gb(P["root"])
401
+ s = src0(cfg)
402
+ n_keep = len(usable_chunks(cfg)) + len(cfg.holdout_chunks)
403
+ rows = n_keep * s["chunk_rows"]
404
+ targets_gb = rows * cfg.output_dim * 2 / 1e9
405
+ transient_gb = len(cfg.experts) * 1.536
406
+ caps_gb = s["n_chunks"] * 0.120
407
+ need = targets_gb + caps_gb + transient_gb + 10.0
408
+ print(f" source on HF : {s['n_chunks'] * len(cfg.experts) * 1.536:.0f} GB expert shards "
409
+ f"(streamed one chunk at a time, deleted after)")
410
+ print(f" disk free : {disk:.1f} GB | stage-2 peak need β‰ˆ {need:.1f} GB "
411
+ f"(targets {targets_gb:.1f} + captions {caps_gb:.1f} + transient {transient_gb:.1f})")
412
+ if disk < need:
413
+ raise RuntimeError(
414
+ f"DISK: {disk:.1f} GB free, need β‰ˆ {need:.1f} GB. Free space, reduce chunks, "
415
+ f"or set push_targets=True and drop consensus locally after each push.")
416
+ try:
417
+ import psutil
418
+ ram = psutil.virtual_memory().total / 1e9
419
+ except Exception:
420
+ ram = float("nan")
421
+ ram_need = (rows * 100 * 2 + rows * 8 + rows * cfg.output_dim * 2) / 1e9
422
+ print(f" RAM total : {ram:.1f} GB | ram_resident need β‰ˆ {ram_need:.1f} GB "
423
+ f"(ragged tokens + offsets + fp16 targets)")
424
+ if cfg.ram_resident and ram == ram and ram_need > 0.7 * ram:
425
+ print(f" !! ram_resident wants {ram_need:.1f} GB of {ram:.1f}. "
426
+ f"Set ram_resident=False to stream per chunk from disk instead.")
427
+ if DEVICE == "cuda":
428
+ g = torch.cuda.get_device_properties(0).total_memory / 1e9
429
+ print(f" GPU : {torch.cuda.get_device_name()} {g:.1f} GB | "
430
+ f"batch {cfg.batch_size} -> {cfg.batch_size} InfoNCE negatives")
431
+ print(f" plan : {rows:,} rows, {rows // cfg.batch_size:,} steps/epoch "
432
+ f"x {cfg.epochs} = {rows // cfg.batch_size * cfg.epochs:,} steps")
433
+
434
+
435
+ def effective_rank(x: torch.Tensor) -> float:
436
+ xc = (x - x.mean(0, keepdim=True)).double()
437
+ s2 = torch.linalg.svdvals(xc) ** 2
438
+ return float((s2.sum() ** 2 / (s2 ** 2).sum()).item())
439
+
440
+
441
+ def hf_token() -> Optional[str]:
442
+ t = os.environ.get("HF_TOKEN")
443
+ if t:
444
+ return t
445
+ try:
446
+ from google.colab import userdata
447
+ return userdata.get("HF_TOKEN")
448
+ except Exception:
449
+ return None
450
+
451
+
452
+ # ══════════════════════════════════════════════════════════════════
453
+ # BACKUP β€” a Colab cull must cost minutes, not the run
454
+ # ══════════════════════════════════════════════════════════════════
455
+
456
+ class Backup:
457
+ def __init__(self, cfg):
458
+ self.cfg, self.api, self.ok, self.last = cfg, None, False, 0.0
459
+ if not cfg.hf_push:
460
+ return
461
+ tok = hf_token()
462
+ if not tok:
463
+ print(" [backup] no HF_TOKEN β€” LOCAL ONLY. A cull will lose the run.")
464
+ return
465
+ try:
466
+ create_repo(cfg.hf_repo, token=tok, exist_ok=True, private=True)
467
+ self.api = HfApi(token=tok)
468
+ self.ok = True
469
+ print(f" [backup] -> {cfg.hf_repo} (private)")
470
+ except Exception as e:
471
+ print(f" [backup] disabled: {type(e).__name__}: {str(e)[:100]}")
472
+
473
+ def push(self, force: bool = False, msg: str = "checkpoint"):
474
+ if not self.ok:
475
+ return
476
+ if not force and (time.time() - self.last) / 60 < self.cfg.push_every_min:
477
+ return
478
+ P = paths(self.cfg)
479
+ try:
480
+ for folder, dest in ((P["ckpt"], "checkpoints"), (P["tb"], "tensorboard"),
481
+ (P["maps"], "maps"), (P["config"], "config")):
482
+ if os.path.isdir(folder) and os.listdir(folder):
483
+ self.api.upload_folder(folder_path=folder, path_in_repo=dest,
484
+ repo_id=self.cfg.hf_repo,
485
+ commit_message=f"{msg} ({dest})")
486
+ self.last = time.time()
487
+ print(f" [backup] pushed ({msg})")
488
+ except Exception as e:
489
+ print(f" [backup] push failed: {type(e).__name__}: {str(e)[:100]}")
490
+
491
+ def pull_latest(self) -> Optional[str]:
492
+ """Recover state.pt after a cull."""
493
+ if not self.ok:
494
+ return None
495
+ try:
496
+ p = hf_hub_download(self.cfg.hf_repo, "checkpoints/state.pt",
497
+ token=hf_token(), local_dir=paths(self.cfg)["root"])
498
+ print(f" [backup] recovered {p}")
499
+ return p
500
+ except Exception:
501
+ return None
502
+
503
+
504
+ # ══════════════════════════════════════════════════════════════════
505
+ # STAGE 0 β€” PARITY GATE
506
+ # ══════════════════════════════════════════════════════════════════
507
+
508
+ def stage0_parity(cfg) -> str:
509
+ """
510
+ Which caption field was embedded, and is row i of <expert>_XXX.pt caption i?
511
+ The manifest names three fields and does not say which was used. If the stored
512
+ vectors came from caption_llava and the student trains on caption_llava_short,
513
+ every target is silently wrong. Re-embed with the real reference model, demand
514
+ cos ~ 1.0. Nothing downstream runs until this passes.
515
+ """
516
+ from transformers import AutoModel, AutoTokenizer
517
+ line("STAGE 0 β€” PARITY GATE (caption field + row alignment)")
518
+ stored = load_expert_chunk(cfg, cfg.ref_expert, cfg.parity_chunk)[: cfg.parity_n].float()
519
+ raw = json.load(open(fetch(cfg, f"captions_{cfg.parity_chunk:03d}.json")))
520
+ if isinstance(raw, dict):
521
+ fields = {k: list(v)[: cfg.parity_n] for k, v in raw.items()
522
+ if k in cfg.caption_field_candidates}
523
+ elif raw and isinstance(raw[0], dict):
524
+ fields = {k: [r[k] for r in raw[: cfg.parity_n]]
525
+ for k in raw[0] if k in cfg.caption_field_candidates}
526
+ else:
527
+ fields = {"(flat)": list(raw[: cfg.parity_n])}
528
+ print(f" stored rows {tuple(stored.shape)} | fields {list(fields)}")
529
+
530
+ tok = AutoTokenizer.from_pretrained(cfg.ref_hf_name)
531
+ mdl = AutoModel.from_pretrained(cfg.ref_hf_name).to(DEVICE).eval()
532
+ best, best_cos = None, -1.0
533
+ for f, texts in fields.items():
534
+ with torch.no_grad():
535
+ inp = tok(list(texts), max_length=512, padding=True, truncation=True,
536
+ return_tensors="pt").to(DEVICE)
537
+ h = mdl(**inp).last_hidden_state
538
+ m = inp.attention_mask.unsqueeze(-1).float()
539
+ pooled = ((h * m).sum(1) / m.sum(1).clamp(min=1)).float().cpu()
540
+ cos = F.cosine_similarity(pooled, stored, dim=-1)
541
+ print(f" {f:22s} cos mean {cos.mean():.6f} min {cos.min():.6f}")
542
+ if cos.mean().item() > best_cos:
543
+ best, best_cos = f, cos.mean().item()
544
+ del mdl; gc.collect(); torch.cuda.empty_cache()
545
+ if best_cos < cfg.parity_min_cos:
546
+ raise RuntimeError(
547
+ f"PARITY GATE FAIL: best field '{best}' only reaches cos {best_cos:.6f} "
548
+ f"(need >= {cfg.parity_min_cos}). Either the field is not among "
549
+ f"{cfg.caption_field_candidates}, row order differs, or the extraction used "
550
+ f"different pooling/truncation. DO NOT SPEND GPU TIME until this resolves.")
551
+ print(f" GATE PASS: field = '{best}' at cos {best_cos:.6f}")
552
+ return best
553
+
554
+
555
+ # ══════════════════════════════════════════════════════════════════
556
+ # STAGE 1 β€” GLOBAL WHITENED PROCRUSTES (out-of-sample reported)
557
+ # ══════════════════════════════════════════════════════════════════
558
+
559
+ def symmetric_inv_sqrt(cov: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
560
+ ev, evec = torch.linalg.eigh(cov.double())
561
+ return (evec @ torch.diag(torch.clamp(ev, min=eps).rsqrt()) @ evec.T).float()
562
+
563
+
564
+ def fit_map(S: torch.Tensor, T: torch.Tensor) -> Dict[str, torch.Tensor]:
565
+ N = S.shape[0]
566
+ s_mean, t_mean = S.mean(0, keepdim=True), T.mean(0, keepdim=True)
567
+ Sc, Tc = S - s_mean, T - t_mean
568
+ s_w = symmetric_inv_sqrt((Sc.T @ Sc) / max(N - 1, 1))
569
+ t_w = symmetric_inv_sqrt((Tc.T @ Tc) / max(N - 1, 1))
570
+ U, _, Vt = torch.linalg.svd(
571
+ (F.normalize(Tc @ t_w, dim=-1).T @ F.normalize(Sc @ s_w, dim=-1)).double(),
572
+ full_matrices=False)
573
+ return {"rotation": (U @ Vt).float(), "source_mean": s_mean.squeeze(0),
574
+ "target_mean": t_mean.squeeze(0), "source_whitener": s_w,
575
+ "target_whitener": t_w, "target_unwhitener": torch.linalg.pinv(t_w)}
576
+
577
+
578
+ def apply_map(emb: torch.Tensor, a) -> torch.Tensor:
579
+ x = (emb.float() - a["source_mean"]) @ a["source_whitener"]
580
+ return (x @ a["rotation"].T) @ a["target_unwhitener"]
581
+
582
+
583
+ def score_map(S, T, a) -> Dict[str, float]:
584
+ Sw = F.normalize((S - a["source_mean"]) @ a["source_whitener"], dim=-1)
585
+ Tw = F.normalize((T - a["target_mean"]) @ a["target_whitener"], dim=-1)
586
+ cos = F.cosine_similarity(Sw @ a["rotation"].T, Tw, dim=-1).mean().item()
587
+ n = min(2000, S.shape[0])
588
+ sim = F.normalize(apply_map(S[:n], a), dim=-1) @ F.normalize(T[:n], dim=-1).T
589
+ return {"cos": cos, "r1": (sim.argmax(1) == torch.arange(n)).float().mean().item(),
590
+ "n": int(S.shape[0]), "chance": 1.0 / n}
591
+
592
+
593
+ def stage1_fit(cfg, bk: "Backup"):
594
+ line("STAGE 1 β€” GLOBAL ALIGNMENT (stratified fit, OUT-OF-SAMPLE report)")
595
+ P = paths(cfg)
596
+ mp = f"{P['maps']}/alignment_maps.pt"
597
+ if os.path.exists(mp):
598
+ print(" maps exist, loading"); return torch.load(mp, weights_only=False)
599
+
600
+ g = torch.Generator().manual_seed(cfg.fit_seed)
601
+ fit = {e: [] for e in cfg.experts}
602
+ for c in cfg.fit_chunks:
603
+ idx = None
604
+ for e in cfg.experts:
605
+ X = load_expert_chunk(cfg, e, c)
606
+ if idx is None:
607
+ idx = torch.randperm(X.shape[0], generator=g)[: cfg.fit_rows_per_chunk]
608
+ fit[e].append(X[idx].float()); del X; gc.collect()
609
+ drop_shard(cfg, f"{e}_{c:03d}.pt")
610
+ print(f" fit chunk {c:03d}: {len(idx)} random rows")
611
+ fit = {e: torch.cat(v) for e, v in fit.items()}
612
+ N = fit[cfg.ref_expert].shape[0]
613
+ print(f" fit set {N} rows, d=768 -> N/d = {N/768:.1f}")
614
+
615
+ hold = {e: [] for e in cfg.experts}
616
+ for c in cfg.holdout_chunks:
617
+ for e in cfg.experts:
618
+ X = load_expert_chunk(cfg, e, c)
619
+ hold[e].append(X[: cfg.fit_rows_per_chunk].float()); del X; gc.collect()
620
+ hold = {e: torch.cat(v) for e, v in hold.items()}
621
+
622
+ maps, report, T = {}, {}, fit[cfg.ref_expert]
623
+ for e in cfg.experts:
624
+ a = fit_map(fit[e], T)
625
+ ins, oos = score_map(fit[e], T, a), score_map(hold[e], hold[cfg.ref_expert], a)
626
+ maps[e], report[e] = a, {"in_sample": ins, "out_of_sample": oos}
627
+ tag = " (ref: must read ~1.0)" if e == cfg.ref_expert else ""
628
+ print(f" {e:9s} cos in {ins['cos']:.4f} / OUT {oos['cos']:.4f} "
629
+ f"R@1 in {ins['r1']:.4f} / OUT {oos['r1']:.4f} "
630
+ f"(chance {oos['chance']:.5f}){tag}")
631
+ print(" READ THE 'OUT' COLUMN. A 768x768 rotation is 294,528 free parameters;")
632
+ print(" at low N/d the in-sample cosine reproduces strong numbers from nothing.")
633
+ torch.save(maps, mp)
634
+ json.dump(report, open(f"{P['maps']}/fit_report.json", "w"), indent=2)
635
+ bk.push(force=True, msg="stage1 alignment maps")
636
+ return maps
637
+
638
+
639
+ # ══════════════════════════════════════════════════════════════════
640
+ # STAGE 2 β€” CONSENSUS TARGETS
641
+ # ══════════════════════════════════════════════════════════════════
642
+
643
+ def stage2_targets(cfg, maps, bk: "Backup") -> List[int]:
644
+ line("STAGE 2 β€” CONSENSUS TARGETS (fp16, per chunk, resumable)")
645
+ P = paths(cfg)
646
+ lp = f"{P['targets']}/ledger.json"
647
+ ledger = json.load(open(lp)) if os.path.exists(lp) else {}
648
+ want = sorted(set(usable_chunks(cfg)) | set(cfg.holdout_chunks))
649
+ print(f" {len(want)} chunks with all {len(cfg.experts)} experts | "
650
+ f"streaming {len(want)*len(cfg.experts)*1.536:.0f} GB through "
651
+ f"{free_gb(P['root']):.0f} GB of free disk")
652
+ tapi = None
653
+ if cfg.push_targets and bk.ok:
654
+ try:
655
+ create_repo(cfg.targets_repo, token=hf_token(), exist_ok=True,
656
+ private=True, repo_type="dataset")
657
+ tapi = HfApi(token=hf_token())
658
+ print(f" targets -> {cfg.targets_repo} (dataset, private)")
659
+ except Exception as e:
660
+ print(f" target push disabled: {type(e).__name__}: {str(e)[:80]}")
661
+ for c in want:
662
+ k, out_p = f"{c:03d}", f"{P['targets']}/consensus_{c:03d}.pt"
663
+ if ledger.get(k) and os.path.exists(out_p):
664
+ continue
665
+ if free_gb(P["root"]) < cfg.disk_floor_gb:
666
+ raise RuntimeError(f"DISK FLOOR: {free_gb(P['root']):.1f} GB free at chunk {k}. "
667
+ f"Push and drop earlier consensus files, then resume.")
668
+ acc, n = None, None
669
+ for e in cfg.experts:
670
+ X = load_expert_chunk(cfg, e, c).float()
671
+ if n is None:
672
+ n = X.shape[0]
673
+ elif X.shape[0] != n:
674
+ raise RuntimeError(f"chunk {k}: {e} has {X.shape[0]} rows, expected {n}")
675
+ A = apply_map(X, maps[e])
676
+ acc = A if acc is None else acc + A
677
+ del X, A; gc.collect()
678
+ drop_shard(cfg, f"{e}_{c:03d}.pt")
679
+ purge_hf_cache(cfg)
680
+ cons = F.normalize(acc / len(cfg.experts), dim=-1).half()
681
+ torch.save(cons, out_p)
682
+ er = effective_rank(cons[:4000].float())
683
+ ledger[k] = {"rows": int(cons.shape[0]), "target_erank": er, "ts": time.time()}
684
+ json.dump(ledger, open(lp, "w"), indent=2)
685
+ if tapi is not None:
686
+ try:
687
+ tapi.upload_file(path_or_fileobj=out_p,
688
+ path_in_repo=f"consensus_{k}.pt",
689
+ repo_id=cfg.targets_repo, repo_type="dataset",
690
+ commit_message=f"consensus chunk {k}")
691
+ except Exception as ex:
692
+ print(f" target push failed for {k}: {str(ex)[:70]}")
693
+ print(f" chunk {k}: {cons.shape[0]} targets | TARGET erank {er:.1f}/768 | "
694
+ f"disk free {free_gb(P['root']):.0f} GB")
695
+ del acc, cons; gc.collect()
696
+ eranks = [v["target_erank"] for v in ledger.values() if "target_erank" in v]
697
+ if eranks:
698
+ print(f" consensus target erank: mean {np.mean(eranks):.1f} "
699
+ f"min {min(eranks):.1f} max {max(eranks):.1f} of 768")
700
+ print(" (v1's STUDENT read 23.6 β€” compare against this to tell 'student")
701
+ print(" collapsed' from 'student faithfully matched a low-rank target')")
702
+ bk.push(force=True, msg="stage2 target ledger")
703
+ return want
704
+
705
+
706
+ # ══════════════════════════════════════════════════════════════════
707
+ # STUDENT
708
+ # ══════════════════════════════════════════════════════════════════
709
+
710
+ class CaptionEncoder(nn.Module):
711
+ """Standalone caption encoder. No experts at inference. No bank."""
712
+
713
+ def __init__(self, vocab_size=30522, max_len=8192, d_model=512, n_heads=8,
714
+ n_layers=12, d_ff=2048, output_dim=768, dropout=0.1,
715
+ pad_token_id=0, pooling="mean", grad_checkpointing=False):
716
+ super().__init__()
717
+ self.pad_token_id, self.pooling = pad_token_id, pooling
718
+ self.grad_checkpointing = grad_checkpointing
719
+ self.token_emb = nn.Embedding(vocab_size, d_model, padding_idx=pad_token_id)
720
+ self.pos_emb = nn.Embedding(max_len, d_model)
721
+ self.emb_norm = nn.LayerNorm(d_model)
722
+ self.emb_drop = nn.Dropout(dropout)
723
+ layer = nn.TransformerEncoderLayer(
724
+ d_model=d_model, nhead=n_heads, dim_feedforward=d_ff, dropout=dropout,
725
+ activation="gelu", batch_first=True, norm_first=True)
726
+ self.encoder = nn.TransformerEncoder(layer, num_layers=n_layers,
727
+ enable_nested_tensor=False)
728
+ self.output_proj = nn.Sequential(
729
+ nn.Linear(d_model, d_model), nn.GELU(), nn.LayerNorm(d_model),
730
+ nn.Linear(d_model, output_dim))
731
+
732
+ def forward(self, input_ids, attention_mask=None):
733
+ L = input_ids.shape[1]
734
+ pos = torch.arange(L, device=input_ids.device).unsqueeze(0)
735
+ x = self.emb_drop(self.emb_norm(self.token_emb(input_ids) + self.pos_emb(pos)))
736
+ kpm = (~attention_mask.bool()) if attention_mask is not None \
737
+ else (input_ids == self.pad_token_id)
738
+ if self.grad_checkpointing and self.training:
739
+ for layer in self.encoder.layers:
740
+ x = torch.utils.checkpoint.checkpoint(
741
+ layer, x, None, kpm, use_reentrant=False)
742
+ else:
743
+ x = self.encoder(x, src_key_padding_mask=kpm)
744
+ if self.pooling == "cls":
745
+ pooled = x[:, 0]
746
+ else:
747
+ m = (attention_mask.unsqueeze(-1).float() if attention_mask is not None
748
+ else (~kpm).unsqueeze(-1).float())
749
+ pooled = (x * m).sum(1) / m.sum(1).clamp(min=1)
750
+ return F.normalize(self.output_proj(pooled), dim=-1)
751
+
752
+
753
+ # ══════════════════════════════════════════════════════════════════
754
+ # LOSS / GAUGES
755
+ # ══════════════════════════════════════════════════════════════════
756
+
757
+ def infonce(a, b, temperature=0.07):
758
+ logits = (a @ b.T) / temperature
759
+ lab = torch.arange(logits.shape[0], device=logits.device)
760
+ loss = (F.cross_entropy(logits, lab) + F.cross_entropy(logits.T, lab)) / 2
761
+ with torch.no_grad():
762
+ acc = (logits.argmax(-1) == lab).float().mean().item()
763
+ return loss, acc
764
+
765
+
766
+ def cayley_menger_vol2(pts):
767
+ pts = pts.float()
768
+ d = pts.unsqueeze(-2) - pts.unsqueeze(-3)
769
+ d2 = (d * d).sum(-1)
770
+ B, V, _ = d2.shape
771
+ cm = torch.zeros(B, V + 1, V + 1, device=d2.device, dtype=torch.float32)
772
+ cm[:, 0, 1:] = 1; cm[:, 1:, 0] = 1; cm[:, 1:, 1:] = d2
773
+ f = math.factorial(V - 1)
774
+ return ((-1.0) ** V) / ((2.0 ** (V - 1)) * f * f) * torch.linalg.det(cm)
775
+
776
+
777
+ def cv_loss(emb, target=0.084, n_samples=16):
778
+ B = emb.shape[0]
779
+ if B < 5:
780
+ return torch.zeros((), device=emb.device)
781
+ s = torch.stack([torch.sqrt(F.relu(cayley_menger_vol2(
782
+ emb[torch.randperm(B, device=emb.device)[:5]].unsqueeze(0))[0]) + 1e-12)
783
+ for _ in range(n_samples)])
784
+ return (s.std() / (s.mean() + 1e-8) - target).abs()
785
+
786
+
787
+ @torch.no_grad()
788
+ def cv_metric(emb, n=200):
789
+ v = [float(torch.sqrt(F.relu(cayley_menger_vol2(
790
+ emb[torch.randperm(emb.shape[0], device=emb.device)[:5]].unsqueeze(0))[0])
791
+ + 1e-12).item()) for _ in range(n)]
792
+ a = np.array([x for x in v if x > 0])
793
+ return float(a.std() / (a.mean() + 1e-8)) if len(a) >= 10 else 0.0
794
+
795
+
796
+ @torch.no_grad()
797
+ def frame_fit_gauge(E: torch.Tensor, T: torch.Tensor, n_pairs: int = 2500) -> Dict[str, float]:
798
+ """
799
+ Standing rider: judge relational objectives with a frame fit or they read as false
800
+ floors. MSE anchors the frame here and the consensus aligns to a REFERENCE MEMBER,
801
+ so a rotation should buy ~nothing. If it buys a lot, the frame is NOT pinned and
802
+ this model needs a shipped rotation after all. Held-out split, fp64.
803
+ """
804
+ N = E.shape[0]
805
+ k = min(n_pairs, N // 2)
806
+ if k < 64:
807
+ return {"skipped": True}
808
+ perm = torch.randperm(N, generator=torch.Generator().manual_seed(0))
809
+ fit_i, hold_i = perm[:k], perm[k:]
810
+ U, _, Vt = torch.linalg.svd(E[fit_i].double().T @ T[fit_i].double(), full_matrices=False)
811
+ Er = F.normalize((E.double() @ (U @ Vt)).float(), dim=-1)
812
+ m = min(2000, len(hold_i))
813
+ hi = hold_i[:m]
814
+ sim = Er[hi] @ T[hi].T
815
+ return {"r1_after_rotation": (sim.argmax(1) == torch.arange(m)).float().mean().item(),
816
+ "cos_after_rotation": F.cosine_similarity(Er[hi], T[hi], dim=-1).mean().item(),
817
+ "n_heldout": int(m)}
818
+
819
+
820
+ # ══════════════════════════════════════════════════════════════════
821
+ # DATA
822
+ # ══════════════════════════════════════════════════════════════════
823
+
824
+ class RamStore:
825
+ """
826
+ Everything resident in system RAM: ragged uint16 tokens + fp16 targets.
827
+
828
+ On the Pro+ box this is 48.8 GB of 176.9 β€” so the training loop does ZERO disk
829
+ I/O and needs no DataLoader workers. Ragged storage (flat token buffer + offsets)
830
+ keeps dynamic padding available at ~5.6 GB instead of the 14 GB a fixed 256-token
831
+ matrix would cost, and captions average ~100 tokens against a 256 ceiling.
832
+ """
833
+
834
+ def __init__(self, cfg, chunks: List[int], tokenizer, tag=""):
835
+ self.cfg, self.tok = cfg, tokenizer
836
+ self.pad = tokenizer.pad_token_id
837
+ flat, offs, tgts, total = [], [0], [], 0
838
+ for c in chunks:
839
+ caps = load_captions_chunk(cfg, c)
840
+ t = torch.load(f"{paths(cfg)['targets']}/consensus_{c:03d}.pt",
841
+ weights_only=True, map_location="cpu")
842
+ n = min(len(caps), t.shape[0])
843
+ caps, t = caps[:n], t[:n]
844
+ for i in range(0, n, 20000):
845
+ enc = tokenizer(caps[i:i + 20000], max_length=cfg.max_tokens,
846
+ truncation=True, padding=False)["input_ids"]
847
+ for ids in enc:
848
+ flat.append(np.asarray(ids, dtype=np.uint16))
849
+ total += len(ids)
850
+ offs.append(total)
851
+ tgts.append(t)
852
+ print(f" chunk {c:03d}: {n:,} rows | flat tokens {total/1e6:.1f}M")
853
+ del caps, t; gc.collect()
854
+ self.flat = np.concatenate(flat) if flat else np.zeros(0, np.uint16)
855
+ del flat; gc.collect()
856
+ self.offs = np.asarray(offs, dtype=np.int64)
857
+ self.tgt = torch.cat(tgts)
858
+ del tgts; gc.collect()
859
+ self.n = len(self.offs) - 1
860
+ self.lens = (self.offs[1:] - self.offs[:-1]).astype(np.int32)
861
+ gb = (self.flat.nbytes + self.offs.nbytes + self.tgt.numel() * 2) / 1e9
862
+ mean_len = total / max(self.n, 1)
863
+ q = np.percentile(self.lens, [50, 90, 99, 100]).astype(int)
864
+ print(f" RamStore{tag}: {self.n:,} rows | {gb:.1f} GB RAM | "
865
+ f"mean {mean_len:.0f} tokens (ceiling {cfg.max_tokens})")
866
+ print(f" length p50 {q[0]} | p90 {q[1]} | p99 {q[2]} | max {q[3]}"
867
+ f" -- unbucketed, a batch pads to the BATCH MAX, i.e. ~{q[3]}")
868
+
869
+ def plan_batches(self, batch_size, seed, window_batches=64, bucket=True):
870
+ """
871
+ Deterministic batch plan for one epoch. Returns a list of index arrays.
872
+
873
+ With bucket=True: shuffle, cut into windows of window_batches*batch_size,
874
+ sort each window by length, slice into batches, then shuffle the BATCH ORDER.
875
+ Batches end up length-homogeneous (so padding is near-free) while batch
876
+ composition stays random across the window and the model never sees the
877
+ corpus in length order. Deterministic in (seed), so a resume mid-epoch
878
+ regenerates the identical plan and the stored batch index stays valid.
879
+ """
880
+ rng = np.random.default_rng(seed)
881
+ perm = rng.permutation(self.n)
882
+ if not bucket:
883
+ n_full = self.n // batch_size
884
+ return [perm[i * batch_size:(i + 1) * batch_size] for i in range(n_full)]
885
+ W = batch_size * max(window_batches, 1)
886
+ batches = []
887
+ for i in range(0, self.n, W):
888
+ win = perm[i:i + W]
889
+ win = win[np.argsort(self.lens[win], kind="stable")]
890
+ for j in range(0, len(win) - batch_size + 1, batch_size):
891
+ batches.append(win[j:j + batch_size])
892
+ rng.shuffle(batches)
893
+ return batches
894
+
895
+ def __len__(self):
896
+ return self.n
897
+
898
+ def batch(self, idx: np.ndarray):
899
+ """Gather a batch with DYNAMIC padding to the batch max."""
900
+ seqs = [self.flat[self.offs[i]:self.offs[i + 1]] for i in idx]
901
+ L = max(len(s) for s in seqs)
902
+ ids = np.full((len(seqs), L), self.pad, dtype=np.int64)
903
+ am = np.zeros((len(seqs), L), dtype=np.int64)
904
+ for r, s in enumerate(seqs):
905
+ ids[r, :len(s)] = s
906
+ am[r, :len(s)] = 1
907
+ return (torch.from_numpy(ids), torch.from_numpy(am),
908
+ self.tgt[torch.from_numpy(idx)])
909
+
910
+
911
+ class ChunkPairs(torch.utils.data.Dataset):
912
+ """Disk-streaming fallback when ram_resident=False."""
913
+ def __init__(self, cfg, chunk, tokenizer):
914
+ self.caps = load_captions_chunk(cfg, chunk)
915
+ self.tgt = torch.load(f"{paths(cfg)['targets']}/consensus_{chunk:03d}.pt",
916
+ weights_only=True, map_location="cpu")
917
+ n = min(len(self.caps), self.tgt.shape[0])
918
+ self.caps, self.tgt = self.caps[:n], self.tgt[:n]
919
+ self.tok, self.max_tokens = tokenizer, cfg.max_tokens
920
+
921
+ def __len__(self):
922
+ return len(self.caps)
923
+
924
+ def __getitem__(self, i):
925
+ return self.caps[i], self.tgt[i]
926
+
927
+ def collate(self, batch):
928
+ texts, tg = zip(*batch)
929
+ enc = self.tok(list(texts), max_length=self.max_tokens, padding=True,
930
+ truncation=True, return_tensors="pt") # DYNAMIC
931
+ return enc["input_ids"], enc["attention_mask"], torch.stack(tg)
932
+
933
+
934
+ @torch.no_grad()
935
+ def evaluate(student, source, cap=5000, batch=512) -> Dict[str, float]:
936
+ student.eval()
937
+ E, T = [], []
938
+ if isinstance(source, RamStore):
939
+ for i in range(0, min(cap, len(source)), batch):
940
+ ids, am, tg = source.batch(np.arange(i, min(i + batch, len(source))))
941
+ E.append(student(ids.to(DEVICE), am.to(DEVICE)).float().cpu())
942
+ T.append(tg.float())
943
+ else:
944
+ for ids, am, tg in source:
945
+ E.append(student(ids.to(DEVICE), am.to(DEVICE)).float().cpu())
946
+ T.append(tg.float())
947
+ if sum(x.shape[0] for x in E) >= cap:
948
+ break
949
+ E, T = torch.cat(E), F.normalize(torch.cat(T), dim=-1)
950
+ n = min(2000, E.shape[0])
951
+ sim = E[:n] @ T[:n].T
952
+ ss = E[:n] @ E[:n].T
953
+ ss.fill_diagonal_(0)
954
+ out = {"mimicry_r1": (sim.argmax(1) == torch.arange(n)).float().mean().item(),
955
+ "cos_to_target": F.cosine_similarity(E, T, dim=-1).mean().item(),
956
+ "self_cos": ss.mean().item(),
957
+ "erank": effective_rank(E),
958
+ "cv": cv_metric(E[:2000].to(DEVICE)),
959
+ "n": int(E.shape[0])}
960
+ out.update({f"frame_{k}": v for k, v in frame_fit_gauge(E, T).items()})
961
+ student.train()
962
+ return out
963
+
964
+
965
+ # ══════════════════════════════════════════════════════════════════
966
+ # STAGE 3 β€” TRAIN (cull-proof)
967
+ # ══════════════════════════════════════════════════════════════════
968
+
969
+ def vram_probe(cfg, student):
970
+ """
971
+ One forward+backward at the WORST case (full batch at the pad ceiling) before
972
+ any data is loaded. With bucketing the longest bucket really is a full batch at
973
+ max_tokens, so this is the case that decides whether the run survives -- and it
974
+ is far cheaper to discover here than 20 minutes into a RamStore build.
975
+ """
976
+ if DEVICE != "cuda":
977
+ return
978
+ line("VRAM PROBE - worst-case batch before spending time on data")
979
+ torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
980
+ total = torch.cuda.get_device_properties(0).total_memory / 1e9
981
+ ids = torch.randint(1, 30000, (cfg.batch_size, cfg.max_tokens), device=DEVICE)
982
+ am = torch.ones_like(ids)
983
+ tgt = F.normalize(torch.randn(cfg.batch_size, cfg.output_dim, device=DEVICE), dim=-1)
984
+ opt = torch.optim.Adam(student.parameters(), lr=1e-9)
985
+ try:
986
+ student.train()
987
+ with torch.amp.autocast("cuda", enabled=cfg.amp):
988
+ emb = student(ids, am)
989
+ emb = emb.float()
990
+ loss = infonce(emb, tgt, cfg.nce_temperature)[0] + F.mse_loss(emb, tgt)
991
+ loss.backward()
992
+ opt.zero_grad(set_to_none=True)
993
+ peak = torch.cuda.max_memory_allocated() / 1e9
994
+ print(f" batch {cfg.batch_size} x L {cfg.max_tokens} "
995
+ f"(checkpointing={cfg.grad_checkpointing}) -> peak {peak:.1f} GB "
996
+ f"of {total:.1f} GB")
997
+ if peak > 0.85 * total:
998
+ print(" !! within 15% of the limit. Reduce batch_size or max_tokens,")
999
+ print(" !! or set grad_checkpointing=True, before starting the run.")
1000
+ else:
1001
+ ok = (total - peak)
1002
+ print(f" PASS - {ok:.1f} GB headroom")
1003
+ except torch.cuda.OutOfMemoryError:
1004
+ torch.cuda.empty_cache()
1005
+ raise RuntimeError(
1006
+ f"VRAM PROBE FAILED at batch {cfg.batch_size} x L {cfg.max_tokens} "
1007
+ f"(checkpointing={cfg.grad_checkpointing}). Options, cheapest first: "
1008
+ f"grad_checkpointing=True; lower max_tokens (corpus mean is ~48); "
1009
+ f"halve batch_size (costs InfoNCE negatives). Nothing was loaded, so "
1010
+ f"changing the config and re-running is quick.")
1011
+ finally:
1012
+ del ids, am, tgt, opt
1013
+ torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
1014
+
1015
+
1016
+ def save_state(cfg, path, student, opt, sched, scaler, step, epoch, chunk_i,
1017
+ order, best, n_rows=None):
1018
+ torch.save({"run_name": cfg.run_name, "n_rows": n_rows,
1019
+ "model": student.state_dict(), "opt": opt.state_dict(),
1020
+ "sched": sched.state_dict(), "scaler": scaler.state_dict(),
1021
+ "step": step, "epoch": epoch, "chunk_i": chunk_i, "order": order,
1022
+ "best": best, "config": asdict(cfg),
1023
+ "rng": {"torch": torch.get_rng_state(), "np": np.random.get_state(),
1024
+ "py": random.getstate()}}, path)
1025
+
1026
+
1027
+ def stage3_train(cfg, chunks: List[int], bk: "Backup"):
1028
+ from transformers import AutoTokenizer
1029
+ line("STAGE 3 β€” TRAIN")
1030
+ P = paths(cfg)
1031
+ torch.manual_seed(cfg.seed); np.random.seed(cfg.seed); random.seed(cfg.seed)
1032
+ tok = AutoTokenizer.from_pretrained(cfg.ref_hf_name)
1033
+ json.dump(asdict(cfg), open(f"{P['config']}/config.json", "w"), indent=2, default=str)
1034
+
1035
+ student = CaptionEncoder(
1036
+ vocab_size=tok.vocab_size, max_len=cfg.max_len, d_model=cfg.d_model,
1037
+ n_heads=cfg.n_heads, n_layers=cfg.n_layers, d_ff=cfg.d_ff,
1038
+ output_dim=cfg.output_dim, dropout=cfg.dropout,
1039
+ pad_token_id=tok.pad_token_id, pooling=cfg.pooling,
1040
+ grad_checkpointing=cfg.grad_checkpointing).to(DEVICE)
1041
+ n_par = sum(p.numel() for p in student.parameters())
1042
+ train_chunks = [c for c in chunks if c not in cfg.holdout_chunks]
1043
+ rows = len(train_chunks) * src0(cfg)["chunk_rows"]
1044
+ spe = rows // cfg.batch_size
1045
+ total = spe * cfg.epochs
1046
+ print(f" {cfg.run_name}: {n_par:,} params ({n_par/109_482_240:.2f}x bert-base)")
1047
+ print(f" {cfg.n_layers}L {cfg.d_model}d {cfg.n_heads}h ff{cfg.d_ff} pool={cfg.pooling}")
1048
+ print(f" {len(train_chunks)} chunks β‰ˆ {rows:,} rows | {spe:,} steps/ep x "
1049
+ f"{cfg.epochs} = {total:,} steps @ batch {cfg.batch_size}")
1050
+ print(f" loss = {cfg.nce_weight}*InfoNCE(T={cfg.nce_temperature}) + "
1051
+ f"{cfg.mse_weight}*MSE + {cfg.cv_weight}*CV [champion consensus_nce_mse]")
1052
+
1053
+ if cfg.vram_probe:
1054
+ vram_probe(cfg, student)
1055
+
1056
+ opt = torch.optim.Adam(student.parameters(), lr=cfg.lr) # pure Adam, no wd
1057
+ sched = torch.optim.lr_scheduler.SequentialLR(
1058
+ opt, [torch.optim.lr_scheduler.LinearLR(opt, 0.01, 1.0, cfg.warmup_steps),
1059
+ torch.optim.lr_scheduler.CosineAnnealingLR(
1060
+ opt, T_max=max(total - cfg.warmup_steps, 1), eta_min=cfg.min_lr)],
1061
+ milestones=[cfg.warmup_steps])
1062
+ scaler = torch.amp.GradScaler(enabled=cfg.amp and DEVICE == "cuda")
1063
+ tb = SummaryWriter(log_dir=f"{P['tb']}/{cfg.run_name}")
1064
+ tb.add_text("config", f"```json\n{json.dumps(asdict(cfg), indent=2, default=str)}\n```")
1065
+ if os.path.exists(f"{P['maps']}/fit_report.json"):
1066
+ tb.add_text("alignment/fit_report",
1067
+ f"```json\n{open(f'{P['maps']}/fit_report.json').read()}\n```")
1068
+
1069
+ # expected row count, known before any store is built: the identity gate
1070
+ # needs something to compare against and must run BEFORE the RamStore is
1071
+ # assembled (that build is the expensive part this failure wasted).
1072
+ n_rows_now = len(train_chunks) * src0(cfg)["chunk_rows"]
1073
+
1074
+ step, ep0, chunk_i0, best = 0, 0, 0, -1.0
1075
+ st, order = None, None
1076
+ sp = f"{P['ckpt']}/state.pt"
1077
+ if cfg.fresh_start:
1078
+ print(" fresh_start=True -- ignoring any local or remote checkpoint")
1079
+ if cfg.resume and not cfg.fresh_start:
1080
+ if not os.path.exists(sp):
1081
+ bk.pull_latest()
1082
+ alt = f"{P['root']}/checkpoints/state.pt"
1083
+ if os.path.exists(alt) and alt != sp:
1084
+ shutil.copy(alt, sp)
1085
+ if os.path.exists(sp):
1086
+ st = torch.load(sp, weights_only=False, map_location=DEVICE)
1087
+ # IDENTITY GATE. A checkpoint is only resumable into the job that
1088
+ # produced it. Missing fields mean a pre-gate checkpoint, which is
1089
+ # exactly the v2-into-B case this was written for -- reject it.
1090
+ why = []
1091
+ if st.get("run_name") != cfg.run_name:
1092
+ why.append(f"run_name {st.get('run_name')!r} != {cfg.run_name!r}")
1093
+ if st.get("n_rows") is None:
1094
+ why.append("checkpoint predates the identity gate (no n_rows)")
1095
+ elif st["n_rows"] != n_rows_now:
1096
+ why.append(f"n_rows {st['n_rows']:,} != {n_rows_now:,}")
1097
+ if st.get("epoch", 0) >= cfg.epochs:
1098
+ why.append(f"already finished ({st['epoch']}/{cfg.epochs} epochs) "
1099
+ f"-- resuming would train ZERO steps")
1100
+ if why and not cfg.allow_mismatched_resume:
1101
+ print(" RESUME REJECTED:")
1102
+ for w in why:
1103
+ print(f" - {w}")
1104
+ print(" Starting fresh. Set allow_mismatched_resume=True to override,")
1105
+ print(" or fresh_start=True to skip the check entirely.")
1106
+ st = None
1107
+ if os.path.exists(sp) and st is not None:
1108
+ student.load_state_dict(st["model"]); opt.load_state_dict(st["opt"])
1109
+ sched.load_state_dict(st["sched"]); scaler.load_state_dict(st["scaler"])
1110
+ step, ep0, chunk_i0, best = st["step"], st["epoch"], st["chunk_i"], st["best"]
1111
+ order = st.get("order")
1112
+ try:
1113
+ torch.set_rng_state(st["rng"]["torch"].cpu())
1114
+ np.random.set_state(st["rng"]["np"]); random.setstate(st["rng"]["py"])
1115
+ except Exception:
1116
+ pass
1117
+ print(f" RESUMED at step {step:,} epoch {ep0+1} chunk_i {chunk_i0}")
1118
+
1119
+ print(" building val store...")
1120
+ if cfg.ram_resident:
1121
+ val_src = RamStore(cfg, [cfg.holdout_chunks[-1]], tok, tag=" [val]")
1122
+ else:
1123
+ vds = ChunkPairs(cfg, cfg.holdout_chunks[-1], tok)
1124
+ val_src = torch.utils.data.DataLoader(
1125
+ vds, batch_size=cfg.batch_size, shuffle=False,
1126
+ num_workers=cfg.num_workers, collate_fn=vds.collate)
1127
+
1128
+ if cfg.ram_resident:
1129
+ print(" building train store (one pass, then zero disk I/O)...")
1130
+ train_src = RamStore(cfg, train_chunks, tok, tag=" [train]")
1131
+ N = len(train_src)
1132
+ spe = N // cfg.batch_size
1133
+ total = spe * cfg.epochs
1134
+ print(f" {N:,} rows resident | {spe:,} steps/ep x {cfg.epochs} = {total:,} steps")
1135
+
1136
+ if step >= total or ep0 >= cfg.epochs:
1137
+ raise RuntimeError(
1138
+ f"NOTHING TO TRAIN: resumed at step {step:,}/{total:,}, epoch "
1139
+ f"{ep0}/{cfg.epochs}. The epoch loop would be empty and this job "
1140
+ f"would report the PREVIOUS run's metrics as its own. Set "
1141
+ f"fresh_start=True for a new corpus, or raise cfg.epochs to continue.")
1142
+
1143
+ t0 = last_ck = time.time()
1144
+ for ep in range(ep0, cfg.epochs):
1145
+ if cfg.ram_resident:
1146
+ # deterministic bucketed plan; chunk_i doubles as the batch index, so a
1147
+ # mid-epoch resume regenerates the identical plan and lands on the same batch
1148
+ plan = train_src.plan_batches(cfg.batch_size, cfg.seed + ep,
1149
+ cfg.bucket_window, cfg.length_bucketing)
1150
+ if ep == ep0:
1151
+ spe = len(plan); total = spe * cfg.epochs
1152
+ bl = np.array([train_src.lens[b].max() for b in plan[:200]])
1153
+ print(f" batch plan: {spe:,} batches/epoch | padded length "
1154
+ f"p50 {int(np.percentile(bl,50))} p90 {int(np.percentile(bl,90))} "
1155
+ f"max {int(bl.max())} (bucketing={cfg.length_bucketing})")
1156
+ for ci in range(chunk_i0 if ep == ep0 else 0, len(plan)):
1157
+ ids, am, tg = train_src.batch(plan[ci])
1158
+ ids = ids.to(DEVICE, non_blocking=True)
1159
+ am = am.to(DEVICE, non_blocking=True)
1160
+ tgt = F.normalize(tg.to(DEVICE, non_blocking=True).float(), dim=-1)
1161
+ with torch.amp.autocast("cuda", enabled=cfg.amp and DEVICE == "cuda"):
1162
+ emb = student(ids, am)
1163
+ emb = emb.float()
1164
+ l_nce, acc = infonce(emb, tgt, cfg.nce_temperature)
1165
+ l_mse = F.mse_loss(emb, tgt)
1166
+ loss = cfg.nce_weight * l_nce + cfg.mse_weight * l_mse
1167
+ l_cv = torch.zeros((), device=emb.device)
1168
+ if cfg.cv_weight > 0:
1169
+ l_cv = cv_loss(emb, cfg.cv_target)
1170
+ loss = loss + cfg.cv_weight * l_cv
1171
+ scaler.scale(loss).backward()
1172
+ scaler.unscale_(opt)
1173
+ gn = torch.nn.utils.clip_grad_norm_(student.parameters(), cfg.grad_clip)
1174
+ scaler.step(opt); scaler.update()
1175
+ opt.zero_grad(set_to_none=True); sched.step()
1176
+ step += 1
1177
+
1178
+ if step % cfg.log_every == 0:
1179
+ lr = opt.param_groups[0]["lr"]
1180
+ tb.add_scalar("train/loss", loss.item(), step)
1181
+ tb.add_scalar("train/nce", l_nce.item(), step)
1182
+ tb.add_scalar("train/mse", l_mse.item(), step)
1183
+ tb.add_scalar("train/cv", float(l_cv), step)
1184
+ tb.add_scalar("train/batch_acc", acc, step)
1185
+ tb.add_scalar("train/lr", lr, step)
1186
+ tb.add_scalar("train/grad_norm", float(gn), step)
1187
+ tb.add_scalar("train/tokens_per_seq", ids.shape[1], step)
1188
+ print(f" e{ep+1} {step:>7,}/{total:,} loss {loss.item():.4f} "
1189
+ f"nce {l_nce.item():.4f} mse {l_mse.item():.5f} acc {acc:.3f} "
1190
+ f"lr {lr:.2e} L{ids.shape[1]} {(time.time()-t0)/60:.0f}m")
1191
+
1192
+ if step % cfg.eval_every == 0:
1193
+ m = evaluate(student, val_src)
1194
+ for k, v in m.items():
1195
+ if isinstance(v, (int, float)):
1196
+ tb.add_scalar(f"val/{k}", v, step)
1197
+ for nm, p in student.named_parameters():
1198
+ if p.grad is not None and ("output_proj" in nm or "token_emb" in nm):
1199
+ tb.add_histogram(f"grad/{nm}", p.grad, step)
1200
+ tb.add_histogram(f"weight/{nm}", p, step)
1201
+ print(f" VAL r1 {m['mimicry_r1']:.4f} cos {m['cos_to_target']:.4f} "
1202
+ f"self_cos {m['self_cos']:+.4f} erank {m['erank']:.1f} "
1203
+ f"cv {m['cv']:.4f} | frame r1 "
1204
+ f"{m.get('frame_r1_after_rotation', float('nan')):.4f}")
1205
+ if m["cos_to_target"] > best:
1206
+ best = m["cos_to_target"]
1207
+ save_state(cfg, f"{P['ckpt']}/best_state.pt", student, opt,
1208
+ sched, scaler, step, ep, ci, order, best,
1209
+ n_rows=n_rows_now)
1210
+ torch.save(student.state_dict(), f"{P['ckpt']}/best_model.pt")
1211
+
1212
+ if (time.time() - last_ck) / 60 >= cfg.ckpt_every_min:
1213
+ save_state(cfg, sp, student, opt, sched, scaler, step, ep, ci, order, best,
1214
+ n_rows=n_rows_now)
1215
+ torch.save(student.state_dict(), f"{P['ckpt']}/model_s{step}.pt")
1216
+ ck = sorted([f for f in os.listdir(P["ckpt"]) if f.startswith("model_s")],
1217
+ key=lambda f: int(f.split("_s")[1].split(".")[0]))
1218
+ for old in ck[:-cfg.keep_local_ckpts]:
1219
+ os.remove(os.path.join(P["ckpt"], old))
1220
+ tb.flush(); bk.push(msg=f"step {step}")
1221
+ last_ck = time.time()
1222
+ else:
1223
+ if order is None or ep != ep0:
1224
+ order = train_chunks[:]; random.shuffle(order)
1225
+ for ci in range(chunk_i0 if ep == ep0 else 0, len(order)):
1226
+ c = order[ci]
1227
+ ds = ChunkPairs(cfg, c, tok)
1228
+ dl = torch.utils.data.DataLoader(
1229
+ ds, batch_size=cfg.batch_size, shuffle=True, drop_last=True,
1230
+ num_workers=cfg.num_workers, collate_fn=ds.collate,
1231
+ pin_memory=(DEVICE == "cuda"))
1232
+ for ids, am, tg in dl:
1233
+ ids = ids.to(DEVICE, non_blocking=True)
1234
+ am = am.to(DEVICE, non_blocking=True)
1235
+ tgt = F.normalize(tg.to(DEVICE, non_blocking=True).float(), dim=-1)
1236
+ with torch.amp.autocast("cuda", enabled=cfg.amp and DEVICE == "cuda"):
1237
+ emb = student(ids, am)
1238
+ emb = emb.float()
1239
+ l_nce, acc = infonce(emb, tgt, cfg.nce_temperature)
1240
+ l_mse = F.mse_loss(emb, tgt)
1241
+ loss = cfg.nce_weight * l_nce + cfg.mse_weight * l_mse
1242
+ l_cv = torch.zeros((), device=emb.device)
1243
+ if cfg.cv_weight > 0:
1244
+ l_cv = cv_loss(emb, cfg.cv_target)
1245
+ loss = loss + cfg.cv_weight * l_cv
1246
+ scaler.scale(loss).backward()
1247
+ scaler.unscale_(opt)
1248
+ gn = torch.nn.utils.clip_grad_norm_(student.parameters(), cfg.grad_clip)
1249
+ scaler.step(opt); scaler.update()
1250
+ opt.zero_grad(set_to_none=True); sched.step()
1251
+ step += 1
1252
+
1253
+ if step % cfg.log_every == 0:
1254
+ lr = opt.param_groups[0]["lr"]
1255
+ tb.add_scalar("train/loss", loss.item(), step)
1256
+ tb.add_scalar("train/nce", l_nce.item(), step)
1257
+ tb.add_scalar("train/mse", l_mse.item(), step)
1258
+ tb.add_scalar("train/cv", float(l_cv), step)
1259
+ tb.add_scalar("train/batch_acc", acc, step)
1260
+ tb.add_scalar("train/lr", lr, step)
1261
+ tb.add_scalar("train/grad_norm", float(gn), step)
1262
+ tb.add_scalar("train/tokens_per_seq", ids.shape[1], step)
1263
+ print(f" e{ep+1} {step:>7,}/{total:,} loss {loss.item():.4f} "
1264
+ f"nce {l_nce.item():.4f} mse {l_mse.item():.5f} acc {acc:.3f} "
1265
+ f"lr {lr:.2e} L{ids.shape[1]} {(time.time()-t0)/60:.0f}m")
1266
+
1267
+ if step % cfg.eval_every == 0:
1268
+ m = evaluate(student, val_src)
1269
+ for k, v in m.items():
1270
+ if isinstance(v, (int, float)):
1271
+ tb.add_scalar(f"val/{k}", v, step)
1272
+ for nm, p in student.named_parameters():
1273
+ if p.grad is not None and ("output_proj" in nm or "token_emb" in nm):
1274
+ tb.add_histogram(f"grad/{nm}", p.grad, step)
1275
+ tb.add_histogram(f"weight/{nm}", p, step)
1276
+ print(f" VAL r1 {m['mimicry_r1']:.4f} cos {m['cos_to_target']:.4f} "
1277
+ f"self_cos {m['self_cos']:+.4f} erank {m['erank']:.1f} "
1278
+ f"cv {m['cv']:.4f} | frame r1 "
1279
+ f"{m.get('frame_r1_after_rotation', float('nan')):.4f}")
1280
+ if m["cos_to_target"] > best:
1281
+ best = m["cos_to_target"]
1282
+ save_state(cfg, f"{P['ckpt']}/best_state.pt", student, opt,
1283
+ sched, scaler, step, ep, ci, order, best)
1284
+ torch.save(student.state_dict(), f"{P['ckpt']}/best_model.pt")
1285
+
1286
+ if (time.time() - last_ck) / 60 >= cfg.ckpt_every_min:
1287
+ save_state(cfg, sp, student, opt, sched, scaler, step, ep, ci, order, best,
1288
+ n_rows=n_rows_now)
1289
+ torch.save(student.state_dict(), f"{P['ckpt']}/model_s{step}.pt")
1290
+ ck = sorted([f for f in os.listdir(P["ckpt"]) if f.startswith("model_s")],
1291
+ key=lambda f: int(f.split("_s")[1].split(".")[0]))
1292
+ for old in ck[:-cfg.keep_local_ckpts]:
1293
+ os.remove(os.path.join(P["ckpt"], old))
1294
+ tb.flush(); bk.push(msg=f"step {step}")
1295
+ last_ck = time.time()
1296
+ del ds, dl; gc.collect()
1297
+ chunk_i0 = 0
1298
+
1299
+ save_state(cfg, sp, student, opt, sched, scaler, step, cfg.epochs, 0, order,
1300
+ best, n_rows=n_rows_now)
1301
+ torch.save(student.state_dict(), f"{P['ckpt']}/final_model.pt")
1302
+ tok.save_pretrained(f"{P['ckpt']}/tokenizer")
1303
+ m = evaluate(student, val_src)
1304
+ line("FINAL")
1305
+ print(f" mimicry R@1 (student->consensus, NOT capability): {m['mimicry_r1']:.4f}")
1306
+ print(f" cos to target : {m['cos_to_target']:.4f}")
1307
+ print(f" self_cos : {m['self_cos']:+.4f} <- isotropy; teachers .81-.98")
1308
+ print(f" effective rank: {m['erank']:.1f}/{cfg.output_dim}")
1309
+ print(f" CV : {m['cv']:.4f}")
1310
+ print(f" frame-fit R@1 : {m.get('frame_r1_after_rotation', float('nan')):.4f} "
1311
+ f"(should be ~mimicry: reference-member alignment pins the frame)")
1312
+ print(" CAPABILITY is decided by STS-B / SICK vs the five teachers, not here.")
1313
+ json.dump({"config": asdict(cfg), "final": m}, open(f"{P['ckpt']}/metrics.json", "w"),
1314
+ indent=2, default=str)
1315
+ tb.flush(); tb.close(); bk.push(force=True, msg="final")
1316
+ return student
1317
+
1318
+
1319
+ # ══════════════════════════════════════════════════════════════════
1320
+ # RUN
1321
+ # ══════════════════════════════════════════════════════════════════
1322
+
1323
+ def run(cfg: BaseConfig = CFG):
1324
+ # THE PROFILE IS APPLIED HERE, not by the caller. This cell auto-runs on
1325
+ # paste, so anything the caller sets afterwards arrives too late -- which is
1326
+ # exactly how a stage-1 refit fired twice against an explicit instruction
1327
+ # not to (2026-08-02). Derived flags, one source of truth.
1328
+ cfg = configure(cfg, cfg.profile)
1329
+ cfg = dataclasses.replace(cfg, profile="_applied")
1330
+ print("=" * 78)
1331
+ print(f"{cfg.run_name.upper()} β€” CONSENSUS DISTILLATION, CC12M SCALE")
1332
+ print("=" * 78)
1333
+ paths(cfg)
1334
+ print(f"device={DEVICE} work_dir={cfg.work_dir}")
1335
+ if DEVICE == "cuda":
1336
+ print(f"gpu={torch.cuda.get_device_name()} "
1337
+ f"vram={torch.cuda.get_device_properties(0).total_memory/1e9:.0f}GB")
1338
+ miss = src0(cfg).get("missing", {})
1339
+ print(f"chunks: {len(usable_chunks(cfg))} train + {len(cfg.holdout_chunks)} holdout "
1340
+ f"| excluded for missing experts: {miss}")
1341
+ if not cfg.require_all_experts:
1342
+ print(" !! require_all_experts=False -> 4-expert consensus on some chunks.")
1343
+ print(" !! The target definition then differs BETWEEN chunks. Discouraged.")
1344
+ bk = Backup(cfg)
1345
+
1346
+ if cfg.run_stage0:
1347
+ cfg.caption_field = stage0_parity(cfg)
1348
+ elif cfg.caption_field is None:
1349
+ raise RuntimeError("caption_field is None and stage 0 is disabled.")
1350
+
1351
+ ensure_artifacts(cfg)
1352
+ maps = stage1_fit(cfg, bk) if cfg.run_stage1 else torch.load(
1353
+ f"{paths(cfg)['maps']}/alignment_maps.pt", weights_only=False)
1354
+ chunks = stage2_targets(cfg, maps, bk) if cfg.run_stage2 else sorted(
1355
+ set(usable_chunks(cfg)) | set(cfg.holdout_chunks))
1356
+ if cfg.run_stage3:
1357
+ return stage3_train(cfg, chunks, bk)
1358
+
1359
+
1360
+ if "get_ipython" in globals() or __name__ == "__main__":
1361
+ STUDENT = run(CFG)