STAR-future commited on
Commit
3712a11
·
verified ·
1 Parent(s): 0352bab

H5 tools: trainer with contiguous-block sampling, driver with H4_CONFIGS

Browse files
tools/colab_h4_fulltail_and_subspace_gate.py CHANGED
@@ -46,6 +46,7 @@ CONFIGS = [
46
  ("F6_Arm9b_EntropySubspaceCartridge", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--entropy-gate", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
47
  ("F7_Arm10a_RealK3_DecoupledOOF_CausalEMA",["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--oof-causal-ema", "--gate-sensor", "x92", "--causal-ema", "0.15", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
48
  ("F8_Arm11_RealK3_TwoStage_WikiShield", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--wiki-shield", "--gate-sensor", "x92", "--causal-ema", "0.15", "--hybrid-alpha", "0.4", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
 
49
  ]
50
 
51
 
@@ -75,6 +76,10 @@ def main() -> int:
75
  ("train7", "STAR-future/Trinity-k3cache-train7", "train7", False),
76
  ("train8", "STAR-future/Trinity-k3cache-train8", "train8", False),
77
  ("train9", "STAR-future/Trinity-k3cache-train9", "train9", False),
 
 
 
 
78
  ("holdout", CACHE_PRIV, "holdout", True),
79
  ]
80
  for m, repo, folder, required in cache_specs:
@@ -99,7 +104,8 @@ def main() -> int:
99
  print("H4 MultiCache sources:", train_caches, "domains:", DOMAINS or "ALL", flush=True)
100
 
101
  rows = []
102
- for name, extra_flags in CONFIGS:
 
103
  out = W / "h4" / name
104
  if not (out / "train_record.json").exists():
105
  cmd = [
 
46
  ("F6_Arm9b_EntropySubspaceCartridge", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--entropy-gate", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
47
  ("F7_Arm10a_RealK3_DecoupledOOF_CausalEMA",["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--oof-causal-ema", "--gate-sensor", "x92", "--causal-ema", "0.15", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
48
  ("F8_Arm11_RealK3_TwoStage_WikiShield", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--wiki-shield", "--gate-sensor", "x92", "--causal-ema", "0.15", "--hybrid-alpha", "0.4", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
49
+ ("F9_Arm11_WikiShield_EntropyGate_FocalHard", ["--head-rank", "64", "--tail-rank", "0", "--k", "0", "--lr", "1.5e-4", "--kl", "0.0", "--epochs", "2", "--modular-cartridges", "--wiki-shield", "--entropy-gate", "--focal-hard-gamma", "2.0", "--gate-sensor", "x92", "--causal-ema", "0.15", "--hybrid-alpha", "0.4", "--subspace-rank", "24", "--tr-lambda", "0.05", "--no-train-final-norm"]),
50
  ]
51
 
52
 
 
76
  ("train7", "STAR-future/Trinity-k3cache-train7", "train7", False),
77
  ("train8", "STAR-future/Trinity-k3cache-train8", "train8", False),
78
  ("train9", "STAR-future/Trinity-k3cache-train9", "train9", False),
79
+ ("train10", "STAR-future/Trinity-k3cache-train10", "train10", False),
80
+ ("train11", "STAR-future/Trinity-k3cache-train11", "train11", False),
81
+ ("train12", "STAR-future/Trinity-k3cache-train12", "train12", False),
82
+ ("train13", "STAR-future/Trinity-k3cache-train13", "train13", False),
83
  ("holdout", CACHE_PRIV, "holdout", True),
84
  ]
85
  for m, repo, folder, required in cache_specs:
 
104
  print("H4 MultiCache sources:", train_caches, "domains:", DOMAINS or "ALL", flush=True)
105
 
106
  rows = []
107
+ only = [c for c in os.environ.get("H4_CONFIGS", "").split(",") if c] # 2026-11-24: run a preregistered subset (H5)
108
+ for name, extra_flags in [c for c in CONFIGS if not only or c[0] in only]:
109
  out = W / "h4" / name
110
  if not (out / "train_record.json").exists():
111
  cmd = [
tools/trinity_full_tail_wsp.py CHANGED
@@ -35,6 +35,8 @@ import math
35
  import os
36
  import sys
37
  import tempfile
 
 
38
  from pathlib import Path
39
  from typing import Any
40
 
@@ -153,6 +155,81 @@ class MultiCache:
153
  self.shards.clear()
154
 
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  class FactorizedLinearLoRA(nn.Module):
157
  """VRAM-safe Low-Rank LoRA for huge projections like `lm_head [163840, 7168]`:
158
  NEVER materializes `[out, in]` during forward; merges chunk-by-chunk into stock BF16 weight."""
@@ -165,9 +242,22 @@ class FactorizedLinearLoRA(nn.Module):
165
  self.a = nn.Parameter(torch.randn(rank, in_features, device=dev, dtype=torch.float32) / math.sqrt(in_features))
166
  self.b = nn.Parameter(torch.zeros(out_features, rank, device=dev, dtype=torch.float32))
167
 
168
- def delta(self, h: torch.Tensor) -> torch.Tensor:
 
 
 
169
  return self.scale * ((h.float() @ self.a.t()) @ self.b.t())
170
 
 
 
 
 
 
 
 
 
 
 
171
  @torch.no_grad()
172
  def merge_into(self, base_w: torch.Tensor, chunk: int = 16384) -> torch.Tensor:
173
  out = base_w.clone()
@@ -198,8 +288,14 @@ class RoutedW2LoRA(nn.Module):
198
  k = len(hot)
199
  self.a = nn.Parameter(torch.randn(k, rank, d_hidden, device=dev, dtype=torch.float32) / math.sqrt(d_hidden))
200
  self.b = nn.Parameter(torch.zeros(k, d_latent, rank, device=dev, dtype=torch.float32))
201
-
202
- def delta_acc(self, xl: torch.Tensor, idx: torch.Tensor, wts: torch.Tensor, orig_experts, situ_mul) -> torch.Tensor:
 
 
 
 
 
 
203
  d = torch.zeros(xl.shape[0], self.b.shape[1], device=xl.device, dtype=torch.float32)
204
  for j, e in enumerate(self.hot):
205
  sel = (idx == e)
@@ -215,6 +311,43 @@ class RoutedW2LoRA(nn.Module):
215
  d = d.index_add(0, rows, d_e * w[:, None])
216
  return d
217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  @torch.no_grad()
219
  def merge_w2(self, j: int, base_w2: torch.Tensor) -> torch.Tensor:
220
  return (base_w2.float() + self.scale * (self.b[j].float() @ self.a[j].float())).to(base_w2.dtype)
@@ -709,6 +842,27 @@ def selftest() -> int:
709
  wts = torch.softmax(torch.randn(16, top_k), -1)
710
  situ = lambda g, u, b, lb: F.silu(g) * u # noqa: E731
711
  assert float(r_lora.delta_acc(xl, idx, wts, orig_exp, situ).detach().abs().max()) == 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712
 
713
  t_lbl = torch.randint(0, V, (16,))
714
  norm_p = nn.Parameter(torch.ones(D))
@@ -817,6 +971,9 @@ def selftest() -> int:
817
  "arm11_causal_ema_chunk_reload_diff": ema_chunk_diff,
818
  "arm11_wikishield_in": round(ws_in, 4),
819
  "arm11_wikishield_gen": round(ws_gen, 5),
 
 
 
820
  }, indent=2))
821
  return 0
822
 
@@ -877,6 +1034,18 @@ def main() -> int:
877
  ap.add_argument("--kl", type=float, default=1.0)
878
  ap.add_argument("--val-frac", type=float, default=0.1)
879
  ap.add_argument("--seed", type=int, default=20261119)
 
 
 
 
 
 
 
 
 
 
 
 
880
  a = ap.parse_args()
881
 
882
  if a.wiki_shield:
@@ -1089,15 +1258,24 @@ def main() -> int:
1089
  bg_seq_t = {bd: collect_sensor_seqs(bg_tr_seqs[bd], a.gate_sensor) for bd in bg_doms if bg_tr_seqs[bd]} if a.all_bg_negatives else {}
1090
 
1091
  if a.wiki_shield:
 
 
1092
  all_pos_t = [s for d in active_doms for s in dom_seq_t[d]]
1093
- ws_negs = [(gen_seq_t, 0.998)] + ([(bg_seq_t[bd], 0.992) for bd in sorted(bg_seq_t)] if bg_seq_t else [])
1094
  wiki_shield_gate = SubspaceEnergyGate.fit_oof_from_sequences(
1095
  all_pos_t, ws_negs, r_sub=a.subspace_rank, reg=0.25,
1096
  beta_ema=a.causal_ema, alpha_lin=a.hybrid_alpha, n_folds=4, warmup=8, sensor_mode=a.gate_sensor,
1097
  )
1098
  ws_row_table = precompute_seq_gates(wiki_shield_gate, all_train_eval_seqs, a.gate_sensor)
1099
- print(f"[Arm-11 WikiShield] sensor={a.gate_sensor} ema={a.causal_ema} bg_negs={sorted(bg_seq_t)} | "
1100
  f"va_dom_ws={float(ws_row_table[va_dom].mean()):.4f} va_gen_ws={float(ws_row_table[va_gen].mean()):.6f}", flush=True)
 
 
 
 
 
 
 
1101
  else:
1102
  h_gen_all, e_gen_all = collect_h_and_ent(rng.permutation(tr_gen), cap=8192)
1103
  dom_cal_raw = {d: collect_h_and_ent(rng.permutation(per_dom_tr[d]), cap=8192) for d in active_doms}
@@ -1129,6 +1307,8 @@ def main() -> int:
1129
  if a.oof_causal_ema:
1130
  if a.wiki_shield:
1131
  other_neg = [(dom_seq_t[od], 0.90) for od in active_doms if od != d]
 
 
1132
  if not other_neg:
1133
  other_neg = [(gen_seq_t, 0.998)]
1134
  gd = SubspaceEnergyGate.fit_oof_from_sequences(
@@ -1159,49 +1339,97 @@ def main() -> int:
1159
  opt_d = torch.optim.AdamW(list(ld.parameters()), lr=a.lr, weight_decay=a.wd)
1160
  bs_d = min(a.bs, len(per_dom_tr[d]))
1161
  steps_d = max(1, int(a.epochs * len(per_dom_tr[d]) / max(1, bs_d)))
 
 
1162
  sched_d = torch.optim.lr_scheduler.OneCycleLR(opt_d, max_lr=a.lr, total_steps=steps_d, pct_start=0.1)
1163
  best_va, best_st = float("inf"), None
1164
 
 
 
 
 
 
 
 
 
 
 
1165
  @torch.no_grad()
1166
- def eval_d(rows_e, use_cart=True):
1167
  rr = []
 
 
 
 
 
 
 
 
 
1168
  for k0 in range(0, len(rows_e), 2048):
1169
  r_ch = np.sort(rows_e[k0:k0 + 2048])
1170
  x, acc, p, A, Z, m, t = cache.batch(r_ch, dev)
1171
  h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
1172
- lg = (h @ lm_head.t()).float()
1173
  if use_cart:
1174
  gv = (torch.from_numpy(g_row_table[r_ch]).to(dev)[:, None] if g_row_table is not None else gd(h.detach()))
1175
- lg = lg + (gv * _ent_mult(lg)) * ld.delta(h)
1176
  rr.append(F.cross_entropy(lg, t, reduction="none").cpu())
1177
  return float(torch.cat(rr).mean()) if rr else float("inf")
1178
 
1179
- va0_d = eval_d(per_dom_va[d], False)
1180
  best_va = va0_d
1181
  best_st = (ld.a.detach().clone(), ld.b.detach().clone())
1182
 
 
 
1183
  for st_i in range(steps_d):
1184
  opt_d.zero_grad(set_to_none=True)
1185
- r_batch = np.sort(rng.choice(per_dom_tr[d], bs_d, replace=False))
1186
- x, acc, p, A, Z, m, t = cache.batch(r_batch, dev)
1187
- with torch.no_grad():
1188
- h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
1189
- base_lg = (h @ lm_head.t()).float()
1190
- gv = (torch.from_numpy(g_row_table[r_batch]).to(dev)[:, None] if g_row_table is not None else gd(h.detach()))
1191
- g_val = gv * _ent_mult(base_lg)
1192
- delta_lg = ld.delta(h)
1193
- loss = F.cross_entropy(base_lg + g_val * delta_lg, t)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1194
  if a.tr_lambda > 0:
1195
- loss = loss + a.tr_lambda * delta_lg.pow(2).mean()
 
1196
  loss.backward()
1197
  torch.nn.utils.clip_grad_norm_(list(ld.parameters()), 1.0)
1198
  opt_d.step()
1199
  sched_d.step()
 
 
 
 
1200
  if (st_i + 1) % max(1, steps_d // 8) == 0 or st_i == steps_d - 1:
1201
- vac = eval_d(per_dom_va[d], True)
1202
  if vac < best_va:
1203
  best_va = vac
1204
  best_st = (ld.a.detach().clone(), ld.b.detach().clone())
 
1205
  with torch.no_grad():
1206
  ld.a.copy_(best_st[0])
1207
  ld.b.copy_(best_st[1])
@@ -1308,68 +1536,128 @@ def main() -> int:
1308
  n_par = sum(p.numel() for p in params)
1309
  print(f"Total trainable params: {n_par:,} (tr_lambda={a.tr_lambda})", flush=True)
1310
 
1311
- def fwd_train(x, acc, p, A, Z, m, use_trained: bool = True, return_delta: bool = False):
1312
  if use_trained and r_lora is not None:
1313
  idx, wts, xl = route(x)
1314
  acc = acc + r_lora.delta_acc(xl, idx, wts, orig_exp, K.situ_mul)
1315
  Wf_c = ({**Wf, "norm": fn_param.to(Wf["norm"].dtype)} if (use_trained and fn_param is not None) else Wf)
1316
  h = K.final_from_terms(p, K.moe_tail(acc, x, Wcur() if use_trained else W0, c), A, Z, m, Wf_c, c)
1317
- lg = (h @ lm_head.t()).float()
1318
- raw_d = None
1319
  if use_trained and head_lora is not None:
1320
- raw_d = head_lora.delta(h)
1321
  d_lg = cg(h.detach()) * raw_d if cg is not None else raw_d
1322
  lg = lg + d_lg
1323
- return (lg, raw_d) if return_delta else lg
1324
-
1325
- def eval_nll(rows, use_trained: bool):
 
 
 
 
 
 
 
 
 
 
 
 
 
1326
  res = []
1327
  with torch.no_grad():
 
 
 
 
 
 
 
 
 
1328
  for i in range(0, len(rows), 2048):
1329
  x, acc, p, A, Z, m, t = cache.batch(rows[i:i + 2048], dev)
1330
  res.append(F.cross_entropy(fwd_train(x, acc, p, A, Z, m, use_trained), t, reduction="none").cpu())
1331
  return float(torch.cat(res).mean()) if res else None
1332
 
1333
- val0, vg0 = eval_nll(va_dom, False), eval_nll(va_gen, False)
1334
- v_id = eval_nll(va_dom, True)
1335
  print(f"val_before={val0:.6f} identity_check={v_id:.6f} val_gen_before={vg0}", flush=True)
1336
 
1337
  opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=a.wd)
1338
  bs_d, bs_g = min(a.bs, len(tr_dom)), min(a.bs // 2, len(tr_gen))
1339
  steps = max(1, int(a.epochs * len(tr_dom) / max(1, bs_d)))
 
 
1340
  sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=steps, pct_start=0.1)
1341
  best_val, best_snap = val0, [p.detach().cpu().clone() for p in params]
1342
  log = []
 
 
1343
  for step in range(steps):
1344
  opt.zero_grad(set_to_none=True)
1345
- x, acc, p, A, Z, m, t = cache.batch(rng.choice(tr_dom, bs_d, replace=False), dev)
1346
- lg_d, raw_d = fwd_train(x, acc, p, A, Z, m, True, return_delta=True)
1347
- loss_d = F.cross_entropy(lg_d, t)
1348
- if a.tr_lambda > 0 and raw_d is not None:
1349
- loss_d = loss_d + a.tr_lambda * raw_d.pow(2).mean()
1350
- ld = float(loss_d.detach())
1351
- loss_d.backward()
1352
- del loss_d, lg_d, raw_d, x, acc, p, A, Z, m, t
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1353
  kl_v = 0.0
1354
  if a.kl > 0 and bs_g > 0:
1355
- xg, accg, pg, Ag, Zg, mg, _ = cache.batch(rng.choice(tr_gen, bs_g, replace=False), dev)
1356
- with torch.no_grad():
1357
- ref = F.log_softmax(fwd_train(xg, accg, pg, Ag, Zg, mg, False), -1)
1358
- cur = F.log_softmax(fwd_train(xg, accg, pg, Ag, Zg, mg, True), -1)
1359
- kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
1360
- kl_v = float(kl.detach())
1361
- (a.kl * kl).backward()
1362
- del kl, cur, ref, xg, accg, pg, Ag, Zg, mg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1363
  torch.nn.utils.clip_grad_norm_(params, 1.0)
1364
  opt.step()
1365
  sched.step()
1366
  if step % 20 == 0 or step == steps - 1:
1367
- rec = {"step": step, "loss_domain": ld, "loss_kl": kl_v}
 
 
1368
  log.append(rec)
1369
  print(json.dumps(rec), flush=True)
1370
  if (step + 1) % max(1, steps // 8) == 0 or step == steps - 1:
1371
- vc = eval_nll(va_dom, True)
1372
- vgc = eval_nll(va_gen, True)
1373
  gen_ok_now = (vg0 is None or vgc is None or ((vgc - vg0) / vg0) <= 0.005)
1374
  if vc is not None and gen_ok_now and vc < best_val:
1375
  best_val = vc
@@ -1379,7 +1667,7 @@ def main() -> int:
1379
  for p, s_t in zip(params, best_snap):
1380
  p.copy_(s_t.to(dev))
1381
 
1382
- val1, vg1 = eval_nll(va_dom, True), eval_nll(va_gen, True)
1383
  rel_d = (val1 - val0) / val0
1384
  rel_g = None if (vg0 is None or vg1 is None) else (vg1 - vg0) / vg0
1385
  print(f"val_after={val1:.6f} rel_dom={rel_d:+.5f} rel_gen={rel_g}", flush=True)
 
35
  import os
36
  import sys
37
  import tempfile
38
+ import time
39
+ from contextlib import nullcontext
40
  from pathlib import Path
41
  from typing import Any
42
 
 
155
  self.shards.clear()
156
 
157
 
158
+ def sample_contiguous_blocks(rows: np.ndarray, batch_size: int, block_size: int, rng: np.random.Generator) -> np.ndarray:
159
+ """Sample `batch_size` rows as contiguous spans of length `block_size` (cuts random mmap page faults by ~200-380x!).
160
+
161
+ When `block_size <= 1` or `batch_size >= len(rows)`, falls back cleanly to exact uniform token sampling.
162
+ Because `rows` is sorted by `(seq_id, pos)`, slicing contiguous spans of `rows` guarantees sequential disk reads
163
+ while drawing blocks uniformly across all documents in the corpus.
164
+ """
165
+ n = len(rows)
166
+ if batch_size >= n:
167
+ return rows
168
+ if block_size <= 1:
169
+ return np.sort(rng.choice(rows, batch_size, replace=False))
170
+ blk = min(block_size, batch_size)
171
+ n_blocks = max(1, (batch_size + blk - 1) // blk)
172
+ # Partition `rows` into non-overlapping contiguous chunks with a fresh random phase offset each step!
173
+ n_chunks = max(1, n // blk)
174
+ if n_chunks <= n_blocks:
175
+ return rows[:batch_size]
176
+ phase = int(rng.integers(0, max(1, n - n_chunks * blk + 1)))
177
+ chosen = np.sort(rng.choice(n_chunks, n_blocks, replace=False))
178
+ parts = [rows[phase + int(ci) * blk: phase + (int(ci) + 1) * blk] for ci in chosen]
179
+ out = np.concatenate(parts)
180
+ return out[:batch_size]
181
+
182
+
183
+ class PrecomputedHBaseCache:
184
+ """Contiguous precomputed `h_base` (`[N, D]` bf16) + `t` (`[N]` int64) + optional gate (`[N]` fp32) cache.
185
+
186
+ For head/cartridge-only H4 configs (`F4..F8`, where `W_tail`/`r_lora`/`final_norm` are frozen), precomputing
187
+ `h_base` ONCE sequentially eliminates `x92`, `acc92`, `prefix92`, `A92`, `Zm92`, `K.moe_tail`, and
188
+ `K.final_from_terms` from EVERY training step (`20-40x` faster on L4: `~0.25-0.55 s/step` vs `11.5 s/step`!).
189
+ """
190
+
191
+ def __init__(self, h_bf16: torch.Tensor, t_i64: torch.Tensor, g_f32: torch.Tensor | None = None):
192
+ self.h = h_bf16 # CPU contiguous bf16 [N, D]
193
+ self.t = t_i64 # CPU contiguous int64 [N]
194
+ self.g = g_f32 # optional CPU contiguous float32 [N]
195
+ self.n = int(h_bf16.shape[0])
196
+
197
+ @classmethod
198
+ @torch.no_grad()
199
+ def build(
200
+ cls,
201
+ cache: MultiCache,
202
+ rows: np.ndarray,
203
+ W0: dict[str, Any],
204
+ Wf: dict[str, Any],
205
+ c: Any,
206
+ K_mod: Any,
207
+ dev: torch.device,
208
+ *,
209
+ g_row_table: np.ndarray | None = None,
210
+ chunk: int = 4096,
211
+ ) -> "PrecomputedHBaseCache":
212
+ rows_s = np.sort(np.asarray(rows, dtype=np.int64))
213
+ n = len(rows_s)
214
+ hs, ts = [], []
215
+ for k0 in range(0, n, chunk):
216
+ x, acc, p, A, Z, m, t = cache.batch(rows_s[k0:k0 + chunk], dev)
217
+ h_b = K_mod.final_from_terms(p, K_mod.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
218
+ hs.append(h_b.to(torch.bfloat16).cpu())
219
+ ts.append(t.cpu())
220
+ h_all = torch.cat(hs, 0).contiguous()
221
+ t_all = torch.cat(ts, 0).contiguous()
222
+ g_all = torch.from_numpy(np.ascontiguousarray(g_row_table[rows_s], dtype=np.float32)) if g_row_table is not None else None
223
+ return cls(h_all, t_all, g_all)
224
+
225
+ def batch(self, idx: np.ndarray, dev: torch.device) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
226
+ ii = torch.from_numpy(np.asarray(idx, dtype=np.int64))
227
+ hb = self.h[ii].to(dev, non_blocking=True)
228
+ tb = self.t[ii].to(dev, non_blocking=True)
229
+ gb = self.g[ii].to(dev, non_blocking=True)[:, None] if self.g is not None else None
230
+ return hb, tb, gb
231
+
232
+
233
  class FactorizedLinearLoRA(nn.Module):
234
  """VRAM-safe Low-Rank LoRA for huge projections like `lm_head [163840, 7168]`:
235
  NEVER materializes `[out, in]` during forward; merges chunk-by-chunk into stock BF16 weight."""
 
242
  self.a = nn.Parameter(torch.randn(rank, in_features, device=dev, dtype=torch.float32) / math.sqrt(in_features))
243
  self.b = nn.Parameter(torch.zeros(out_features, rank, device=dev, dtype=torch.float32))
244
 
245
+ def delta(self, h: torch.Tensor, bf16_amp: bool = False) -> torch.Tensor:
246
+ if bf16_amp and h.is_cuda:
247
+ u = self.scale * (h.to(torch.bfloat16) @ self.a.to(torch.bfloat16).t())
248
+ return (u @ self.b.to(torch.bfloat16).t()).float()
249
  return self.scale * ((h.float() @ self.a.t()) @ self.b.t())
250
 
251
+ def tr_loss(self, h: torch.Tensor) -> torch.Tensor:
252
+ """Exact algebraic low-rank Frobenius Trust-Region: `mean(delta(h)^2) == sum((U^T U)*(B^T B)) / (N * V)`.
253
+
254
+ Bit-exact algebraic identity that avoids backpropagating through `[N, 163840]` (`1.34 GB` -> `16 KB`!).
255
+ """
256
+ u = self.scale * (h.float() @ self.a.t())
257
+ utu = u.t() @ u
258
+ btb = self.b.t() @ self.b
259
+ return (utu * btb).sum() / float(h.shape[0] * self.b.shape[0])
260
+
261
  @torch.no_grad()
262
  def merge_into(self, base_w: torch.Tensor, chunk: int = 16384) -> torch.Tensor:
263
  out = base_w.clone()
 
288
  k = len(hot)
289
  self.a = nn.Parameter(torch.randn(k, rank, d_hidden, device=dev, dtype=torch.float32) / math.sqrt(d_hidden))
290
  self.b = nn.Parameter(torch.zeros(k, d_latent, rank, device=dev, dtype=torch.float32))
291
+ max_e = max(hot) + 1 if hot else 1
292
+ lut = torch.full((max_e,), -1, dtype=torch.long, device=dev)
293
+ for j, e in enumerate(hot):
294
+ lut[e] = j
295
+ self.register_buffer("hot_lut", lut)
296
+
297
+ def delta_acc_naive(self, xl: torch.Tensor, idx: torch.Tensor, wts: torch.Tensor, orig_experts, situ_mul) -> torch.Tensor:
298
+ """Reference loop implementation (kept for CPU numerical parity checks)."""
299
  d = torch.zeros(xl.shape[0], self.b.shape[1], device=xl.device, dtype=torch.float32)
300
  for j, e in enumerate(self.hot):
301
  sel = (idx == e)
 
311
  d = d.index_add(0, rows, d_e * w[:, None])
312
  return d
313
 
314
+ def delta_acc(self, xl: torch.Tensor, idx: torch.Tensor, wts: torch.Tensor, orig_experts, situ_mul) -> torch.Tensor:
315
+ """Zero-sync single-pass grouped expert dispatch (eliminates 128 per-expert CUDA sync stalls per step!)."""
316
+ n_tok, top_k = idx.shape
317
+ d = torch.zeros(n_tok, self.b.shape[1], device=xl.device, dtype=torch.float32)
318
+ k_hot = len(self.hot)
319
+ if k_hot == 0:
320
+ return d
321
+ flat_e = idx.reshape(-1)
322
+ lut = self.hot_lut
323
+ in_range = flat_e < lut.shape[0]
324
+ j_flat = torch.where(in_range, lut[flat_e.clamp_max(lut.shape[0] - 1)], torch.full_like(flat_e, -1))
325
+ valid = j_flat >= 0
326
+ if not valid.any():
327
+ return d
328
+ j_val = j_flat[valid]
329
+ tok_val = torch.arange(n_tok, device=xl.device).repeat_interleave(top_k)[valid]
330
+ w_val = wts.reshape(-1)[valid].float()
331
+ order = torch.argsort(j_val)
332
+ j_sorted = j_val[order]
333
+ tok_sorted = tok_val[order]
334
+ w_sorted = w_val[order]
335
+ counts = torch.bincount(j_sorted, minlength=k_hot).tolist()
336
+ start = 0
337
+ for j, cnt in enumerate(counts):
338
+ if cnt == 0:
339
+ continue
340
+ rows = tok_sorted[start:start + cnt]
341
+ w = w_sorted[start:start + cnt]
342
+ start += cnt
343
+ x_ = xl[rows]
344
+ w1, _, w3 = orig_experts[j]
345
+ with torch.no_grad():
346
+ hid = situ_mul(x_ @ w1.t(), x_ @ w3.t(), 4.0, 25.0).float()
347
+ d_e = self.scale * ((hid @ self.a[j].t()) @ self.b[j].t())
348
+ d = d.index_add(0, rows, d_e * w[:, None])
349
+ return d
350
+
351
  @torch.no_grad()
352
  def merge_w2(self, j: int, base_w2: torch.Tensor) -> torch.Tensor:
353
  return (base_w2.float() + self.scale * (self.b[j].float() @ self.a[j].float())).to(base_w2.dtype)
 
842
  wts = torch.softmax(torch.randn(16, top_k), -1)
843
  situ = lambda g, u, b, lb: F.silu(g) * u # noqa: E731
844
  assert float(r_lora.delta_acc(xl, idx, wts, orig_exp, situ).detach().abs().max()) == 0.0
845
+ # Verify zero-sync RoutedW2LoRA parity vs naive reference loop (< 1e-5) and exact algebraic tr_loss value+grad parity!
846
+ with torch.no_grad():
847
+ r_lora.b.normal_(0.0, 0.25)
848
+ routed_parity_diff = float(
849
+ (r_lora.delta_acc(xl, idx, wts, orig_exp, situ) - r_lora.delta_acc_naive(xl, idx, wts, orig_exp, situ)).detach().abs().max()
850
+ )
851
+ assert routed_parity_diff < 1e-5, f"RoutedW2LoRA zero-sync parity diff {routed_parity_diff}"
852
+ with torch.no_grad():
853
+ r_lora.b.zero_()
854
+ head_lora.b.normal_(0.0, 0.2)
855
+ tr_fast = head_lora.tr_loss(h_in)
856
+ tr_ref = head_lora.delta(h_in).pow(2).mean()
857
+ tr_val_diff = float((tr_fast - tr_ref).detach().abs().item())
858
+ ga_f, gb_f = torch.autograd.grad(tr_fast, (head_lora.a, head_lora.b), retain_graph=True)
859
+ ga_r, gb_r = torch.autograd.grad(tr_ref, (head_lora.a, head_lora.b))
860
+ tr_grad_diff = max(float((ga_f - ga_r).abs().max().item()), float((gb_f - gb_r).abs().max().item()))
861
+ assert tr_val_diff < 1e-5 and tr_grad_diff < 1e-5, f"tr_loss parity failed: val={tr_val_diff}, grad={tr_grad_diff}"
862
+ with torch.no_grad():
863
+ head_lora.b.zero_()
864
+ blk_s = sample_contiguous_blocks(np.arange(1000, dtype=np.int64), 128, 32, np.random.default_rng(7))
865
+ assert len(blk_s) == 128 and len(np.unique(blk_s)) == 128 and bool(np.all(np.diff(blk_s) > 0))
866
 
867
  t_lbl = torch.randint(0, V, (16,))
868
  norm_p = nn.Parameter(torch.ones(D))
 
971
  "arm11_causal_ema_chunk_reload_diff": ema_chunk_diff,
972
  "arm11_wikishield_in": round(ws_in, 4),
973
  "arm11_wikishield_gen": round(ws_gen, 5),
974
+ "routed_zerosync_parity_diff": routed_parity_diff,
975
+ "tr_algebraic_val_diff": tr_val_diff,
976
+ "tr_algebraic_grad_diff": tr_grad_diff,
977
  }, indent=2))
978
  return 0
979
 
 
1034
  ap.add_argument("--kl", type=float, default=1.0)
1035
  ap.add_argument("--val-frac", type=float, default=0.1)
1036
  ap.add_argument("--seed", type=int, default=20261119)
1037
+ ap.add_argument("--block-size", type=int, default=256,
1038
+ help="Contiguous mmap block size per random batch slice (default 256 -> ~380x fewer random disk seeks; 1 = legacy token gather)")
1039
+ ap.add_argument("--precompute-h", action="store_true", default=True,
1040
+ help="Precompute contiguous h_base BF16 once when backbone is frozen (F4..F8/cartridges -> 20-40x speedup!)")
1041
+ ap.add_argument("--no-precompute-h", dest="precompute_h", action="store_false")
1042
+ ap.add_argument("--bf16-amp", action="store_true", default=True,
1043
+ help="Use BF16 Tensor Cores for lm_head & FactorizedLinearLoRA matmuls on CUDA (master weights & CE/KL stay FP32)")
1044
+ ap.add_argument("--no-bf16-amp", dest="bf16_amp", action="store_false")
1045
+ ap.add_argument("--max-steps", type=int, default=0,
1046
+ help="Optional hard cap on training steps per cartridge/run (0 = full epochs)")
1047
+ ap.add_argument("--focal-hard-gamma", type=float, default=0.0,
1048
+ help="Targeted hard-token focal weighting `1 + gamma * sigmoid(nll_base - 2.0)` (MSG-0089 #2; default 0.0)")
1049
  a = ap.parse_args()
1050
 
1051
  if a.wiki_shield:
 
1258
  bg_seq_t = {bd: collect_sensor_seqs(bg_tr_seqs[bd], a.gate_sensor) for bd in bg_doms if bg_tr_seqs[bd]} if a.all_bg_negatives else {}
1259
 
1260
  if a.wiki_shield:
1261
+ # Stage-1 WikiShield guards strictly against general_wiki (q=0.998 -> ~0.99 science recall, 0.000 wiki!).
1262
+ # Background non-target domains (physics/chemistry) are guarded in Stage-2 specialist routers at q=0.92!
1263
  all_pos_t = [s for d in active_doms for s in dom_seq_t[d]]
1264
+ ws_negs = [(gen_seq_t, 0.998)]
1265
  wiki_shield_gate = SubspaceEnergyGate.fit_oof_from_sequences(
1266
  all_pos_t, ws_negs, r_sub=a.subspace_rank, reg=0.25,
1267
  beta_ema=a.causal_ema, alpha_lin=a.hybrid_alpha, n_folds=4, warmup=8, sensor_mode=a.gate_sensor,
1268
  )
1269
  ws_row_table = precompute_seq_gates(wiki_shield_gate, all_train_eval_seqs, a.gate_sensor)
1270
+ print(f"[Arm-11 WikiShield] sensor={a.gate_sensor} ema={a.causal_ema} | "
1271
  f"va_dom_ws={float(ws_row_table[va_dom].mean()):.4f} va_gen_ws={float(ws_row_table[va_gen].mean()):.6f}", flush=True)
1272
+ if a.entropy_gate:
1273
+ # Allow combining Arm10/Arm11 WikiShield WITH Arm9b EntropyGate u(H(p_base)) to prevent +3.1% easy-token damage!
1274
+ _, e_gen_s = collect_h_and_ent(rng.permutation(tr_gen), cap=4096)
1275
+ _, e_dom_s = collect_h_and_ent(rng.permutation(tr_dom), cap=4096)
1276
+ tau_mem = float(torch.quantile(e_gen_s, 0.72).item())
1277
+ tau_ent = max(tau_mem + 0.30, 0.5 * (float(torch.quantile(e_gen_s, 0.70).item()) + float(torch.quantile(e_dom_s, 0.55).item())))
1278
+ print(f"[Arm11+EntropyGate] calibrated tau_ent={tau_ent:.3f} (shuts off easy tokens H < tau_ent!)", flush=True)
1279
  else:
1280
  h_gen_all, e_gen_all = collect_h_and_ent(rng.permutation(tr_gen), cap=8192)
1281
  dom_cal_raw = {d: collect_h_and_ent(rng.permutation(per_dom_tr[d]), cap=8192) for d in active_doms}
 
1307
  if a.oof_causal_ema:
1308
  if a.wiki_shield:
1309
  other_neg = [(dom_seq_t[od], 0.90) for od in active_doms if od != d]
1310
+ for bd in sorted(bg_seq_t):
1311
+ other_neg.append((bg_seq_t[bd], 0.92))
1312
  if not other_neg:
1313
  other_neg = [(gen_seq_t, 0.998)]
1314
  gd = SubspaceEnergyGate.fit_oof_from_sequences(
 
1339
  opt_d = torch.optim.AdamW(list(ld.parameters()), lr=a.lr, weight_decay=a.wd)
1340
  bs_d = min(a.bs, len(per_dom_tr[d]))
1341
  steps_d = max(1, int(a.epochs * len(per_dom_tr[d]) / max(1, bs_d)))
1342
+ if a.max_steps > 0:
1343
+ steps_d = min(steps_d, a.max_steps)
1344
  sched_d = torch.optim.lr_scheduler.OneCycleLR(opt_d, max_lr=a.lr, total_steps=steps_d, pct_start=0.1)
1345
  best_va, best_st = float("inf"), None
1346
 
1347
+ # Fast precomputed contiguous h_base cache (1 sequential pass -> kills 5-file random mmap + moe_tail/attn_res!)
1348
+ h_tr_cache = None
1349
+ h_va_cache = None
1350
+ if a.precompute_h:
1351
+ t_pre = time.perf_counter()
1352
+ h_tr_cache = PrecomputedHBaseCache.build(cache, per_dom_tr[d], W0, Wf, c, K, dev, g_row_table=g_row_table)
1353
+ h_va_cache = PrecomputedHBaseCache.build(cache, per_dom_va[d], W0, Wf, c, K, dev, g_row_table=g_row_table)
1354
+ print(f"[Cartridge:{d}] Precomputed contiguous h_base BF16: tr={h_tr_cache.n:,} va={h_va_cache.n:,} "
1355
+ f"({(h_tr_cache.h.nbytes + h_va_cache.h.nbytes)/1e9:.2f} GB) in {time.perf_counter()-t_pre:.1f}s", flush=True)
1356
+
1357
  @torch.no_grad()
1358
+ def eval_d(rows_e, use_cart=True, h_cache_obj=None):
1359
  rr = []
1360
+ if h_cache_obj is not None:
1361
+ for k0 in range(0, h_cache_obj.n, 2048):
1362
+ h, t, gv_c = h_cache_obj.batch(np.arange(k0, min(h_cache_obj.n, k0 + 2048)), dev)
1363
+ lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
1364
+ if use_cart:
1365
+ gv = gv_c if gv_c is not None else gd(h.detach())
1366
+ lg = lg + (gv * _ent_mult(lg)) * ld.delta(h, bf16_amp=a.bf16_amp)
1367
+ rr.append(F.cross_entropy(lg, t, reduction="none").cpu())
1368
+ return float(torch.cat(rr).mean()) if rr else float("inf")
1369
  for k0 in range(0, len(rows_e), 2048):
1370
  r_ch = np.sort(rows_e[k0:k0 + 2048])
1371
  x, acc, p, A, Z, m, t = cache.batch(r_ch, dev)
1372
  h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
1373
+ lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
1374
  if use_cart:
1375
  gv = (torch.from_numpy(g_row_table[r_ch]).to(dev)[:, None] if g_row_table is not None else gd(h.detach()))
1376
+ lg = lg + (gv * _ent_mult(lg)) * ld.delta(h, bf16_amp=a.bf16_amp)
1377
  rr.append(F.cross_entropy(lg, t, reduction="none").cpu())
1378
  return float(torch.cat(rr).mean()) if rr else float("inf")
1379
 
1380
+ va0_d = eval_d(per_dom_va[d], False, h_cache_obj=h_va_cache)
1381
  best_va = va0_d
1382
  best_st = (ld.a.detach().clone(), ld.b.detach().clone())
1383
 
1384
+ t_loop = time.perf_counter()
1385
+ io_acc = 0.0
1386
  for st_i in range(steps_d):
1387
  opt_d.zero_grad(set_to_none=True)
1388
+ t_io0 = time.perf_counter()
1389
+ if h_tr_cache is not None:
1390
+ idx_b = rng.choice(h_tr_cache.n, bs_d, replace=False)
1391
+ h, t, gv_c = h_tr_cache.batch(idx_b, dev)
1392
+ io_acc += time.perf_counter() - t_io0
1393
+ with torch.no_grad():
1394
+ base_lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
1395
+ gv = gv_c if gv_c is not None else gd(h.detach())
1396
+ g_val = gv * _ent_mult(base_lg)
1397
+ else:
1398
+ r_batch = sample_contiguous_blocks(per_dom_tr[d], bs_d, a.block_size, rng)
1399
+ x, acc, p, A, Z, m, t = cache.batch(r_batch, dev)
1400
+ io_acc += time.perf_counter() - t_io0
1401
+ with torch.no_grad():
1402
+ h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
1403
+ base_lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
1404
+ gv = (torch.from_numpy(g_row_table[r_batch]).to(dev)[:, None] if g_row_table is not None else gd(h.detach()))
1405
+ g_val = gv * _ent_mult(base_lg)
1406
+ delta_lg = ld.delta(h, bf16_amp=a.bf16_amp)
1407
+ if a.focal_hard_gamma > 0.0:
1408
+ ce_tok = F.cross_entropy(base_lg + g_val * delta_lg, t, reduction="none")
1409
+ with torch.no_grad():
1410
+ nll_b = F.cross_entropy(base_lg, t, reduction="none")
1411
+ w_f = 1.0 + a.focal_hard_gamma * torch.sigmoid(nll_b - 2.0)
1412
+ w_f = w_f / w_f.mean().clamp_min(1e-6)
1413
+ loss = (ce_tok * w_f).mean()
1414
+ else:
1415
+ loss = F.cross_entropy(base_lg + g_val * delta_lg, t)
1416
  if a.tr_lambda > 0:
1417
+ # Exact algebraic Frobenius TR (0 MB vs 1.34 GB VRAM, mathematically identical to delta_lg.pow(2).mean()!)
1418
+ loss = loss + a.tr_lambda * ld.tr_loss(h)
1419
  loss.backward()
1420
  torch.nn.utils.clip_grad_norm_(list(ld.parameters()), 1.0)
1421
  opt_d.step()
1422
  sched_d.step()
1423
+ if (st_i + 1) % 20 == 0 or st_i == steps_d - 1:
1424
+ s_per_st = (time.perf_counter() - t_loop) / (st_i + 1)
1425
+ print(f"[Cartridge:{d}] step={st_i+1}/{steps_d} loss={float(loss.detach()):.5f} "
1426
+ f"s_per_step={s_per_st:.3f} io_ms={1000.0*io_acc/(st_i+1):.1f}", flush=True)
1427
  if (st_i + 1) % max(1, steps_d // 8) == 0 or st_i == steps_d - 1:
1428
+ vac = eval_d(per_dom_va[d], True, h_cache_obj=h_va_cache)
1429
  if vac < best_va:
1430
  best_va = vac
1431
  best_st = (ld.a.detach().clone(), ld.b.detach().clone())
1432
+ del h_tr_cache, h_va_cache
1433
  with torch.no_grad():
1434
  ld.a.copy_(best_st[0])
1435
  ld.b.copy_(best_st[1])
 
1536
  n_par = sum(p.numel() for p in params)
1537
  print(f"Total trainable params: {n_par:,} (tr_lambda={a.tr_lambda})", flush=True)
1538
 
1539
+ def fwd_train(x, acc, p, A, Z, m, use_trained: bool = True, return_h: bool = False):
1540
  if use_trained and r_lora is not None:
1541
  idx, wts, xl = route(x)
1542
  acc = acc + r_lora.delta_acc(xl, idx, wts, orig_exp, K.situ_mul)
1543
  Wf_c = ({**Wf, "norm": fn_param.to(Wf["norm"].dtype)} if (use_trained and fn_param is not None) else Wf)
1544
  h = K.final_from_terms(p, K.moe_tail(acc, x, Wcur() if use_trained else W0, c), A, Z, m, Wf_c, c)
1545
+ lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
 
1546
  if use_trained and head_lora is not None:
1547
+ raw_d = head_lora.delta(h, bf16_amp=a.bf16_amp)
1548
  d_lg = cg(h.detach()) * raw_d if cg is not None else raw_d
1549
  lg = lg + d_lg
1550
+ return (lg, h) if return_h else lg
1551
+
1552
+ backbone_frozen = (r_lora is None and tail_lora is None and fn_param is None and head_lora is not None)
1553
+ h_tr_dom = h_tr_gen = h_va_dom = h_va_gen = None
1554
+ if backbone_frozen and a.precompute_h:
1555
+ t_pre = time.perf_counter()
1556
+ h_tr_dom = PrecomputedHBaseCache.build(cache, tr_dom, W0, Wf, c, K, dev)
1557
+ h_va_dom = PrecomputedHBaseCache.build(cache, va_dom, W0, Wf, c, K, dev)
1558
+ if len(tr_gen) > 0:
1559
+ h_tr_gen = PrecomputedHBaseCache.build(cache, tr_gen, W0, Wf, c, K, dev)
1560
+ if len(va_gen) > 0:
1561
+ h_va_gen = PrecomputedHBaseCache.build(cache, va_gen, W0, Wf, c, K, dev)
1562
+ gb_tot = sum(hc.h.nbytes for hc in (h_tr_dom, h_va_dom, h_tr_gen, h_va_gen) if hc is not None) / 1e9
1563
+ print(f"[FastHBase] Precomputed contiguous h_base BF16 ({gb_tot:.2f} GB) in {time.perf_counter()-t_pre:.1f}s!", flush=True)
1564
+
1565
+ def eval_nll(rows, use_trained: bool, h_cache_obj=None):
1566
  res = []
1567
  with torch.no_grad():
1568
+ if h_cache_obj is not None:
1569
+ for i in range(0, h_cache_obj.n, 2048):
1570
+ h, t, _ = h_cache_obj.batch(np.arange(i, min(h_cache_obj.n, i + 2048)), dev)
1571
+ lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
1572
+ if use_trained and head_lora is not None:
1573
+ raw_d = head_lora.delta(h, bf16_amp=a.bf16_amp)
1574
+ lg = lg + (cg(h.detach()) * raw_d if cg is not None else raw_d)
1575
+ res.append(F.cross_entropy(lg, t, reduction="none").cpu())
1576
+ return float(torch.cat(res).mean()) if res else None
1577
  for i in range(0, len(rows), 2048):
1578
  x, acc, p, A, Z, m, t = cache.batch(rows[i:i + 2048], dev)
1579
  res.append(F.cross_entropy(fwd_train(x, acc, p, A, Z, m, use_trained), t, reduction="none").cpu())
1580
  return float(torch.cat(res).mean()) if res else None
1581
 
1582
+ val0, vg0 = eval_nll(va_dom, False, h_cache_obj=h_va_dom), eval_nll(va_gen, False, h_cache_obj=h_va_gen)
1583
+ v_id = eval_nll(va_dom, True, h_cache_obj=h_va_dom)
1584
  print(f"val_before={val0:.6f} identity_check={v_id:.6f} val_gen_before={vg0}", flush=True)
1585
 
1586
  opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=a.wd)
1587
  bs_d, bs_g = min(a.bs, len(tr_dom)), min(a.bs // 2, len(tr_gen))
1588
  steps = max(1, int(a.epochs * len(tr_dom) / max(1, bs_d)))
1589
+ if a.max_steps > 0:
1590
+ steps = min(steps, a.max_steps)
1591
  sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=steps, pct_start=0.1)
1592
  best_val, best_snap = val0, [p.detach().cpu().clone() for p in params]
1593
  log = []
1594
+ t_loop = time.perf_counter()
1595
+ io_acc = 0.0
1596
  for step in range(steps):
1597
  opt.zero_grad(set_to_none=True)
1598
+ t_io0 = time.perf_counter()
1599
+ if h_tr_dom is not None:
1600
+ h, t, _ = h_tr_dom.batch(rng.choice(h_tr_dom.n, bs_d, replace=False), dev)
1601
+ io_acc += time.perf_counter() - t_io0
1602
+ with torch.no_grad():
1603
+ base_lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
1604
+ raw_d = head_lora.delta(h, bf16_amp=a.bf16_amp)
1605
+ lg_d = base_lg + (cg(h.detach()) * raw_d if cg is not None else raw_d)
1606
+ loss_d = F.cross_entropy(lg_d, t)
1607
+ if a.tr_lambda > 0:
1608
+ loss_d = loss_d + a.tr_lambda * head_lora.tr_loss(h)
1609
+ ld = float(loss_d.detach())
1610
+ loss_d.backward()
1611
+ del loss_d, lg_d, raw_d, base_lg, h, t
1612
+ else:
1613
+ r_dom_b = sample_contiguous_blocks(tr_dom, bs_d, a.block_size, rng)
1614
+ x, acc, p, A, Z, m, t = cache.batch(r_dom_b, dev)
1615
+ io_acc += time.perf_counter() - t_io0
1616
+ lg_d, h_d = fwd_train(x, acc, p, A, Z, m, True, return_h=True)
1617
+ loss_d = F.cross_entropy(lg_d, t)
1618
+ if a.tr_lambda > 0 and head_lora is not None:
1619
+ loss_d = loss_d + a.tr_lambda * head_lora.tr_loss(h_d)
1620
+ ld = float(loss_d.detach())
1621
+ loss_d.backward()
1622
+ del loss_d, lg_d, h_d, x, acc, p, A, Z, m, t
1623
  kl_v = 0.0
1624
  if a.kl > 0 and bs_g > 0:
1625
+ t_iog = time.perf_counter()
1626
+ if h_tr_gen is not None:
1627
+ hg, _, _ = h_tr_gen.batch(rng.choice(h_tr_gen.n, bs_g, replace=False), dev)
1628
+ io_acc += time.perf_counter() - t_iog
1629
+ with torch.no_grad():
1630
+ base_g = (hg.to(lm_head.dtype) @ lm_head.t()).float()
1631
+ ref = F.log_softmax(base_g, -1)
1632
+ raw_dg = head_lora.delta(hg, bf16_amp=a.bf16_amp)
1633
+ cur = F.log_softmax(base_g + (cg(hg.detach()) * raw_dg if cg is not None else raw_dg), -1)
1634
+ kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
1635
+ kl_v = float(kl.detach())
1636
+ (a.kl * kl).backward()
1637
+ del kl, cur, ref, raw_dg, base_g, hg
1638
+ else:
1639
+ r_gen_b = sample_contiguous_blocks(tr_gen, bs_g, a.block_size, rng)
1640
+ xg, accg, pg, Ag, Zg, mg, _ = cache.batch(r_gen_b, dev)
1641
+ io_acc += time.perf_counter() - t_iog
1642
+ with torch.no_grad():
1643
+ ref = F.log_softmax(fwd_train(xg, accg, pg, Ag, Zg, mg, False), -1)
1644
+ cur = F.log_softmax(fwd_train(xg, accg, pg, Ag, Zg, mg, True), -1)
1645
+ kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
1646
+ kl_v = float(kl.detach())
1647
+ (a.kl * kl).backward()
1648
+ del kl, cur, ref, xg, accg, pg, Ag, Zg, mg
1649
  torch.nn.utils.clip_grad_norm_(params, 1.0)
1650
  opt.step()
1651
  sched.step()
1652
  if step % 20 == 0 or step == steps - 1:
1653
+ s_per_st = (time.perf_counter() - t_loop) / (step + 1)
1654
+ rec = {"step": step, "loss_domain": ld, "loss_kl": kl_v,
1655
+ "s_per_step": round(s_per_st, 3), "io_ms": round(1000.0 * io_acc / (step + 1), 1)}
1656
  log.append(rec)
1657
  print(json.dumps(rec), flush=True)
1658
  if (step + 1) % max(1, steps // 8) == 0 or step == steps - 1:
1659
+ vc = eval_nll(va_dom, True, h_cache_obj=h_va_dom)
1660
+ vgc = eval_nll(va_gen, True, h_cache_obj=h_va_gen)
1661
  gen_ok_now = (vg0 is None or vgc is None or ((vgc - vg0) / vg0) <= 0.005)
1662
  if vc is not None and gen_ok_now and vc < best_val:
1663
  best_val = vc
 
1667
  for p, s_t in zip(params, best_snap):
1668
  p.copy_(s_t.to(dev))
1669
 
1670
+ val1, vg1 = eval_nll(va_dom, True, h_cache_obj=h_va_dom), eval_nll(va_gen, True, h_cache_obj=h_va_gen)
1671
  rel_d = (val1 - val0) / val0
1672
  rel_g = None if (vg0 is None or vg1 is None) else (vg1 - vg0) / vg0
1673
  print(f"val_after={val1:.6f} rel_dom={rel_d:+.5f} rel_gen={rel_g}", flush=True)