File size: 22,771 Bytes
f80e81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
"""Trinity H2b: UNFREEZE real routed experts of layer 92 and train them (weight-space programming on existing experts).



The k3pass cache stores, per token, the MoE input x and the routed latent sum acc (fp32, before routed_expert_norm).

With the original routing kept fixed (same top-16 selection and weights as the model), the effect of changing the

weights of a set H of experts is exact and local:

    acc' = acc + sum_{e in H, e selected} w_e * ( f_e'(xl) - f_e(xl) ),   xl = x @ routed_expert_down_proj^T

where f_e is the expert SwiGLU (SITU) in the 3584-d latent. H = the K experts most used by the training domain

tokens (counted on the cache, not on the holdout). At step 0 f_e' = f_e, so the model is exactly Trinity (tested).

The router is not trained in this step (a changed selection would need outputs of experts that are not in H).



    python lb_unfreeze.py train --cache DIR --out DIR [--k 16 --lr 1e-5 --epochs 2]

    python lb_unfreeze.py eval  --cache DIR --trained DIR/experts.pt --out DIR

    python lb_unfreeze.py selftest

"""
from __future__ import annotations

import argparse
import json
import math
import sys
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F

BETA, LINB = 4.0, 25.0                                    # SITU activation of Kimi K3.1 (k3ref docstring)


def expert_out(xl, w1, w2, w3, situ_mul, beta=BETA, lin_b=LINB):
    return (situ_mul(xl @ w1.t(), xl @ w3.t(), beta, lin_b)) @ w2.t()


def delta_acc(xl, idx, wts, hot, orig, train, situ_mul):
    """Exact change of the routed sum when experts in `hot` take the `train` weights instead of `orig`."""
    d = torch.zeros(xl.shape[0], orig[0][1].shape[0], device=xl.device, dtype=torch.float32)
    for j, e in enumerate(hot):
        sel = (idx == e)
        rows = sel.any(-1).nonzero(as_tuple=True)[0]
        if len(rows) == 0:
            continue
        w = (wts * sel).sum(-1)[rows].float()
        x_ = xl[rows]
        new = expert_out(x_.float(), *[t.float() for t in train[j]], situ_mul)
        with torch.no_grad():
            old = expert_out(x_, *orig[j], situ_mul).float()
        d = d.index_add(0, rows, (new - old) * w[:, None])
    return d


def easy_kl_domain_loss(

    cur_logits: torch.Tensor,

    targets: torch.Tensor,

    ref_nll: torch.Tensor | None = None,

    ref_logp_easy: torch.Tensor | None = None,

    easy_kl: float = 0.0,

    easy_thresh: float = 0.5,

    hard_weight: float = 1.0,

    hard_thresh: float = 2.0,

) -> tuple[torch.Tensor, dict[str, float]]:
    """Domain loss with optional easy-token KL anchor & hard-token upweighting (NEXUS Patch 26, MSG-20261121-0067).



    When `easy_kl == 0.0` and `hard_weight == 1.0`, reduces bit-identically to standard `F.cross_entropy`.

    When active:

      - Tokens where reference Trinity has `ref_nll < easy_thresh` (default 0.5 nats, where LB-B2 degraded +11.6%)

        are EXCLUDED from CE push and instead anchored to Trinity via `easy_kl * KL(ref || cur)`.

      - Remaining tokens receive weighted CE (`hard_weight` for `ref_nll >= hard_thresh`, `1.0` for mid tokens).

    """
    if easy_kl <= 0.0 and abs(hard_weight - 1.0) < 1e-9:
        loss = F.cross_entropy(cur_logits, targets)
        return loss, {"loss_ce": float(loss.detach()), "loss_easy_kl": 0.0, "easy_frac": 0.0, "hard_frac": 0.0}
    assert ref_nll is not None, "ref_nll required when easy_kl > 0 or hard_weight != 1.0"
    easy = ref_nll < easy_thresh
    hard = ref_nll >= hard_thresh
    ce_tok = F.cross_entropy(cur_logits, targets, reduction="none")
    w_tok = torch.where(hard, torch.full_like(ce_tok, float(hard_weight)), torch.ones_like(ce_tok))
    non_easy = ~easy
    if non_easy.any():
        w_active = w_tok * non_easy.to(ce_tok.dtype)
        ce_loss = (ce_tok * w_active).sum() / w_active.sum().clamp_min(1e-8)
    else:
        ce_loss = cur_logits.new_zeros(())
    kl_easy = cur_logits.new_zeros(())
    if easy_kl > 0.0 and easy.any():
        assert ref_logp_easy is not None, "ref_logp_easy required when easy_kl > 0 and easy tokens exist"
        cur_logp_easy = F.log_softmax(cur_logits[easy], dim=-1)
        kl_easy = F.kl_div(cur_logp_easy, ref_logp_easy.float(), log_target=True, reduction="batchmean")
    total = ce_loss + float(easy_kl) * kl_easy
    return total, {
        "loss_ce": float(ce_loss.detach()),
        "loss_easy_kl": float(kl_easy.detach()),
        "easy_frac": float(easy.float().mean().item()),
        "hard_frac": float(hard.float().mean().item()),
    }


def make_domain_filter(domains_arg: str = ""):
    """Return predicate(meta) matching non-general domain rows, optionally restricted to `--domains chips,space` (Patch 27).



    Empty `--domains` preserves exact legacy behavior (all non-wikipedia/non-general sets).

    Non-empty `--domains` (comma-separated, case-insensitive) matches exact set names or domain tokens such as

    `chips`, `train_chips`, `holdout_chips`, `space`, `train_space`, etc., always excluding general/wikipedia sets.

    """
    wanted = [d.strip().lower() for d in (domains_arg or "").split(",") if d.strip()]

    def _pred(m: dict) -> bool:
        s = str(m.get("set", "")).lower()
        if s == "wikipedia" or s.startswith("general"):
            return False
        if not wanted:
            return True
        tokens = set(s.replace("-", "_").split("_"))
        return any(w == s or w in tokens or s.startswith(w + "_") or s.endswith("_" + w) for w in wanted)

    return _pred


def selftest() -> int:
    import k3ref as K
    torch.manual_seed(0)
    n, D, L, H, E, k = 64, 16, 8, 12, 6, 2
    xl = torch.randn(n, L)
    idx = torch.stack([torch.randperm(E)[:k] for _ in range(n)])
    wts = torch.softmax(torch.randn(n, k), -1)
    orig = [tuple(torch.randn(*s) * 0.3 for s in ((H, L), (D, H), (H, L))) for _ in range(3)]
    hot = [0, 2, 5]
    train = [tuple(torch.nn.Parameter(t.clone()) for t in o) for o in orig]
    d0 = delta_acc(xl, idx, wts, hot, orig, train, K.situ_mul)
    ident = float(d0.abs().max()) == 0.0
    params = [p for t in train for p in t]
    before = [p.detach().clone() for p in params]
    opt = torch.optim.AdamW(params, lr=1e-2)
    for _ in range(2):
        opt.zero_grad()
        loss = (delta_acc(xl, idx, wts, hot, orig, train, K.situ_mul) - 1.0).pow(2).mean()
        loss.backward()
        opt.step()
    dW = sum(float((p.detach() - b).abs().sum()) for p, b in zip(params, before))
    # Functional CPU test of --easy-kl + --hard-weight (Patch 26, MSG-20261121-0067)
    vocab = 32
    head_w = torch.randn(vocab, D) * 0.5
    base_h = torch.randn(n, D) * 0.4
    tgt = torch.randint(0, vocab, (n,))
    # Make first half easy tokens (ref NLL < 0.5) and second half hard tokens (ref NLL >= 2.0)
    ref_logits = (base_h @ head_w.t())
    ref_logits[: n // 2, :] = -4.0
    for i in range(n // 2):
        ref_logits[i, tgt[i]] = 4.0
    ref_nll = F.cross_entropy(ref_logits, tgt, reduction="none")
    easy_mask = ref_nll < 0.5
    ref_logp_e = F.log_softmax(ref_logits[easy_mask], dim=-1)
    train_ek = [tuple(torch.nn.Parameter(t.clone()) for t in o) for o in orig]
    ek_params = [p for t in train_ek for p in t]
    ek_before = [p.detach().clone() for p in ek_params]
    # Step 0 identity: delta_acc == 0 => cur_logits == ref_logits => kl_easy == 0.0 exact!
    cur0 = ref_logits + delta_acc(xl, idx, wts, hot, orig, train_ek, K.situ_mul) @ head_w.t()
    l0, m0 = easy_kl_domain_loss(cur0, tgt, ref_nll, ref_logp_e, easy_kl=1.0, easy_thresh=0.5, hard_weight=2.0)
    ek_ident_zero = (m0["loss_easy_kl"] <= 1e-6) and (m0["easy_frac"] > 0.3) and (m0["hard_frac"] > 0.2)
    opt_ek = torch.optim.AdamW(ek_params, lr=2e-2)
    for _ in range(3):
        opt_ek.zero_grad()
        cur = ref_logits + delta_acc(xl, idx, wts, hot, orig, train_ek, K.situ_mul) @ head_w.t()
        lek, mek = easy_kl_domain_loss(cur, tgt, ref_nll, ref_logp_e, easy_kl=1.0, easy_thresh=0.5, hard_weight=2.0)
        lek.backward()
        opt_ek.step()
    ek_dW = sum(float((p.detach() - b).abs().sum()) for p, b in zip(ek_params, ek_before))
    # Functional CPU test of --domains chips,space filter & per-domain hot expert counting (Patch 27, MSG-20261121-0071)
    f_cs = make_domain_filter("chips,space")
    f_all = make_domain_filter("")
    mock_meta = [
        {"set": "train_chips", "role": "train"},
        {"set": "space", "role": "train"},
        {"set": "train_physics", "role": "train"},
        {"set": "chemistry", "role": "train"},
        {"set": "wikipedia", "role": "train"},
        {"set": "general_replay_cc0", "role": "train"},
    ]
    cs_selected = [m["set"] for m in mock_meta if f_cs(m)]
    all_selected = [m["set"] for m in mock_meta if f_all(m)]
    dom_filter_ok = (cs_selected == ["train_chips", "space"]) and (all_selected == ["train_chips", "space", "train_physics", "chemistry"])
    # Verify per-domain hot-expert selection picks different experts when domain routing differs
    idx_chips_space = torch.tensor([[1, 4]] * 20)
    idx_other = torch.tensor([[0, 3]] * 40)
    c_cs = torch.bincount(idx_chips_space.reshape(-1), minlength=E).float()
    c_all = torch.bincount(torch.cat([idx_chips_space, idx_other]).reshape(-1), minlength=E).float()
    hot_cs = sorted(c_cs.topk(2).indices.tolist())
    hot_all = sorted(c_all.topk(2).indices.tolist())
    dom_hot_distinct_ok = (hot_cs == [1, 4]) and (hot_all == [0, 3])
    res = {
        "identity_at_init": ident,
        "delta_W": dW,
        "delta_W_nonzero": dW > 0,
        "loss_finite": math.isfinite(float(loss.detach())),
        "easy_kl_identity_zero": ek_ident_zero,
        "easy_kl_delta_W": ek_dW,
        "easy_kl_delta_W_nonzero": ek_dW > 0,
        "easy_kl_loss_finite": math.isfinite(float(lek.detach())),
        "easy_kl_final_stats": mek,
        "domain_filter_ok": dom_filter_ok,
        "domain_hot_distinct_ok": dom_hot_distinct_ok,
    }
    print(json.dumps(res))
    ok_all = (res["identity_at_init"] and res["delta_W_nonzero"] and res["loss_finite"]
              and res["easy_kl_identity_zero"] and res["easy_kl_delta_W_nonzero"] and res["easy_kl_loss_finite"]
              and res["domain_filter_ok"] and res["domain_hot_distinct_ok"])
    return 0 if ok_all else 1


def main() -> int:
    if len(sys.argv) > 1 and sys.argv[1] == "selftest":
        return selftest()
    import os
    import k3pass as KP
    import k3ref as K
    import lb_tail_train as TT
    from huggingface_hub import hf_hub_download
    from safetensors import safe_open
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["train", "eval"])
    ap.add_argument("--cache", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--trained", default="")
    ap.add_argument("--k", type=int, default=16)
    ap.add_argument("--lr", type=float, default=1e-5)
    ap.add_argument("--epochs", type=float, default=2.0)
    ap.add_argument("--bs", type=int, default=2048)
    ap.add_argument("--kl", type=float, default=1.0)
    ap.add_argument("--val-frac", type=float, default=0.1)
    ap.add_argument("--seed", type=int, default=20261119)
    ap.add_argument("--opt", choices=["adamw", "adafactor"], default="adamw")  # adafactor: ~8 B/param, for large K
    ap.add_argument("--easy-kl", type=float, default=0.0, help="KL weight anchoring easy domain tokens (ref NLL < --easy-thresh) to base Trinity")
    ap.add_argument("--easy-thresh", type=float, default=0.5, help="NLL threshold (nats) below which domain tokens are treated as easy")
    ap.add_argument("--hard-weight", type=float, default=1.0, help="CE weight multiplier for hard domain tokens (ref NLL >= --hard-thresh)")
    ap.add_argument("--hard-thresh", type=float, default=2.0, help="NLL threshold (nats) above which domain tokens are upweighted")
    ap.add_argument("--domains", default="", help="comma-separated target domains for WSP (e.g. chips,space); empty = all non-general domains")
    a = ap.parse_args()
    dev = torch.device("cuda")
    tok = os.environ.get("HF_TOKEN")
    c = K.Cfg(json.loads(Path(hf_hub_download(TT.BASE, "config.json")).read_text())["text_config"])
    cache = TT.Cache(Path(a.cache))
    W0, Wf, lm_head = TT.load_tail(dev, tok)
    f93 = safe_open(hf_hub_download(TT.REPO, "model-00093-of-000096.safetensors", token=tok), framework="pt", device="cpu")
    L92 = KP.layer_weights(f93, 92, dev)
    gate, bias, down = L92["gate"].float(), L92["e_score_correction_bias"].float(), L92["routed_expert_down_proj"]
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)

    def route(x):
        with torch.no_grad():
            s = torch.sigmoid(x.float() @ gate.t())
            idx = (s + bias).topk(c.topk, dim=-1).indices
            w = s.gather(1, idx)
            return idx, w / w.sum(-1, keepdim=True), x @ down.t()

    def logits(x, acc, p, A, Z, m, hot, orig, train):
        if hot:
            idx, wts, xl = route(x)
            acc = acc + delta_acc(xl, idx, wts, hot, orig, train, K.situ_mul)
        h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
        return h @ lm_head.t()

    def nll(rows, hot, orig, train, bs=2048):
        res = []
        with torch.no_grad():
            for i in range(0, len(rows), bs):
                x, acc, p, A, Z, m, t = cache.batch(rows[i:i + bs], dev)
                res.append(F.cross_entropy(logits(x, acc, p, A, Z, m, hot, orig, train).float(), t, reduction="none").cpu())
        return torch.cat(res) if res else torch.zeros(0)

    if a.cmd == "eval":
        st = torch.load(a.trained, weights_only=True)
        hot = st["hot"]
        orig = [L92["experts"](e) for e in hot]
        train = [tuple(t.to(dev) for t in st["experts"][j]) for j in range(len(hot))]
        s = json.loads((Path(a.cache) / "streams.json").read_text())
        pass_nll = np.load(Path(a.cache) / "nll.npy")
        T = s["seq"]
        res, raw = {"per_set": {}}, {}
        for sname in sorted({m["set"] for m in cache.meta if m["role"] == "holdout"}):
            seqs = [i for i, m in enumerate(cache.meta) if m["role"] == "holdout" and m["set"] == sname]
            per = {"lb": [], "lb_unfrozen": [], "base": []}
            for i in seqs:
                rows = np.arange(i * T, (i + 1) * T - 1)
                lb = nll(rows, [], None, None).numpy()
                tu = nll(rows, hot, orig, train).numpy()
                raw[f"{sname}/{i}/lb"], raw[f"{sname}/{i}/lb_unfrozen"] = lb.astype(np.float32), tu.astype(np.float32)
                per["lb"].append(lb.mean())
                per["lb_unfrozen"].append(tu.mean())
                if [i, "base"] in s["streams"]:
                    b = np.asarray(pass_nll[s["streams"].index([i, "base"])], dtype=np.float32)
                    raw[f"{sname}/{i}/base"] = b
                    per["base"].append(b.mean())
            r = {k: float(np.mean(v)) for k, v in per.items() if v}
            if per["base"]:
                b, rng = np.array(per["base"]), np.random.default_rng(0)
                for k_ in ("lb", "lb_unfrozen"):
                    d = (np.array(per[k_]) - b) / b
                    bs_ = [float(rng.choice(d, len(d)).mean()) for _ in range(2000)]
                    r[f"{k_}_vs_base_rel"] = float(d.mean())
                    r[f"{k_}_vs_base_ci95"] = [float(np.percentile(bs_, 2.5)), float(np.percentile(bs_, 97.5))]
            r["n_seqs"] = len(seqs)
            res["per_set"][sname] = r
        dom = {k_: v for k_, v in res["per_set"].items() if k_ != "wikipedia" and not k_.startswith("general")}
        gen = [v for k_, v in res["per_set"].items() if k_ == "wikipedia" or k_.startswith("general")]
        wins = sum(1 for v in dom.values() if v.get("lb_unfrozen_vs_base_rel", 1) <= -0.02)
        gen_ok = bool(gen) and all(v.get("lb_unfrozen_vs_base_rel", 1) <= 0.005 for v in gen)
        res["acceptance"] = {"domain_sets_meeting_-2%": f"{wins}/{len(dom)}", "general_ok": gen_ok,
                             "verdict": "PASS" if wins >= 2 and gen_ok else "FAIL"}
        np.savez_compressed(out / "verdict_h2b.raw.npz", **raw)
        (out / "verdict_h2b.json").write_text(json.dumps(res, indent=1))
        print(json.dumps(res["acceptance"]), json.dumps(res["per_set"], indent=1))
        return 0

    torch.manual_seed(a.seed)
    rng = np.random.default_rng(a.seed)                   # same split as lb_tail_train.py (LB-B)
    train_seq = [i for i, m in enumerate(cache.meta) if m["role"] == "train"]
    rng.shuffle(train_seq)
    val_seq = set(train_seq[:max(1, int(len(train_seq) * a.val_frac))])
    dom = make_domain_filter(a.domains)
    is_gen = lambda m: m["set"] == "wikipedia" or str(m["set"]).startswith("general")  # noqa: E731
    tr_dom = cache.rows(lambda i, m: m["role"] == "train" and dom(m) and i not in val_seq)
    tr_gen = cache.rows(lambda i, m: m["role"] == "train" and is_gen(m) and i not in val_seq)
    va_dom = cache.rows(lambda i, m: m["role"] == "train" and dom(m) and i in val_seq)
    va_gen = cache.rows(lambda i, m: m["role"] == "train" and is_gen(m) and i in val_seq)
    if len(tr_dom) == 0:
        raise SystemExit(f"no training domain tokens matched --domains={a.domains!r}")
    counts = torch.zeros(gate.shape[0], device=dev)
    for i in range(0, len(tr_dom), 4096):                # expert usage of the TRAINING domain tokens only
        x = cache.batch(tr_dom[i:i + 4096], dev)[0]
        counts += torch.bincount(route(x)[0].reshape(-1), minlength=gate.shape[0]).float()
    hot = counts.topk(a.k).indices.tolist()
    orig = [L92["experts"](e) for e in hot]
    train = [tuple(torch.nn.Parameter(t.float().clone()) for t in o) for o in orig]
    params = [p for t in train for p in t]
    n_par = sum(p.numel() for p in params)
    print("unfrozen experts", hot, "parameters", n_par, "share of domain routing",
          round(float(counts[hot].sum() / counts.sum()), 4), flush=True)
    val0 = float(nll(va_dom, [], None, None).mean())
    vg0 = float(nll(va_gen, [], None, None).mean()) if len(va_gen) else None
    v_id = float(nll(va_dom, hot, orig, train).mean())
    print("validation before", val0, "identity check", v_id, flush=True)
    opt = (torch.optim.Adafactor(params, lr=a.lr, weight_decay=0.0) if a.opt == "adafactor"
           else torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0))
    if torch.cuda.is_available():
        print("gpu memory after setup GiB", round(torch.cuda.memory_allocated() / 2**30, 2), flush=True)
    bs_d, bs_g = min(a.bs, len(tr_dom)), min(a.bs // 2, len(tr_gen))
    steps = max(1, int(a.epochs * len(tr_dom) / max(1, bs_d)))
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=steps, pct_start=0.1,
                                                cycle_momentum=a.opt != "adafactor")  # Adafactor has no momentum
    log = []
    for step in range(steps):
        opt.zero_grad(set_to_none=True)
        x, acc, p, A, Z, m, t = cache.batch(rng.choice(tr_dom, bs_d, replace=False), dev)
        use_ek = (a.easy_kl > 0.0) or (abs(a.hard_weight - 1.0) >= 1e-9)
        ref_nll, ref_logp_e = None, None
        if use_ek:
            # VRAM-safe: compute reference NLL & easy-token log-probs in no_grad and FREE full ref_logits before grad forward!
            with torch.no_grad():
                ref_log = logits(x, acc, p, A, Z, m, [], None, None).float()
                ref_nll = F.cross_entropy(ref_log, t, reduction="none")
                if a.easy_kl > 0.0:
                    em = ref_nll < a.easy_thresh
                    if em.any():
                        ref_logp_e = F.log_softmax(ref_log[em], dim=-1).to(torch.bfloat16)
                del ref_log
        cur_log = logits(x, acc, p, A, Z, m, hot, orig, train).float()
        ld, ek_stats = easy_kl_domain_loss(
            cur_log, t, ref_nll=ref_nll, ref_logp_easy=ref_logp_e,
            easy_kl=a.easy_kl, easy_thresh=a.easy_thresh, hard_weight=a.hard_weight, hard_thresh=a.hard_thresh,
        )
        ldv = float(ld.detach())
        ld.backward()
        del ld, cur_log, ref_nll, ref_logp_e, x, acc, p, A, Z, m, t
        klv = 0.0
        if a.kl > 0 and bs_g > 0:
            xg, accg, pg, Ag, Zg, mg, _ = cache.batch(rng.choice(tr_gen, bs_g, replace=False), dev)
            with torch.no_grad():
                ref = F.log_softmax(logits(xg, accg, pg, Ag, Zg, mg, [], None, None).float(), -1)
            cur = F.log_softmax(logits(xg, accg, pg, Ag, Zg, mg, hot, orig, train).float(), -1)
            kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
            klv = float(kl.detach())
            (a.kl * kl).backward()
            del kl, cur, ref
        torch.nn.utils.clip_grad_norm_(params, 1.0)
        opt.step()
        sched.step()
        if step % 20 == 0 or step == steps - 1:
            log.append({"step": step, "loss_domain": ldv, "loss_kl": klv, "loss_easy_kl": ek_stats["loss_easy_kl"], "easy_frac": ek_stats["easy_frac"]})
            print(json.dumps(log[-1]), flush=True)
    val1 = float(nll(va_dom, hot, orig, train).mean())
    vg1 = float(nll(va_gen, hot, orig, train).mean()) if len(va_gen) else None
    dW = sum(float((p.detach() - o.float()).abs().sum()) for t, oo in zip(train, orig) for p, o in zip(t, oo))
    torch.save({"hot": hot, "experts": [tuple(p.detach().to(torch.bfloat16).cpu() for p in t) for t in train]},
               out / "experts.pt")
    rec = {"args": vars(a), "domains_filter": a.domains or "ALL", "tr_dom_tokens": int(len(tr_dom)),
           "va_dom_tokens": int(len(va_dom)), "unfrozen_experts": hot, "trained_parameters": n_par, "val_before": val0,
           "identity_check": v_id, "val_after": val1, "val_gen_before": vg0, "val_gen_after": vg1,
           "rel_dom": (val1 - val0) / val0, "rel_gen": None if not vg0 else (vg1 - vg0) / vg0,
           "delta_W_abs_sum": dW, "steps": steps, "log": log,
           "domain_routing_share": float(counts[hot].sum() / counts.sum()),
           "peak_gpu_gib": (torch.cuda.max_memory_allocated() / 2**30) if torch.cuda.is_available() else None}
    (out / "train_record.json").write_text(json.dumps(rec, indent=1))
    print("RECORD", json.dumps({k_: rec[k_] for k_ in ("trained_parameters", "rel_dom", "rel_gen", "identity_check",
                                                        "val_before", "steps")}), flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())