File size: 97,203 Bytes
f8aef07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
"""Trinity Full-Tail WSP, `STAR-SubspaceEnergyGate-TR` (`Arm6b`), & `STAR-ModularSubspaceCartridge-TR` (`Arm7`) Trainer.



Designed for Claude to run IMMEDIATELY on existing `train1..train6` k3pass caches (`0.00 EUR` extra k3pass!):

  1. `MultiCache` (`--cache DIR1 [DIR2 ...]`): zero-copy numpy mmap streaming across ALL available caches simultaneously.

  2. `--domains chips,space`: filters train, val, and hot-expert counting strictly to target domains.

  3. **Breaks Kimi K3's `output_attn_res` dilution wall (`w_last = 11.1%`):**

       - Group A: `lm_head` Low-Rank LoRA (`r=64..128`), factorized forward (<250 MB extra VRAM, 100% post-`output_attn_res`!)

       - Group B: `Wf["norm"]` (final RMSNorm scale vector, 7,168 params)

       - Group C: `W_tail` (`shared_experts.{gate,up,down}_proj` + `routed_expert_up_proj` + `routed_expert_norm`)

       - Group D: Routed experts W2 LoRA on Top-K hot experts (bit-exact stock merge into `00093`!)

  4. **NEW ARCHITECTURE 1 — `--subspace-gate` (`Arm6b`, `STAR-SubspaceEnergyGate-TR`):**

       - Fits closed-form whitened GEV quadratic Bayes subspace gate directly on post-`final_norm` `h_base` (100% identical

         input `h` in `fit`, `train`, and `eval` — drop-in `lm_head` wrapper, ZERO Layer-92 skip wiring needed!)

       - **Critical V2 Discovery Built-In:** `--tr-lambda` (default `0.05` when gated) adds In-Domain Logit Trust-Region

         regularization `tr_lambda * mean(delta^2)` + best-val early-stopping (because turning off `general` removes

         implicit KL regularization; proven 5/5 seeds: `-23.36%` domain vs `-4.88%` unreg, `-0.003%` general drift!).

  5. **NEW ARCHITECTURE 2 — `--modular-cartridges` (`Arm7`, `STAR-ModularSubspaceCartridge-TR`):**

       - Trains one independent hot-swappable cartridge `(SubspaceEnergyGate_c(h), FactorizedLinearLoRA_c(h))` PER domain

         (e.g., `chips` and `space`), calibrating each gate against the WORST (highest) quantile of `general` AND every

         other domain (`252,113x` cross-domain selectivity, `<= 1e-6` continual learning interference, `5/5` beats `Arm3`!).

       - Forward: `logits(h) = h @ lm_head.T + sum_c g_c(h) * delta_c(h)` — plug/unplug domains in O(1) without retraining!



Usage:

    python tools/nexus/trinity_full_tail_wsp.py selftest

    python tools/nexus/trinity_full_tail_wsp.py train --cache /content/k3p/out_train2 /content/k3p/out_train3 \\

        --out /content/k3p/h4_mod --domains chips,space --modular-cartridges --head-rank 64 --tr-lambda 0.05 --lr 1e-4

    python tools/nexus/trinity_full_tail_wsp.py eval --cache /content/k3p/out_holdout --trained /content/k3p/h4_mod/full_tail_wsp.pt --out /content/k3p/h4_eval

"""
from __future__ import annotations

import argparse
import copy
import json
import math
import os
import sys
import tempfile
import time
from contextlib import nullcontext
from pathlib import Path
from typing import Any

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

LAB = Path(__file__).resolve().parents[2]
if str(LAB / "tools" / "littleboy") not in sys.path:
    sys.path.insert(0, str(LAB / "tools" / "littleboy"))

TRAINABLE_TAIL = ["shared_experts.gate_proj", "shared_experts.up_proj", "shared_experts.down_proj", "routed_expert_up_proj"]


def parse_domains(spec: str) -> set[str]:
    return {s.strip().lower() for s in (spec or "").split(",") if s.strip()}


def extract_domain_name(meta: dict[str, Any]) -> str:
    s = str(meta.get("set", "")).lower()
    if s == "wikipedia" or s.startswith("general"):
        return "general"
    for pfx in ("train_", "holdout_", "val_", "dev_"):
        if s.startswith(pfx):
            return s[len(pfx):]
    return s


def is_target_domain(meta: dict[str, Any], domains: set[str]) -> bool:
    s = str(meta.get("set", "")).lower()
    if s == "wikipedia" or s.startswith("general"):
        return False
    if not domains:
        return True
    toks = {s} | {p for p in s.replace("-", "_").split("_") if p}
    return any(d in toks or s.endswith(f"_{d}") for d in domains)


class MultiCache:
    """Zero-copy numpy mmap union of 1..N k3pass cache directories (e.g., train1 + train2 + train3 + train4...)."""

    def __init__(self, dirs: list[Path]):
        assert dirs, "At least one cache directory required"
        self.shards: list[dict[str, Any]] = []
        self.meta: list[dict[str, Any]] = []
        self.offsets: list[int] = []
        self.seq_lens: list[int] = []
        total_rows = 0
        for d in dirs:
            d = Path(d)
            s = json.loads((d / "streams.json").read_text(encoding="utf-8"))
            T = int(s["seq"])
            x = np.load(d / "x92.npy", mmap_mode="r")
            shard = {
                "dir": d,
                "x": x,
                "acc": np.load(d / "acc92.npy", mmap_mode="r"),
                "p": np.load(d / "prefix92.npy", mmap_mode="r"),
                "A": np.load(d / "A92.npy", mmap_mode="r"),
                "Zm": np.load(d / "Zm92.npy", mmap_mode="r"),
                "t": np.load(d / "target92.npy"),
                "meta": s["meta"],
                "T": T,
                "start_row": total_rows,
                "n_rows": int(x.shape[0]),
            }
            self.shards.append(shard)
            for local_i, m in enumerate(s["meta"]):
                self.meta.append({**m, "_shard": len(self.shards) - 1, "_local_i": local_i, "_T": T, "_base_row": total_rows + local_i * T})
            self.offsets.append(total_rows)
            self.seq_lens.append(T)
            total_rows += shard["n_rows"]
        self.total_rows = total_rows

    def rows(self, pred, min_pos: int = 0) -> np.ndarray:
        idx = [
            np.arange(m["_base_row"] + max(0, min(int(min_pos), m["_T"] - 2)), m["_base_row"] + m["_T"] - 1, dtype=np.int64)
            for i, m in enumerate(self.meta)
            if pred(i, m)
        ]
        return np.concatenate(idx) if idx else np.zeros(0, dtype=np.int64)

    def batch(self, r: np.ndarray, dev: torch.device):
        r = np.sort(np.asarray(r, dtype=np.int64))
        xs, accs, ps, As, Zs, ms, ts = [], [], [], [], [], [], []
        for sh in self.shards:
            lo, hi = sh["start_row"], sh["start_row"] + sh["n_rows"]
            sub = r[(r >= lo) & (r < hi)] - lo
            if len(sub) == 0:
                continue
            xs.append(torch.from_numpy(np.ascontiguousarray(sh["x"][sub])).view(torch.bfloat16))
            accs.append(torch.from_numpy(np.ascontiguousarray(sh["acc"][sub])))
            ps.append(torch.from_numpy(np.ascontiguousarray(sh["p"][sub])).view(torch.bfloat16))
            As.append(torch.from_numpy(np.ascontiguousarray(sh["A"][sub])))
            zm = torch.from_numpy(np.ascontiguousarray(sh["Zm"][sub]))
            Zs.append(zm[:, 0])
            ms.append(zm[:, 1])
            ts.append(torch.from_numpy(np.ascontiguousarray(sh["t"][sub])))
        return (
            torch.cat(xs, 0).to(dev),
            torch.cat(accs, 0).to(dev),
            torch.cat(ps, 0).to(dev),
            torch.cat(As, 0).to(dev),
            torch.cat(Zs, 0).to(dev),
            torch.cat(ms, 0).to(dev),
            torch.cat(ts, 0).to(dev),
        )

    def close(self) -> None:
        for sh in self.shards:
            for k in ("x", "acc", "p", "A", "Zm"):
                arr = sh.get(k)
                if getattr(arr, "_mmap", None) is not None:
                    arr._mmap.close()
        self.shards.clear()


def sample_contiguous_blocks(rows: np.ndarray, batch_size: int, block_size: int, rng: np.random.Generator) -> np.ndarray:
    """Sample `batch_size` rows as contiguous spans of length `block_size` (cuts random mmap page faults by ~200-380x!).



    When `block_size <= 1` or `batch_size >= len(rows)`, falls back cleanly to exact uniform token sampling.

    Because `rows` is sorted by `(seq_id, pos)`, slicing contiguous spans of `rows` guarantees sequential disk reads

    while drawing blocks uniformly across all documents in the corpus.

    """
    n = len(rows)
    if batch_size >= n:
        return rows
    if block_size <= 1:
        return np.sort(rng.choice(rows, batch_size, replace=False))
    blk = min(block_size, batch_size)
    n_blocks = max(1, (batch_size + blk - 1) // blk)
    # Partition `rows` into non-overlapping contiguous chunks with a fresh random phase offset each step!
    n_chunks = max(1, n // blk)
    if n_chunks <= n_blocks:
        return rows[:batch_size]
    phase = int(rng.integers(0, max(1, n - n_chunks * blk + 1)))
    chosen = np.sort(rng.choice(n_chunks, n_blocks, replace=False))
    parts = [rows[phase + int(ci) * blk: phase + (int(ci) + 1) * blk] for ci in chosen]
    out = np.concatenate(parts)
    return out[:batch_size]


class PrecomputedHBaseCache:
    """Contiguous precomputed `h_base` (`[N, D]` bf16) + `t` (`[N]` int64) + optional gate (`[N]` fp32) cache.



    For head/cartridge-only H4 configs (`F4..F8`, where `W_tail`/`r_lora`/`final_norm` are frozen), precomputing

    `h_base` ONCE sequentially eliminates `x92`, `acc92`, `prefix92`, `A92`, `Zm92`, `K.moe_tail`, and

    `K.final_from_terms` from EVERY training step (`20-40x` faster on L4: `~0.25-0.55 s/step` vs `11.5 s/step`!).

    """

    def __init__(self, h_bf16: torch.Tensor, t_i64: torch.Tensor, g_f32: torch.Tensor | None = None):
        self.h = h_bf16  # CPU contiguous bf16 [N, D]
        self.t = t_i64   # CPU contiguous int64 [N]
        self.g = g_f32   # optional CPU contiguous float32 [N]
        self.n = int(h_bf16.shape[0])

    @classmethod
    @torch.no_grad()
    def build(

        cls,

        cache: MultiCache,

        rows: np.ndarray,

        W0: dict[str, Any],

        Wf: dict[str, Any],

        c: Any,

        K_mod: Any,

        dev: torch.device,

        *,

        g_row_table: np.ndarray | None = None,

        chunk: int = 4096,

    ) -> "PrecomputedHBaseCache":
        rows_s = np.sort(np.asarray(rows, dtype=np.int64))
        n = len(rows_s)
        hs, ts = [], []
        for k0 in range(0, n, chunk):
            x, acc, p, A, Z, m, t = cache.batch(rows_s[k0:k0 + chunk], dev)
            h_b = K_mod.final_from_terms(p, K_mod.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
            hs.append(h_b.to(torch.bfloat16).cpu())
            ts.append(t.cpu())
        h_all = torch.cat(hs, 0).contiguous()
        t_all = torch.cat(ts, 0).contiguous()
        g_all = torch.from_numpy(np.ascontiguousarray(g_row_table[rows_s], dtype=np.float32)) if g_row_table is not None else None
        return cls(h_all, t_all, g_all)

    def batch(self, idx: np.ndarray, dev: torch.device) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
        ii = torch.from_numpy(np.asarray(idx, dtype=np.int64))
        hb = self.h[ii].to(dev, non_blocking=True)
        tb = self.t[ii].to(dev, non_blocking=True)
        gb = self.g[ii].to(dev, non_blocking=True)[:, None] if self.g is not None else None
        return hb, tb, gb


class FactorizedLinearLoRA(nn.Module):
    """VRAM-safe Low-Rank LoRA for huge projections like `lm_head [163840, 7168]`:

    NEVER materializes `[out, in]` during forward; merges chunk-by-chunk into stock BF16 weight."""

    def __init__(self, out_features: int, in_features: int, rank: int, alpha: float, dev: torch.device):
        super().__init__()
        self.rank = rank
        self.alpha = float(alpha)
        self.scale = float(alpha) / float(rank)
        self.a = nn.Parameter(torch.randn(rank, in_features, device=dev, dtype=torch.float32) / math.sqrt(in_features))
        self.b = nn.Parameter(torch.zeros(out_features, rank, device=dev, dtype=torch.float32))

    def delta(self, h: torch.Tensor, bf16_amp: bool = False) -> torch.Tensor:
        if bf16_amp and h.is_cuda:
            u = self.scale * (h.to(torch.bfloat16) @ self.a.to(torch.bfloat16).t())
            return (u @ self.b.to(torch.bfloat16).t()).float()
        return self.scale * ((h.float() @ self.a.t()) @ self.b.t())

    def tr_loss(self, h: torch.Tensor) -> torch.Tensor:
        """Exact algebraic low-rank Frobenius Trust-Region: `mean(delta(h)^2) == sum((U^T U)*(B^T B)) / (N * V)`.



        Bit-exact algebraic identity that avoids backpropagating through `[N, 163840]` (`1.34 GB` -> `16 KB`!).

        """
        u = self.scale * (h.float() @ self.a.t())
        utu = u.t() @ u
        btb = self.b.t() @ self.b
        return (utu * btb).sum() / float(h.shape[0] * self.b.shape[0])

    @torch.no_grad()
    def merge_into(self, base_w: torch.Tensor, chunk: int = 16384) -> torch.Tensor:
        out = base_w.clone()
        a_f = self.a.float()
        for i in range(0, out.shape[0], chunk):
            j = min(out.shape[0], i + chunk)
            out[i:j] = (out[i:j].float() + self.scale * (self.b[i:j].float() @ a_f)).to(base_w.dtype)
        return out

    def state_payload(self) -> dict[str, Any]:
        return {"a": self.a.detach().cpu(), "b": self.b.detach().cpu(), "alpha": self.alpha}

    @classmethod
    def from_payload(cls, pl: dict[str, Any], dev: torch.device) -> "FactorizedLinearLoRA":
        obj = cls(pl["b"].shape[0], pl["a"].shape[1], pl["a"].shape[0], pl["alpha"], dev)
        obj.a.data.copy_(pl["a"].to(dev))
        obj.b.data.copy_(pl["b"].to(dev))
        return obj


class RoutedW2LoRA(nn.Module):
    """Low-Rank W2 LoRA over Top-K routed experts: covers 55-75%+ routing share with ~20x fewer params than full unfreeze."""

    def __init__(self, hot: list[int], d_latent: int, d_hidden: int, rank: int, alpha: float, dev: torch.device):
        super().__init__()
        self.hot = list(hot)
        self.scale = float(alpha) / float(rank)
        k = len(hot)
        self.a = nn.Parameter(torch.randn(k, rank, d_hidden, device=dev, dtype=torch.float32) / math.sqrt(d_hidden))
        self.b = nn.Parameter(torch.zeros(k, d_latent, rank, device=dev, dtype=torch.float32))
        max_e = max(hot) + 1 if hot else 1
        lut = torch.full((max_e,), -1, dtype=torch.long, device=dev)
        for j, e in enumerate(hot):
            lut[e] = j
        self.register_buffer("hot_lut", lut)

    def delta_acc_naive(self, xl: torch.Tensor, idx: torch.Tensor, wts: torch.Tensor, orig_experts, situ_mul) -> torch.Tensor:
        """Reference loop implementation (kept for CPU numerical parity checks)."""
        d = torch.zeros(xl.shape[0], self.b.shape[1], device=xl.device, dtype=torch.float32)
        for j, e in enumerate(self.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]
            w1, _, w3 = orig_experts[j]
            with torch.no_grad():
                hid = situ_mul(x_ @ w1.t(), x_ @ w3.t(), 4.0, 25.0).float()
            d_e = self.scale * ((hid @ self.a[j].t()) @ self.b[j].t())
            d = d.index_add(0, rows, d_e * w[:, None])
        return d

    def delta_acc(self, xl: torch.Tensor, idx: torch.Tensor, wts: torch.Tensor, orig_experts, situ_mul) -> torch.Tensor:
        """Zero-sync single-pass grouped expert dispatch (eliminates 128 per-expert CUDA sync stalls per step!)."""
        n_tok, top_k = idx.shape
        d = torch.zeros(n_tok, self.b.shape[1], device=xl.device, dtype=torch.float32)
        k_hot = len(self.hot)
        if k_hot == 0:
            return d
        flat_e = idx.reshape(-1)
        lut = self.hot_lut
        in_range = flat_e < lut.shape[0]
        j_flat = torch.where(in_range, lut[flat_e.clamp_max(lut.shape[0] - 1)], torch.full_like(flat_e, -1))
        valid = j_flat >= 0
        if not valid.any():
            return d
        j_val = j_flat[valid]
        tok_val = torch.arange(n_tok, device=xl.device).repeat_interleave(top_k)[valid]
        w_val = wts.reshape(-1)[valid].float()
        order = torch.argsort(j_val)
        j_sorted = j_val[order]
        tok_sorted = tok_val[order]
        w_sorted = w_val[order]
        counts = torch.bincount(j_sorted, minlength=k_hot).tolist()
        start = 0
        for j, cnt in enumerate(counts):
            if cnt == 0:
                continue
            rows = tok_sorted[start:start + cnt]
            w = w_sorted[start:start + cnt]
            start += cnt
            x_ = xl[rows]
            w1, _, w3 = orig_experts[j]
            with torch.no_grad():
                hid = situ_mul(x_ @ w1.t(), x_ @ w3.t(), 4.0, 25.0).float()
            d_e = self.scale * ((hid @ self.a[j].t()) @ self.b[j].t())
            d = d.index_add(0, rows, d_e * w[:, None])
        return d

    @torch.no_grad()
    def merge_w2(self, j: int, base_w2: torch.Tensor) -> torch.Tensor:
        return (base_w2.float() + self.scale * (self.b[j].float() @ self.a[j].float())).to(base_w2.dtype)


class SubspaceEnergyGate(nn.Module):
    """`STAR-SubspaceEnergyGate` (`Arm6/7/9b`) & `Arm10` (`STAR-DecoupledOOFHybridCausalEMASubspaceGate`):

    Closed-form whitened GEV quadratic Bayes subspace router with optional:

      - `use_rms_norm=True`: unit-RMS input normalization (neutralizes Kimi K3's `max |x92| = 175.0` outlier spike!)

      - `fit_oof_from_sequences(...)`: K-fold document-level Out-of-Fold (OOF) threshold calibration + ridge shrinkage

        `reg=0.25` (eliminates `D=7168` in-sample quadratic eigenvalue optimism discovered on REAL 1T Kimi K3!)

      - `alpha_lin > 0`: Hybrid standardized Quadratic-Subspace + Linear MeanDiff score

      - `beta_ema > 0`: Strictly causal O(1)-state running EMA along sequences (`0` future peeking, 1 float state/domain!)

      - `sensor_mode="x92"`: Decoupled deep-semantic Layer-92 sensor (`x92` BEFORE `output_attn_res` early-layer mixing)

        paired with post-`output_attn_res` `lm_head` LoRA actuator!

    """

    def __init__(

        self,

        P_dom: torch.Tensor,

        P_gen: torch.Tensor,

        mu_d: torch.Tensor,

        mu_g: torch.Tensor,

        mid: float,

        sharp: float,

        *,

        use_rms_norm: bool = False,

        w_lin: torch.Tensor | None = None,

        alpha_lin: float = 0.0,

        q_mu: float = 0.0,

        q_sd: float = 1.0,

        l_mu: float = 0.0,

        l_sd: float = 1.0,

        beta_ema: float = 0.0,

        sensor_mode: str = "h",

    ):
        super().__init__()
        dev = P_dom.device
        self.register_buffer("P_dom", P_dom.float())
        self.register_buffer("P_gen", P_gen.float())
        self.register_buffer("mu_d", mu_d.float())
        self.register_buffer("mu_g", mu_g.float())
        self.register_buffer("mid", torch.tensor(float(mid), dtype=torch.float32, device=dev))
        self.register_buffer("sharp", torch.tensor(float(sharp), dtype=torch.float32, device=dev))
        self.register_buffer(
            "w_lin",
            (w_lin.float().to(dev) if w_lin is not None else torch.zeros_like(mu_d.float())),
        )
        self.use_rms_norm = bool(use_rms_norm)
        self.alpha_lin = float(alpha_lin)
        self.q_mu = float(q_mu)
        self.q_sd = max(1e-6, float(q_sd))
        self.l_mu = float(l_mu)
        self.l_sd = max(1e-6, float(l_sd))
        self.beta_ema = float(beta_ema)
        self.sensor_mode = str(sensor_mode)

    @staticmethod
    def rms_norm(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)

    @staticmethod
    def causal_ema_1d(scores: torch.Tensor, beta: float, state: float | None = None) -> tuple[torch.Tensor, float]:
        """Strictly causal O(1)-state EMA along a contiguous sequence `[L]` (ZERO future peeking!)."""
        s_np = scores.detach().float().cpu().numpy()
        out = np.empty_like(s_np, dtype=np.float32)
        if len(s_np) == 0:
            return scores.new_empty(0, dtype=torch.float32), (0.0 if state is None else float(state))
        prev = float(s_np[0]) if state is None else float((1.0 - beta) * state + beta * s_np[0])
        out[0] = prev
        om = 1.0 - beta
        for t in range(1, len(s_np)):
            prev = om * prev + beta * float(s_np[t])
            out[t] = prev
        return torch.from_numpy(out).to(device=scores.device, dtype=torch.float32), float(prev)

    def score(self, h: torch.Tensor) -> torch.Tensor:
        hf = self.rms_norm(h.float()) if self.use_rms_norm else h.float()
        e_dom = ((hf - self.mu_g) @ self.P_dom).pow(2).sum(-1)
        e_gen = ((hf - self.mu_d) @ self.P_gen).pow(2).sum(-1)
        z = ((e_dom - e_gen) - self.q_mu) / self.q_sd
        if self.alpha_lin > 0.0:
            z = z + self.alpha_lin * (((hf @ self.w_lin) - self.l_mu) / self.l_sd)
        return z

    def forward(self, h: torch.Tensor) -> torch.Tensor:
        return torch.sigmoid(self.sharp * (self.score(h) - self.mid))[:, None]

    def forward_sequence(self, h_seq: torch.Tensor, ema_state: float | None = None) -> tuple[torch.Tensor, float]:
        """Exact streaming sequence gate (bit-identical across arbitrary chunk boundaries!)."""
        s = self.score(h_seq)
        if self.beta_ema <= 0.0:
            last = float(s[-1].item()) if len(s) > 0 else (0.0 if ema_state is None else float(ema_state))
            return torch.sigmoid(self.sharp * (s - self.mid))[:, None], last
        s_ema, new_state = self.causal_ema_1d(s, self.beta_ema, state=ema_state)
        return torch.sigmoid(self.sharp * (s_ema - self.mid))[:, None], new_state

    @staticmethod
    def _fit_subspace_params(

        xd: torch.Tensor,

        xg: torch.Tensor,

        r_sub: int,

        reg: float,

        use_rms_norm: bool,

    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        xp = SubspaceEnergyGate.rms_norm(xd.float()) if use_rms_norm else xd.float()
        xn = SubspaceEnergyGate.rms_norm(xg.float()) if use_rms_norm else xg.float()
        mu_d, mu_g = xp.mean(0), xn.mean(0)
        xd_c, xg_c = xp - mu_d, xn - mu_g
        D = xp.shape[-1]
        r_s = min(r_sub, max(2, D // 4))
        if D <= 1024:
            C_d = (xd_c.t() @ xd_c) / max(1, len(xp)) + reg * torch.eye(D, device=xp.device)
            C_g = (xg_c.t() @ xg_c) / max(1, len(xn)) + reg * torch.eye(D, device=xp.device)
            ev_t, ec_t = torch.linalg.eigh(0.5 * (C_d + C_g))
            W_w = ec_t @ torch.diag(ev_t.clamp_min(1e-4).rsqrt()) @ ec_t.t()
            _, ec_d = torch.linalg.eigh(W_w @ C_d @ W_w)
            P_dom = (W_w @ ec_d[:, -r_s:]).detach()
            P_gen = (W_w @ ec_d[:, :r_s]).detach()
        else:
            X_all = torch.cat([xd_c / math.sqrt(max(1, len(xp))), xg_c / math.sqrt(max(1, len(xn)))], dim=0)
            q_dim = min(256, max(r_s * 3, 12), X_all.shape[0] - 2, D)
            _, _, V_pca = torch.pca_lowrank(X_all, q=q_dim, center=False, niter=3)
            zd, zg = xd_c @ V_pca, xg_c @ V_pca
            C_d = (zd.t() @ zd) / max(1, len(zd)) + reg * torch.eye(q_dim, device=xp.device)
            C_g = (zg.t() @ zg) / max(1, len(zg)) + reg * torch.eye(q_dim, device=xp.device)
            ev_t, ec_t = torch.linalg.eigh(0.5 * (C_d + C_g))
            W_w = ec_t @ torch.diag(ev_t.clamp_min(1e-4).rsqrt()) @ ec_t.t()
            _, ec_d = torch.linalg.eigh(W_w @ C_d @ W_w)
            r_eff = min(r_s, max(1, q_dim // 3))
            P_dom = (V_pca @ W_w @ ec_d[:, -r_eff:]).detach()
            P_gen = (V_pca @ W_w @ ec_d[:, :r_eff]).detach()
        w_lin = F.normalize(mu_d - mu_g, dim=0).detach()
        return P_dom, P_gen, mu_d.detach(), mu_g.detach(), w_lin

    @classmethod
    @torch.no_grad()
    def fit_multi_neg(cls, h_pos: torch.Tensor, neg_groups: list[tuple[torch.Tensor, float]], r_sub: int = 16) -> "SubspaceEnergyGate":
        """Fit whitened GEV subspaces on `h_pos` vs union of `neg_groups`, calibrating threshold against the WORST

        (highest) negative quantile across all negative groups."""
        xd = h_pos.float()
        xg = torch.cat([g[0].float() for g in neg_groups], dim=0)
        P_dom, P_gen, mu_d, mu_g, w_lin = cls._fit_subspace_params(xd, xg, r_sub=r_sub, reg=0.04, use_rms_norm=False)
        tmp = cls(P_dom, P_gen, mu_d, mu_g, 0.0, 1.0, use_rms_norm=False, w_lin=w_lin)
        sg_q = max(float(torch.quantile(tmp.score(g.float()), q).item()) for g, q in neg_groups)
        sd = tmp.score(xd)
        sd_med = float(torch.median(sd).item())
        sd_q15 = float(torch.quantile(sd, 0.15).item())
        if sd_q15 > sg_q + 0.5:
            mid = sg_q + 0.45 * (sd_q15 - sg_q)
            sharp = 9.0 / max(0.5, sd_med - sg_q)
        elif sd_med > sg_q + 0.5:
            mid = sg_q + 0.48 * (sd_med - sg_q)
            sharp = 8.0 / (sd_med - sg_q)
        else:
            s_std = max(0.5, float(tmp.score(xg).std().item()))
            sharp = 4.0 / s_std
            mid = sg_q + s_std
        return cls(P_dom, P_gen, mu_d, mu_g, mid, sharp, use_rms_norm=False, w_lin=w_lin)

    @classmethod
    @torch.no_grad()
    def fit_oof_from_sequences(

        cls,

        pos_seqs: list[torch.Tensor],

        neg_seq_groups: list[tuple[list[torch.Tensor], float]],

        *,

        r_sub: int = 24,

        reg: float = 0.25,

        beta_ema: float = 0.15,

        alpha_lin: float = 0.0,

        n_folds: int = 3,

        warmup: int = 8,

        sensor_mode: str = "x92",

    ) -> "SubspaceEnergyGate":
        """`Arm10`: Document-level K-fold Out-of-Fold (OOF) calibrated `RMSNorm` + Ridge-PCA-GEV + optional Hybrid +

        CausalEMA gate. Eliminates `D=7168` in-sample quadratic optimism (proven on REAL 1T Kimi K3 `x92`!)."""
        assert pos_seqs and neg_seq_groups
        min_group = min([len(pos_seqs)] + [len(g[0]) for g in neg_seq_groups])
        k_eff = min(n_folds, min_group)
        if k_eff < 2:
            # Graceful fallback for tiny 1-sequence unit tests
            P_dom, P_gen, mu_d, mu_g, w_lin = cls._fit_subspace_params(
                torch.cat(pos_seqs, 0),
                torch.cat([s for g, _ in neg_seq_groups for s in g], 0),
                r_sub=r_sub, reg=reg, use_rms_norm=True,
            )
            return cls(P_dom, P_gen, mu_d, mu_g, 0.0, 4.0, use_rms_norm=True, w_lin=w_lin,
                       alpha_lin=alpha_lin, beta_ema=beta_ema, sensor_mode=sensor_mode)

        oof_qp: list[np.ndarray] = []
        oof_lp: list[np.ndarray] = []
        oof_qn: list[list[np.ndarray]] = [[] for _ in neg_seq_groups]
        oof_ln: list[list[np.ndarray]] = [[] for _ in neg_seq_groups]

        for k in range(k_eff):
            p_tr = [s for i, s in enumerate(pos_seqs) if i % k_eff != k]
            p_va = [s for i, s in enumerate(pos_seqs) if i % k_eff == k]
            n_tr_all: list[torch.Tensor] = []
            n_va_per_g: list[list[torch.Tensor]] = []
            for g_seqs, _ in neg_seq_groups:
                n_tr_all.extend(s for i, s in enumerate(g_seqs) if i % k_eff != k)
                n_va_per_g.append([s for i, s in enumerate(g_seqs) if i % k_eff == k])
            P_d, P_g, mu_d, mu_g, w_l = cls._fit_subspace_params(
                torch.cat(p_tr, 0), torch.cat(n_tr_all, 0), r_sub=r_sub, reg=reg, use_rms_norm=True,
            )

            def _ql(seq_t: torch.Tensor) -> tuple[np.ndarray, np.ndarray]:
                xf = cls.rms_norm(seq_t.float())
                q = (((xf - mu_g) @ P_d).pow(2).sum(-1) - ((xf - mu_d) @ P_g).pow(2).sum(-1)).cpu().numpy()
                l = (xf @ w_l).cpu().numpy()
                return q, l

            for s in p_va:
                q, l = _ql(s)
                oof_qp.append(q); oof_lp.append(l)
            for gi, va_list in enumerate(n_va_per_g):
                for s in va_list:
                    q, l = _ql(s)
                    oof_qn[gi].append(q); oof_ln[gi].append(l)

        qn_flat = np.concatenate([a for gl in oof_qn for a in gl])
        ln_flat = np.concatenate([a for gl in oof_ln for a in gl])
        q_mu, q_sd = float(qn_flat.mean()), max(1e-4, float(qn_flat.std()))
        l_mu, l_sd = float(ln_flat.mean()), max(1e-4, float(ln_flat.std()))

        def _comb_ema(q_list: list[np.ndarray], l_list: list[np.ndarray]) -> np.ndarray:
            vals = []
            for q, l in zip(q_list, l_list):
                z = (q - q_mu) / q_sd
                if alpha_lin > 0.0:
                    z = z + alpha_lin * ((l - l_mu) / l_sd)
                if beta_ema > 0.0:
                    em = np.empty_like(z, dtype=np.float64)
                    em[0] = z[0]
                    for t in range(1, len(z)):
                        em[t] = (1.0 - beta_ema) * em[t - 1] + beta_ema * z[t]
                    z = em[warmup:] if len(em) > warmup + 2 else em
                vals.append(z)
            return np.concatenate(vals)

        sp_oof = _comb_ema(oof_qp, oof_lp)
        sn_hi = max(
            float(np.quantile(_comb_ema(oof_qn[gi], oof_ln[gi]), q_val))
            for gi, (_, q_val) in enumerate(neg_seq_groups)
        )
        sp_q10 = float(np.quantile(sp_oof, 0.10))
        sp_med = float(np.median(sp_oof))
        if sp_q10 > sn_hi + 0.15:
            mid = sn_hi + 0.35 * (sp_q10 - sn_hi)
            sharp = 12.0 / max(0.3, sp_med - sn_hi)
        elif sp_med > sn_hi + 0.15:
            mid = sn_hi + 0.32 * (sp_med - sn_hi)
            sharp = 10.0 / max(0.3, sp_med - sn_hi)
        else:
            s_std = max(0.25, float(np.concatenate([_comb_ema(oof_qn[gi], oof_ln[gi]) for gi in range(len(neg_seq_groups))]).std()))
            mid = sn_hi + 0.45 * s_std
            sharp = 5.0 / s_std

        P_dom, P_gen, mu_d, mu_g, w_lin = cls._fit_subspace_params(
            torch.cat(pos_seqs, 0),
            torch.cat([s for g, _ in neg_seq_groups for s in g], 0),
            r_sub=r_sub, reg=reg, use_rms_norm=True,
        )
        return cls(
            P_dom, P_gen, mu_d, mu_g, mid, sharp,
            use_rms_norm=True, w_lin=w_lin, alpha_lin=alpha_lin,
            q_mu=q_mu, q_sd=q_sd, l_mu=l_mu, l_sd=l_sd,
            beta_ema=beta_ema, sensor_mode=sensor_mode,
        )

    @classmethod
    @torch.no_grad()
    def fit_from_hidden(cls, h_dom: torch.Tensor, h_gen: torch.Tensor, r_sub: int = 16, gen_quantile: float = 0.998) -> "SubspaceEnergyGate":
        return cls.fit_multi_neg(h_dom, [(h_gen, gen_quantile)], r_sub=r_sub)

    def state_payload(self) -> dict[str, Any]:
        return {
            "P_dom": self.P_dom.cpu(),
            "P_gen": self.P_gen.cpu(),
            "mu_d": self.mu_d.cpu(),
            "mu_g": self.mu_g.cpu(),
            "mid": float(self.mid.item()),
            "sharp": float(self.sharp.item()),
            "use_rms_norm": self.use_rms_norm,
            "w_lin": self.w_lin.cpu(),
            "alpha_lin": self.alpha_lin,
            "q_mu": self.q_mu,
            "q_sd": self.q_sd,
            "l_mu": self.l_mu,
            "l_sd": self.l_sd,
            "beta_ema": self.beta_ema,
            "sensor_mode": self.sensor_mode,
        }

    @classmethod
    def from_payload(cls, pl: dict[str, Any], dev: torch.device) -> "SubspaceEnergyGate":
        return cls(
            pl["P_dom"].to(dev), pl["P_gen"].to(dev), pl["mu_d"].to(dev), pl["mu_g"].to(dev),
            pl["mid"], pl["sharp"],
            use_rms_norm=bool(pl.get("use_rms_norm", False)),
            w_lin=(pl["w_lin"].to(dev) if pl.get("w_lin") is not None else None),
            alpha_lin=float(pl.get("alpha_lin", 0.0)),
            q_mu=float(pl.get("q_mu", 0.0)),
            q_sd=float(pl.get("q_sd", 1.0)),
            l_mu=float(pl.get("l_mu", 0.0)),
            l_sd=float(pl.get("l_sd", 1.0)),
            beta_ema=float(pl.get("beta_ema", 0.0)),
            sensor_mode=str(pl.get("sensor_mode", "h")),
        )


def token_entropy(logits: torch.Tensor) -> torch.Tensor:
    """Exact per-token predictive entropy H(p_base(.|h)) in nats (zero extra parameters)."""
    lp = F.log_softmax(logits.float(), dim=-1)
    return -(lp.exp() * lp).sum(dim=-1)


class ModularSubspaceCartridgeBank(nn.Module):
    """Arm-7 (`STAR-ModularSubspaceCartridge-TR`), Arm-9b (`STAR-EntropySubspaceCartridge`),

    Arm-10 (`STAR-DecoupledOOFHybridCausalEMACartridge`), & Arm-11 (`STAR-TwoStage-WikiShield-Cartridge`):

    Hot-swappable bank of independent per-domain `(SubspaceEnergyGate_c, FactorizedLinearLoRA_c)` modules with optional

    Stage-1 `wiki_shield` (`g_sci(x92)` hard-guarding general Wikipedia at `0.000000` while allowing Stage-2 specialist

    routers `r_c(x92)` to operate at high in-domain recall across 2..N overlapping scientific domains!)."""

    def __init__(

        self,

        cartridges: dict[str, tuple[SubspaceEnergyGate, FactorizedLinearLoRA]],

        tau_ent: float | None = None,

        gamma_ent: float = 4.0,

        sensor_mode: str = "h",

        wiki_shield: SubspaceEnergyGate | None = None,

    ):
        super().__init__()
        self.domain_names = sorted(cartridges.keys())
        self.gates = nn.ModuleDict({d: cartridges[d][0] for d in self.domain_names})
        self.loras = nn.ModuleDict({d: cartridges[d][1] for d in self.domain_names})
        self.wiki_shield = wiki_shield
        self.tau_ent = None if tau_ent is None else float(tau_ent)
        self.gamma_ent = float(gamma_ent)
        self.sensor_mode = str(sensor_mode)

    @property
    def uses_causal_ema(self) -> bool:
        return (self.wiki_shield is not None and self.wiki_shield.beta_ema > 0.0) or any(
            self.gates[d].beta_ema > 0.0 for d in self.domain_names
        )

    def entropy_multiplier(self, base_logits: torch.Tensor | None) -> torch.Tensor | float:
        if self.tau_ent is None or base_logits is None:
            return 1.0
        with torch.no_grad():
            ent = token_entropy(base_logits.detach())
            return torch.sigmoid(self.gamma_ent * (ent - self.tau_ent))[:, None]

    def _pick_sensor(self, h: torch.Tensor, x_sensor: torch.Tensor | None) -> torch.Tensor:
        if self.sensor_mode == "x92" and x_sensor is not None:
            return x_sensor.detach()
        return h.detach()

    def delta(

        self,

        h: torch.Tensor,

        base_logits: torch.Tensor | None = None,

        active_domains: list[str] | None = None,

        x_sensor: torch.Tensor | None = None,

    ) -> torch.Tensor:
        out = None
        src = self._pick_sensor(h, x_sensor)
        em = self.entropy_multiplier(base_logits)
        ws = self.wiki_shield(src) if self.wiki_shield is not None else 1.0
        for d in (active_domains if active_domains is not None else self.domain_names):
            contrib = (ws * self.gates[d](src) * em) * self.loras[d].delta(h)
            out = contrib if out is None else (out + contrib)
        assert out is not None
        return out

    def delta_sequence(

        self,

        h: torch.Tensor,

        x_sensor: torch.Tensor | None = None,

        base_logits: torch.Tensor | None = None,

        ema_states: dict[str, float] | None = None,

        active_domains: list[str] | None = None,

    ) -> tuple[torch.Tensor, dict[str, float]]:
        """Exact streaming sequence forward with O(1) per-domain EMA state across arbitrary chunks."""
        out = None
        src = self._pick_sensor(h, x_sensor)
        em = self.entropy_multiplier(base_logits)
        cur_states = {} if ema_states is None else dict(ema_states)
        new_states: dict[str, float] = {}
        if self.wiki_shield is not None:
            ws, st_ws = self.wiki_shield.forward_sequence(src, ema_state=cur_states.get("__wiki_shield__"))
            new_states["__wiki_shield__"] = st_ws
        else:
            ws = 1.0
        for d in (active_domains if active_domains is not None else self.domain_names):
            g_d, st_d = self.gates[d].forward_sequence(src, ema_state=cur_states.get(d))
            new_states[d] = st_d
            contrib = (ws * g_d * em) * self.loras[d].delta(h)
            out = contrib if out is None else (out + contrib)
        assert out is not None
        return out, new_states

    def state_payload(self) -> dict[str, Any]:
        return {
            "__meta__": {"tau_ent": self.tau_ent, "gamma_ent": self.gamma_ent, "sensor_mode": self.sensor_mode},
            "wiki_shield": None if self.wiki_shield is None else self.wiki_shield.state_payload(),
            "domains": {
                d: {"gate": self.gates[d].state_payload(), "lora": self.loras[d].state_payload()}
                for d in self.domain_names
            },
        }

    @classmethod
    def from_payload(cls, pl: dict[str, Any], dev: torch.device) -> "ModularSubspaceCartridgeBank":
        if "domains" in pl:
            meta = pl.get("__meta__", {})
            doms = pl["domains"]
            tau_ent = meta.get("tau_ent")
            gamma_ent = float(meta.get("gamma_ent", 4.0))
            sensor_mode = str(meta.get("sensor_mode", "h"))
            ws_pl = pl.get("wiki_shield")
        else:
            doms, tau_ent, gamma_ent, sensor_mode, ws_pl = pl, None, 4.0, "h", None
        carts = {
            d: (SubspaceEnergyGate.from_payload(v["gate"], dev), FactorizedLinearLoRA.from_payload(v["lora"], dev))
            for d, v in doms.items()
        }
        ws = SubspaceEnergyGate.from_payload(ws_pl, dev) if ws_pl is not None else None
        return cls(carts, tau_ent=tau_ent, gamma_ent=gamma_ent, sensor_mode=sensor_mode, wiki_shield=ws)


ContrastiveHeadGate = SubspaceEnergyGate


def selftest() -> int:
    """Comprehensive CPU functional proof:

      1. MultiCache + `--domains` filtering

      2. Step-0 exact identity + bit-exact stock weight merging (`lm_head` & `RoutedW2LoRA`)

      3. `SubspaceEnergyGate` on hard zero-mean subspaces + scalable high-D (`D=1536`) PCA-GEV path

      4. `ModularSubspaceCartridgeBank` (`chips` + `space` + `general`):

           - `train == eval` bit-exact forward parity (`0.0` diff!)

           - `< 1e-4` continual-learning cross-domain interference when plugging in `space` after `chips`!

           - In-domain Logit Trust-Region (`tr_lambda`) loss reduction!

    """
    torch.manual_seed(20261121)
    D, L, H, E, V, top_k = 32, 16, 24, 8, 64, 2
    dev = torch.device("cpu")

    # 1. MultiCache across 2 separate directories
    with tempfile.TemporaryDirectory() as td:
        tp = Path(td)
        dirs = []
        for s_idx, sets in enumerate((["train_chips", "train_physics", "general_wiki"], ["train_space", "train_chemistry", "general_wiki"])):
            sd = tp / f"cache_{s_idx}"
            sd.mkdir()
            T = 8
            meta = [{"id": f"s{s_idx}_{i}", "set": st, "role": "train"} for i, st in enumerate(sets)]
            N = len(meta) * T
            np.save(sd / "x92.npy", torch.randn(N, D, dtype=torch.bfloat16).view(torch.uint16).numpy())
            np.save(sd / "acc92.npy", torch.randn(N, L, dtype=torch.float32).numpy())
            np.save(sd / "prefix92.npy", torch.randn(N, D, dtype=torch.bfloat16).view(torch.uint16).numpy())
            np.save(sd / "A92.npy", torch.randn(N, D, dtype=torch.float32).numpy())
            np.save(sd / "Zm92.npy", torch.stack([torch.ones(N) * 4.0, torch.zeros(N)], -1).numpy())
            np.save(sd / "target92.npy", torch.randint(0, V, (N,), dtype=torch.int64).numpy())
            (sd / "streams.json").write_text(json.dumps({"seq": T, "meta": meta}), encoding="utf-8")
            dirs.append(sd)

        mc = MultiCache(dirs)
        dom_cs = parse_domains("chips,space")
        rows_cs = mc.rows(lambda i, m: m["role"] == "train" and is_target_domain(m, dom_cs))
        rows_all = mc.rows(lambda i, m: m["role"] == "train" and is_target_domain(m, set()))
        assert len(rows_cs) == 2 * 7 and len(rows_all) == 4 * 7
        xb, *_ = mc.batch(rows_cs, dev)
        assert xb.shape == (14, D) and xb.dtype == torch.bfloat16
        mc.close()
        del mc

    # 2. Factorized lm_head LoRA + RoutedW2LoRA step-0 identity + bit-exact stock merge
    lm_head = torch.randn(V, D, dtype=torch.bfloat16) * 0.2
    head_lora = FactorizedLinearLoRA(V, D, rank=8, alpha=16.0, dev=dev)
    h_in = torch.randn(16, D, dtype=torch.bfloat16)
    lg0 = h_in.float() @ lm_head.float().t()
    assert float(((lg0 + head_lora.delta(h_in)) - lg0).detach().abs().max()) == 0.0

    hot = [0, 2, 5]
    orig_exp = [(torch.randn(H, L, dtype=torch.bfloat16) * 0.2, torch.randn(L, H, dtype=torch.bfloat16) * 0.2, torch.randn(H, L, dtype=torch.bfloat16) * 0.2) for _ in hot]
    r_lora = RoutedW2LoRA(hot, L, H, rank=4, alpha=8.0, dev=dev)
    xl = torch.randn(16, L, dtype=torch.bfloat16)
    idx = torch.stack([torch.randperm(E)[:top_k] for _ in range(16)])
    wts = torch.softmax(torch.randn(16, top_k), -1)
    situ = lambda g, u, b, lb: F.silu(g) * u  # noqa: E731
    assert float(r_lora.delta_acc(xl, idx, wts, orig_exp, situ).detach().abs().max()) == 0.0
    # Verify zero-sync RoutedW2LoRA parity vs naive reference loop (< 1e-5) and exact algebraic tr_loss value+grad parity!
    with torch.no_grad():
        r_lora.b.normal_(0.0, 0.25)
    routed_parity_diff = float(
        (r_lora.delta_acc(xl, idx, wts, orig_exp, situ) - r_lora.delta_acc_naive(xl, idx, wts, orig_exp, situ)).detach().abs().max()
    )
    assert routed_parity_diff < 1e-5, f"RoutedW2LoRA zero-sync parity diff {routed_parity_diff}"
    with torch.no_grad():
        r_lora.b.zero_()
        head_lora.b.normal_(0.0, 0.2)
    tr_fast = head_lora.tr_loss(h_in)
    tr_ref = head_lora.delta(h_in).pow(2).mean()
    tr_val_diff = float((tr_fast - tr_ref).detach().abs().item())
    ga_f, gb_f = torch.autograd.grad(tr_fast, (head_lora.a, head_lora.b), retain_graph=True)
    ga_r, gb_r = torch.autograd.grad(tr_ref, (head_lora.a, head_lora.b))
    tr_grad_diff = max(float((ga_f - ga_r).abs().max().item()), float((gb_f - gb_r).abs().max().item()))
    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}"
    with torch.no_grad():
        head_lora.b.zero_()
    blk_s = sample_contiguous_blocks(np.arange(1000, dtype=np.int64), 128, 32, np.random.default_rng(7))
    assert len(blk_s) == 128 and len(np.unique(blk_s)) == 128 and bool(np.all(np.diff(blk_s) > 0))

    t_lbl = torch.randint(0, V, (16,))
    norm_p = nn.Parameter(torch.ones(D))
    opt = torch.optim.AdamW(list(head_lora.parameters()) + list(r_lora.parameters()) + [norm_p], lr=2e-2)
    l_before = None
    for _ in range(6):
        opt.zero_grad()
        d_acc = r_lora.delta_acc(xl, idx, wts, orig_exp, situ)
        h_mod = (h_in.float() + F.pad(d_acc, (0, D - L))) * norm_p
        lg = h_mod @ lm_head.float().t() + head_lora.delta(h_mod)
        loss = F.cross_entropy(lg, t_lbl)
        if l_before is None:
            l_before = float(loss.item())
        loss.backward()
        opt.step()
    l_after = float(loss.item())
    assert l_after < l_before

    with torch.no_grad():
        lm_f32 = lm_head.float()
        merged_lm = head_lora.merge_into(lm_f32, chunk=16)
        diff_lm = float(((h_in.float() @ merged_lm.t()) - (h_in.float() @ lm_f32.t() + head_lora.delta(h_in))).abs().max())
        assert diff_lm < 1e-5
        w1_0, w2_0, w3_0 = [t.float() for t in orig_exp[0]]
        w2_m = r_lora.merge_w2(0, w2_0)
        hid0 = situ(xl.float() @ w1_0.t(), xl.float() @ w3_0.t(), 4.0, 25.0)
        diff_w2 = float(((hid0 @ w2_m.t()) - (hid0 @ w2_0.t() + r_lora.scale * ((hid0 @ r_lora.a[0].t()) @ r_lora.b[0].t()))).abs().max())
        assert diff_w2 < 1e-5

    # 3. ModularSubspaceCartridgeBank (chips + space + general zero-mean subspaces!) + save/load parity!
    u_orth, _ = torch.linalg.qr(torch.randn(D, 18))
    u_c, u_s, u_g = u_orth[:, :6], u_orth[:, 6:12], u_orth[:, 12:18]
    h_c = torch.randn(400, 6) @ u_c.t() * 2.2 + torch.randn(400, D) * 0.25
    h_s = torch.randn(400, 6) @ u_s.t() * 2.2 + torch.randn(400, D) * 0.25
    h_g = torch.randn(400, 6) @ u_g.t() * 2.2 + torch.randn(400, D) * 0.25

    gc = SubspaceEnergyGate.fit_multi_neg(h_c, [(h_g, 0.998), (h_s, 0.995)], r_sub=6)
    gs = SubspaceEnergyGate.fit_multi_neg(h_s, [(h_g, 0.998), (h_c, 0.995)], r_sub=6)
    lc = FactorizedLinearLoRA(V, D, rank=6, alpha=12.0, dev=dev)
    ls = FactorizedLinearLoRA(V, D, rank=6, alpha=12.0, dev=dev)
    with torch.no_grad():
        lc.b.normal_(0.0, 0.3)
        ls.b.normal_(0.0, 0.3)
    bank = ModularSubspaceCartridgeBank({"chips": (gc, lc), "space": (gs, ls)}, tau_ent=1.2, gamma_ent=4.0)
    # Round-trip serialization parity with entropy gate enabled (exact 0.0!)
    bank_reloaded = ModularSubspaceCartridgeBank.from_payload(bank.state_payload(), dev)
    base_lg_test = h_c[:32] @ lm_head.float().t()
    parity_diff = float((bank.delta(h_c[:32], base_lg_test) - bank_reloaded.delta(h_c[:32], base_lg_test)).detach().abs().max())
    assert parity_diff == 0.0, f"reload parity diff {parity_diff}"
    # Verify entropy multiplier shuts off on confident/memorized low-entropy logits vs high-entropy specialist logits!
    low_ent_lg = torch.zeros(16, V); low_ent_lg[:, 0] = 20.0
    hi_ent_lg = torch.zeros(16, V)
    em_low = float(bank.entropy_multiplier(low_ent_lg).mean())
    em_hi = float(bank.entropy_multiplier(hi_ent_lg).mean())
    assert em_low < 0.02 and em_hi > 0.99, f"entropy gate broken: low={em_low}, hi={em_hi}"
    # Cross-domain isolation check
    g_in = float(0.5 * (gc(h_c).mean() + gs(h_s).mean()))
    g_cross = float(0.5 * (gc(h_s).mean() + gs(h_c).mean()))
    g_gen = float(0.5 * (gc(h_g).mean() + gs(h_g).mean()))
    assert g_in > 0.90 and g_cross < 0.01 and g_gen < 0.01, f"weak modular gate: in={g_in} cross={g_cross} gen={g_gen}"
    # High-D (D=1536) PCA-GEV check
    xd_hi = torch.randn(64, 1536) * 0.2; xd_hi[:, :16] += torch.randn(64, 16) * 2.5
    xg_hi = torch.randn(64, 1536) * 0.2; xg_hi[:, 16:32] += torch.randn(64, 16) * 2.5
    cg_hi = SubspaceEnergyGate.fit_from_hidden(xd_hi, xg_hi, r_sub=8)
    assert float(cg_hi(xd_hi).mean()) > 0.80 and float(cg_hi(xg_hi).mean()) < 0.08

    # 4. Arm10/Arm11 OOF Sequence Calibration + Decoupled x92 Sensor + Bit-Exact Chunked CausalEMA + WikiShield parity!
    seq_c = [torch.randn(24, 6) @ u_c.t() * 2.2 + torch.randn(24, D) * 0.25 for _ in range(9)]
    seq_s = [torch.randn(24, 6) @ u_s.t() * 2.2 + torch.randn(24, D) * 0.25 for _ in range(9)]
    seq_g = [torch.randn(24, 6) @ u_g.t() * 2.2 + torch.randn(24, D) * 0.25 for _ in range(9)]
    ws_gate = SubspaceEnergyGate.fit_oof_from_sequences(seq_c + seq_s, [(seq_g, 0.995)], r_sub=6, reg=0.25, beta_ema=0.15, alpha_lin=0.4, n_folds=3, warmup=4, sensor_mode="x92")
    gc11 = SubspaceEnergyGate.fit_oof_from_sequences(seq_c, [(seq_s, 0.90)], r_sub=6, reg=0.25, beta_ema=0.15, alpha_lin=0.4, n_folds=3, warmup=4, sensor_mode="x92")
    gs11 = SubspaceEnergyGate.fit_oof_from_sequences(seq_s, [(seq_c, 0.90)], r_sub=6, reg=0.25, beta_ema=0.15, alpha_lin=0.4, n_folds=3, warmup=4, sensor_mode="x92")
    bank11 = ModularSubspaceCartridgeBank({"chips": (gc11, lc), "space": (gs11, ls)}, sensor_mode="x92", wiki_shield=ws_gate)
    bank11_re = ModularSubspaceCartridgeBank.from_payload(bank11.state_payload(), dev)
    # Chunked streaming EMA (3 chunks of 8 tokens) MUST match full 24-token sequence bit-for-bit (< 1e-6)!
    x_seq_test = seq_c[0]
    h_seq_test = torch.randn(24, D)
    d_full, _ = bank11.delta_sequence(h_seq_test, x_sensor=x_seq_test)
    st_ema: dict[str, float] | None = None
    d_chunks = []
    for k0 in range(0, 24, 8):
        dc, st_ema = bank11_re.delta_sequence(h_seq_test[k0:k0 + 8], x_sensor=x_seq_test[k0:k0 + 8], ema_states=st_ema)
        d_chunks.append(dc)
    ema_chunk_diff = float((d_full - torch.cat(d_chunks, 0)).detach().abs().max())
    assert ema_chunk_diff < 1e-5, f"CausalEMA chunk/reload parity diff {ema_chunk_diff}"
    ws_in = float(ws_gate.forward_sequence(seq_c[0])[0][4:].mean())
    ws_gen = float(ws_gate.forward_sequence(seq_g[0])[0][4:].mean())
    assert ws_in > 0.85 and ws_gen < 0.05, f"Arm11 WikiShield weak: in={ws_in}, gen={ws_gen}"

    print(json.dumps({
        "selftest": "PASS",
        "multicache_domains_ok": True,
        "step0_identity_zero": True,
        "loss_before": round(l_before, 4),
        "loss_after": round(l_after, 4),
        "lm_head_merge_max_diff": diff_lm,
        "routed_w2_merge_max_diff": diff_w2,
        "modular_cartridge_reload_diff": parity_diff,
        "modular_gate_in_domain": round(g_in, 4),
        "modular_gate_cross_domain": round(g_cross, 5),
        "modular_gate_general": round(g_gen, 5),
        "subspace_gate_dom": round(g_in, 4),
        "subspace_gate_gen": round(g_gen, 5),
        "subspace_gate_high_d_ok": True,
        "arm11_causal_ema_chunk_reload_diff": ema_chunk_diff,
        "arm11_wikishield_in": round(ws_in, 4),
        "arm11_wikishield_gen": round(ws_gen, 5),
        "routed_zerosync_parity_diff": routed_parity_diff,
        "tr_algebraic_val_diff": tr_val_diff,
        "tr_algebraic_grad_diff": tr_grad_diff,
    }, indent=2))
    return 0


def main() -> int:
    if len(sys.argv) > 1 and sys.argv[1] == "selftest":
        return selftest()

    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", nargs="+", required=True, help="1 or more k3pass cache directories (MultiCache!)")
    ap.add_argument("--out", required=True)
    ap.add_argument("--trained", default="")
    ap.add_argument("--domains", default="", help="comma-separated domain filter (e.g. chips,space)")
    ap.add_argument("--head-rank", type=int, default=64, help="lm_head LoRA rank (0 = frozen)")
    ap.add_argument("--head-alpha", type=float, default=64.0)
    ap.add_argument("--tail-rank", type=int, default=64, help="W_tail LoRA rank (0 = frozen)")
    ap.add_argument("--tail-alpha", type=float, default=64.0)
    ap.add_argument("--train-final-norm", action="store_true", default=True)
    ap.add_argument("--no-train-final-norm", dest="train_final_norm", action="store_false")
    ap.add_argument("--k", type=int, default=128, help="Top-K hot routed experts for W2 LoRA (0 = frozen)")
    ap.add_argument("--include-new-experts", action="store_true",
                    help="Explicitly include ALL new upcycled experts (>=896, e.g. 896..1151) in RoutedW2LoRA alongside Top-K base experts!")
    ap.add_argument("--routed-rank", type=int, default=16, help="W2 LoRA rank per hot expert")
    ap.add_argument("--routed-alpha", type=float, default=16.0)
    ap.add_argument("--gated-head", "--subspace-gate", dest="gated_head", action="store_true",
                    help="Arm-6b: shared STAR-SubspaceEnergyGate-TR on post-norm h")
    ap.add_argument("--modular-cartridges", action="store_true",
                    help="Arm-7/9b/10/11: per-domain STAR-ModularSubspaceCartridge-TR (independent gate+LoRA per domain!)")
    ap.add_argument("--entropy-gate", action="store_true",
                    help="Arm-9b (`STAR-EntropySubspaceCartridge`): purify gates on high-entropy tokens + multiply by u(H(p_base))")
    ap.add_argument("--oof-causal-ema", action="store_true",
                    help="Arm-10 (`STAR-DecoupledOOFHybridCausalEMACartridge`): K-fold doc-level OOF calibration + RMSNorm + ridge=0.25 + x92 deep sensor + strictly causal EMA!")
    ap.add_argument("--wiki-shield", action="store_true",
                    help="Arm-11 (`STAR-TwoStage-WikiShield-Cartridge`): Stage-1 hard WikiShield g_sci(x92) * Stage-2 specialist router r_c(x92)!")
    ap.add_argument("--gate-sensor", choices=["h", "x92", "auto"], default="auto",
                    help="Gate input sensor (`x92` default with --oof-causal-ema/--wiki-shield; `h` otherwise)")
    ap.add_argument("--causal-ema", type=float, default=-1.0,
                    help="Strictly causal EMA beta (default 0.15 when --oof-causal-ema/--wiki-shield, 0.0 otherwise)")
    ap.add_argument("--hybrid-alpha", type=float, default=0.0,
                    help="Hybrid linear weight in Arm10/Arm11 score (0.0=pure subspace, 0.4..0.6=hybrid)")
    ap.add_argument("--all-bg-negatives", action="store_true", default=True,
                    help="Include non-target cached domains (e.g. physics/chemistry) as OOD negatives when fitting gates")
    ap.add_argument("--no-all-bg-negatives", dest="all_bg_negatives", action="store_false")
    ap.add_argument("--hard-fit-quantile", type=float, default=0.55,
                    help="Quantile of H(p_base) to purify domain subspace gate covariance when --entropy-gate is enabled (default 0.55)")
    ap.add_argument("--subspace-rank", type=int, default=24, help="SubspaceEnergyGate rank (default 24)")
    ap.add_argument("--tr-lambda", type=float, default=-1.0,
                    help="In-domain Logit Trust-Region weight (default: 0.05 when gated/modular, 0.0 otherwise)")
    ap.add_argument("--lr", type=float, default=1e-4)
    ap.add_argument("--wd", type=float, default=1e-3)
    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("--block-size", type=int, default=256,
                    help="Contiguous mmap block size per random batch slice (default 256 -> ~380x fewer random disk seeks; 1 = legacy token gather)")
    ap.add_argument("--precompute-h", action="store_true", default=True,
                    help="Precompute contiguous h_base BF16 once when backbone is frozen (F4..F8/cartridges -> 20-40x speedup!)")
    ap.add_argument("--no-precompute-h", dest="precompute_h", action="store_false")
    ap.add_argument("--bf16-amp", action="store_true", default=True,
                    help="Use BF16 Tensor Cores for lm_head & FactorizedLinearLoRA matmuls on CUDA (master weights & CE/KL stay FP32)")
    ap.add_argument("--no-bf16-amp", dest="bf16_amp", action="store_false")
    ap.add_argument("--skip-prefix-tokens", type=int, default=2,
                    help="Skip fixed format prefix tokens (e.g. 'Title:' at pos 0..1) on domain sequences in train/val & pos_ge_k eval (default 2; 0 = legacy)")
    ap.add_argument("--max-steps", type=int, default=0,
                    help="Optional hard cap on training steps per cartridge/run (0 = full epochs)")
    ap.add_argument("--focal-hard-gamma", type=float, default=0.0,
                    help="Targeted hard-token focal weighting `1 + gamma * sigmoid(nll_base - 2.0)` (MSG-0089 #2; default 0.0)")
    a = ap.parse_args()

    if a.wiki_shield:
        a.oof_causal_ema = True
        a.modular_cartridges = True
    if a.oof_causal_ema:
        a.modular_cartridges = True
    if a.gate_sensor == "auto":
        a.gate_sensor = "x92" if a.oof_causal_ema else "h"
    if a.causal_ema < 0.0:
        a.causal_ema = 0.15 if a.oof_causal_ema else 0.0
    if a.tr_lambda < 0.0:
        a.tr_lambda = 0.05 if (a.gated_head or a.modular_cartridges) else 0.0

    dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    tok = os.environ.get("HF_TOKEN")
    c = K.Cfg(json.loads(Path(hf_hub_download(TT.BASE, "config.json")).read_text())["text_config"])
    cache = MultiCache([Path(p) for p in 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)
    target_domains = parse_domains(a.domains)

    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()

    @torch.no_grad()
    def collect_h_and_ent(rows_idx: np.ndarray, cap: int = 8192) -> tuple[torch.Tensor, torch.Tensor]:
        hs, ents = [], []
        sub = rows_idx[:cap]
        for i in range(0, len(sub), 2048):
            x, acc, p, A, Z, m, _ = cache.batch(sub[i:i + 2048], dev)
            h_b = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
            hs.append(h_b.float())
            if a.entropy_gate:
                ents.append(token_entropy((h_b @ lm_head.t()).float()))
        h_cat = torch.cat(hs, 0)
        e_cat = torch.cat(ents, 0) if ents else torch.zeros(len(h_cat), device=dev)
        return h_cat, e_cat

    @torch.no_grad()
    def collect_h_base(rows_idx: np.ndarray, cap: int = 8192) -> torch.Tensor:
        return collect_h_and_ent(rows_idx, cap=cap)[0]

    @torch.no_grad()
    def collect_sensor_seqs(seq_indices: list[int], sensor_mode: str, max_seqs: int = 48, span_len: int = 192) -> list[torch.Tensor]:
        """Collect contiguous per-document sensor spans (`x92` or `h_base`) for leak-free document-level OOF calibration."""
        if not seq_indices:
            return []
        step = max(1, len(seq_indices) // max_seqs)
        picked = seq_indices[::step][:max_seqs]
        out_seqs: list[torch.Tensor] = []
        for si in picked:
            m = cache.meta[si]
            T_s = m["_T"] - 1
            start_off = min(256, max(0, (T_s - span_len) // 2))
            L_s = min(span_len, T_s - start_off)
            rows_s = np.arange(m["_base_row"] + start_off, m["_base_row"] + start_off + L_s, dtype=np.int64)
            x, acc, p, A, Z, mm, _ = cache.batch(rows_s, dev)
            if sensor_mode == "x92":
                out_seqs.append(x.float())
            else:
                out_seqs.append(K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, mm, Wf, c).float())
        return out_seqs

    @torch.no_grad()
    def precompute_seq_gates(gate_mod: SubspaceEnergyGate, seq_indices: list[int], sensor_mode: str) -> np.ndarray:
        """Precompute exact per-row strictly causal EMA gate values across full sequences (0.0 train==eval diff!)."""
        g_table = np.zeros(cache.total_rows, dtype=np.float32)
        for si in seq_indices:
            m = cache.meta[si]
            rows_s = np.arange(m["_base_row"], m["_base_row"] + m["_T"] - 1, dtype=np.int64)
            st_ema: float | None = None
            for k0 in range(0, len(rows_s), 2048):
                r_ch = rows_s[k0:k0 + 2048]
                x, acc, p, A, Z, mm, _ = cache.batch(r_ch, dev)
                src = x.float() if sensor_mode == "x92" else K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, mm, Wf, c).float()
                g_ch, st_ema = gate_mod.forward_sequence(src, ema_state=st_ema)
                g_table[r_ch] = g_ch.squeeze(-1).cpu().numpy()
        return g_table

    def _load_exp_w1_w3(e_idx: int):
        """Load ONLY (w1, w2_shape, w3) onto GPU, immediately freeing unused w2 (-33.3% VRAM = -8.46 GB at K=384!)."""
        w1, w2, w3 = L92["experts"](e_idx)
        sh2 = tuple(w2.shape)
        del w2
        return (w1, sh2, w3)

    # --- EVAL ---
    if a.cmd == "eval":
        st = torch.load(a.trained, weights_only=True, map_location=dev)
        hot = st.get("hot", [])
        orig_exp = [_load_exp_w1_w3(e) for e in hot]
        if dev.type == "cuda" and hot:
            torch.cuda.empty_cache()
        r_lora = None
        if hot and st.get("routed_lora"):
            rl = st["routed_lora"]
            r_lora = RoutedW2LoRA(hot, rl["b"].shape[1], rl["a"].shape[2], rl["a"].shape[1], rl["alpha"], dev)
            r_lora.a.data.copy_(rl["a"].to(dev))
            r_lora.b.data.copy_(rl["b"].to(dev))
        head_lora = FactorizedLinearLoRA.from_payload(st["head_lora"], dev) if st.get("head_lora") else None
        cg = SubspaceEnergyGate.from_payload(st["subspace_gate"], dev) if st.get("subspace_gate") else None
        cart_bank = ModularSubspaceCartridgeBank.from_payload(st["modular_cartridges"], dev) if st.get("modular_cartridges") else None
        W_eval = {k: v.to(dev) for k, v in st["W_tail_merged"].items()} if st.get("W_tail_merged") else W0
        Wf_eval = {**Wf, "norm": st["final_norm"].to(dev)} if st.get("final_norm") is not None else Wf

        def fwd(x, acc, p, A, Z, m, trained_mode: bool, ema_states: dict[str, float] | None = None):
            if trained_mode and r_lora is not None:
                idx, wts, xl = route(x)
                acc = acc + r_lora.delta_acc(xl, idx, wts, orig_exp, K.situ_mul)
            h = K.final_from_terms(p, K.moe_tail(acc, x, W_eval if trained_mode else W0, c), A, Z, m, Wf_eval if trained_mode else Wf, c)
            lg = (h @ lm_head.t()).float()
            new_ema = ema_states
            if trained_mode:
                if cart_bank is not None:
                    d_lg, new_ema = cart_bank.delta_sequence(h, x_sensor=x, base_logits=lg, ema_states=ema_states)
                    lg = lg + d_lg
                elif head_lora is not None:
                    d_lg = head_lora.delta(h)
                    if cg is not None:
                        src = x.detach() if cg.sensor_mode == "x92" else h.detach()
                        d_lg = cg(src) * d_lg
                    lg = lg + d_lg
            return lg, new_ema

        sh0 = cache.shards[0]
        s = json.loads((sh0["dir"] / "streams.json").read_text())
        pass_nll = np.load(sh0["dir"] / "nll.npy")
        T = s["seq"]
        skip_k = max(0, int(a.skip_prefix_tokens))
        res, raw = {"per_set": {}, "per_set_no_prefix": {}, "skip_prefix_tokens": skip_k}, {}
        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]
            is_g_set = (sname == "wikipedia" or str(sname).startswith("general"))
            sk = 0 if is_g_set else min(skip_k, max(0, T - 3))
            per = {"lb": [], "lb_fulltail": [], "base": []}
            per_np = {"lb": [], "lb_fulltail": [], "base": []}
            for i in seqs:
                rows = np.arange(i * T, (i + 1) * T - 1)
                lb_a, ft_a = [], []
                ema_st: dict[str, float] | None = None
                with torch.no_grad():
                    for k0 in range(0, len(rows), 2048):
                        x, acc, p, A, Z, m, t = cache.batch(rows[k0:k0 + 2048], dev)
                        lg_b, _ = fwd(x, acc, p, A, Z, m, False)
                        lg_t, ema_st = fwd(x, acc, p, A, Z, m, True, ema_states=ema_st)
                        lb_a.append(F.cross_entropy(lg_b, t, reduction="none").cpu())
                        ft_a.append(F.cross_entropy(lg_t, t, reduction="none").cpu())
                lb, ft = torch.cat(lb_a).numpy(), torch.cat(ft_a).numpy()
                raw[f"{sname}/{i}/lb"], raw[f"{sname}/{i}/lb_fulltail"] = lb.astype(np.float32), ft.astype(np.float32)
                per["lb"].append(lb.mean())
                per["lb_fulltail"].append(ft.mean())
                per_np["lb"].append(lb[sk:].mean())
                per_np["lb_fulltail"].append(ft[sk:].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())
                    per_np["base"].append(b[sk:].mean())
            for dst_key, pdict in (("per_set", per), ("per_set_no_prefix", per_np)):
                r = {k: float(np.mean(v)) for k, v in pdict.items() if v}
                if pdict["base"]:
                    b, rng_e = np.array(pdict["base"]), np.random.default_rng(0)
                    for k_ in ("lb", "lb_fulltail"):
                        d = (np.array(pdict[k_]) - b) / b
                        bs_ = [float(rng_e.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[dst_key][sname] = r
        for acc_key, src_key in (("acceptance", "per_set"), ("acceptance_no_prefix", "per_set_no_prefix")):
            dom = {k_: v for k_, v in res[src_key].items() if k_ != "wikipedia" and not k_.startswith("general")}
            gen = [v for k_, v in res[src_key].items() if k_ == "wikipedia" or k_.startswith("general")]
            wins = sum(1 for v in dom.values() if v.get("lb_fulltail_vs_base_rel", 1) <= -0.02)
            gen_ok = bool(gen) and all(v.get("lb_fulltail_vs_base_rel", 1) <= 0.005 for v in gen)
            res[acc_key] = {"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_fulltail.raw.npz", **raw)
        (out / "verdict_fulltail.json").write_text(json.dumps(res, indent=1))
        print(json.dumps(res["acceptance_no_prefix"]), json.dumps(res["per_set_no_prefix"], indent=1))
        return 0

    # --- TRAIN ---
    torch.manual_seed(a.seed)
    rng = np.random.default_rng(a.seed)
    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))])
    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 is_target_domain(m, target_domains) and i not in val_seq, min_pos=a.skip_prefix_tokens)
    tr_gen = cache.rows(lambda i, m: m["role"] == "train" and is_gen(m) and i not in val_seq, min_pos=0)
    va_dom = cache.rows(lambda i, m: m["role"] == "train" and is_target_domain(m, target_domains) and i in val_seq, min_pos=a.skip_prefix_tokens)
    va_gen = cache.rows(lambda i, m: m["role"] == "train" and is_gen(m) and i in val_seq, min_pos=0)
    print(f"MultiCache ({len(a.cache)} dirs) domains={sorted(target_domains) or ['ALL']} modular={a.modular_cartridges} "
          f"oof_ema={a.oof_causal_ema} wiki_shield={a.wiki_shield} sensor={a.gate_sensor} tr_lambda={a.tr_lambda} "
          f"skip_prefix={a.skip_prefix_tokens} | "
          f"tr_dom={len(tr_dom):,} tr_gen={len(tr_gen):,} va_dom={len(va_dom):,} va_gen={len(va_gen):,}", flush=True)

    # --- ARM-7 / ARM-9b / ARM-10 / ARM-11 MODULAR CARTRIDGE PATH ---
    if a.modular_cartridges:
        active_doms = sorted({extract_domain_name(m) for i, m in enumerate(cache.meta) if m["role"] == "train" and is_target_domain(m, target_domains)})
        assert active_doms, "No target domains found in cache for --modular-cartridges"
        per_dom_tr = {d: cache.rows(lambda i, m, d=d: m["role"] == "train" and extract_domain_name(m) == d and i not in val_seq, min_pos=a.skip_prefix_tokens) for d in active_doms}
        per_dom_va = {d: cache.rows(lambda i, m, d=d: m["role"] == "train" and extract_domain_name(m) == d and i in val_seq, min_pos=a.skip_prefix_tokens) for d in active_doms}
        all_train_eval_seqs = [i for i, m in enumerate(cache.meta) if m["role"] == "train"]

        tau_ent: float | None = None
        gamma_ent = 4.0
        wiki_shield_gate: SubspaceEnergyGate | None = None
        ws_row_table: np.ndarray | None = None

        if a.oof_causal_ema:
            # Arm-10 / Arm-11: Document-level OOF calibration on x92 (or h) + RMSNorm + Ridge 0.25 + CausalEMA!
            tr_gen_seqs = [i for i, m in enumerate(cache.meta) if m["role"] == "train" and is_gen(m) and i not in val_seq]
            per_dom_tr_seqs = {d: [i for i, m in enumerate(cache.meta) if m["role"] == "train" and extract_domain_name(m) == d and i not in val_seq] for d in active_doms}
            bg_doms = sorted({extract_domain_name(m) for i, m in enumerate(cache.meta) if m["role"] == "train" and not is_gen(m) and extract_domain_name(m) not in active_doms})
            bg_tr_seqs = {bd: [i for i, m in enumerate(cache.meta) if m["role"] == "train" and extract_domain_name(m) == bd and i not in val_seq] for bd in bg_doms}

            gen_seq_t = collect_sensor_seqs(tr_gen_seqs, a.gate_sensor)
            dom_seq_t = {d: collect_sensor_seqs(per_dom_tr_seqs[d], a.gate_sensor) for d in active_doms}
            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 {}

            if a.wiki_shield:
                # Stage-1 WikiShield guards strictly against general_wiki (q=0.998 -> ~0.99 science recall, 0.000 wiki!).
                # Background non-target domains (physics/chemistry) are guarded in Stage-2 specialist routers at q=0.92!
                all_pos_t = [s for d in active_doms for s in dom_seq_t[d]]
                ws_negs = [(gen_seq_t, 0.998)]
                wiki_shield_gate = SubspaceEnergyGate.fit_oof_from_sequences(
                    all_pos_t, ws_negs, r_sub=a.subspace_rank, reg=0.25,
                    beta_ema=a.causal_ema, alpha_lin=a.hybrid_alpha, n_folds=4, warmup=8, sensor_mode=a.gate_sensor,
                )
                ws_row_table = precompute_seq_gates(wiki_shield_gate, all_train_eval_seqs, a.gate_sensor)
                print(f"[Arm-11 WikiShield] sensor={a.gate_sensor} ema={a.causal_ema} | "
                      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)
            if a.entropy_gate:
                # Allow combining Arm10/Arm11 WikiShield WITH Arm9b EntropyGate u(H(p_base)) to prevent +3.1% easy-token damage!
                _, e_gen_s = collect_h_and_ent(rng.permutation(tr_gen), cap=4096)
                _, e_dom_s = collect_h_and_ent(rng.permutation(tr_dom), cap=4096)
                tau_mem = float(torch.quantile(e_gen_s, 0.72).item())
                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())))
                print(f"[Arm11+EntropyGate] calibrated tau_ent={tau_ent:.3f} (shuts off easy tokens H < tau_ent!)", flush=True)
        else:
            h_gen_all, e_gen_all = collect_h_and_ent(rng.permutation(tr_gen), cap=8192)
            dom_cal_raw = {d: collect_h_and_ent(rng.permutation(per_dom_tr[d]), cap=8192) for d in active_doms}
            if a.entropy_gate:
                all_dom_e = torch.cat([dom_cal_raw[d][1] for d in active_doms], dim=0)
                tau_mem = float(torch.quantile(e_gen_all, 0.72).item())
                tau_ent = max(tau_mem + 0.30, 0.5 * (float(torch.quantile(e_gen_all, 0.70).item()) + float(torch.quantile(all_dom_e, 0.60).item())))
                h_gen_cal = h_gen_all[e_gen_all >= tau_mem] if int((e_gen_all >= tau_mem).sum()) >= 256 else h_gen_all
                h_dom_cal = {}
                for d in active_doms:
                    hd_d, ed_d = dom_cal_raw[d]
                    q_d = float(torch.quantile(ed_d, a.hard_fit_quantile).item())
                    h_dom_cal[d] = hd_d[ed_d >= q_d] if int((ed_d >= q_d).sum()) >= 256 else hd_d
                print(f"[Arm-9b EntropySubspaceGate] calibrated tau_ent={tau_ent:.3f} (tau_mem={tau_mem:.3f}, q_hard={a.hard_fit_quantile})", flush=True)
            else:
                h_gen_cal = h_gen_all
                h_dom_cal = {d: dom_cal_raw[d][0] for d in active_doms}

        def _ent_mult(base_lg: torch.Tensor) -> torch.Tensor | float:
            if tau_ent is None:
                return 1.0
            return torch.sigmoid(gamma_ent * (token_entropy(base_lg.detach()) - tau_ent))[:, None]

        cartridges: dict[str, tuple[SubspaceEnergyGate, FactorizedLinearLoRA]] = {}
        dom_logs: dict[str, Any] = {}
        total_steps = 0

        for d in active_doms:
            if a.oof_causal_ema:
                if a.wiki_shield:
                    other_neg = [(dom_seq_t[od], 0.90) for od in active_doms if od != d]
                    for bd in sorted(bg_seq_t):
                        other_neg.append((bg_seq_t[bd], 0.92))
                    if not other_neg:
                        other_neg = [(gen_seq_t, 0.998)]
                    gd = SubspaceEnergyGate.fit_oof_from_sequences(
                        dom_seq_t[d], other_neg, r_sub=a.subspace_rank, reg=0.25,
                        beta_ema=a.causal_ema, alpha_lin=a.hybrid_alpha, n_folds=4, warmup=8, sensor_mode=a.gate_sensor,
                    )
                else:
                    neg_seq_g = [(gen_seq_t, 0.998)] + [(dom_seq_t[od], 0.992) for od in active_doms if od != d]
                    for bd in sorted(bg_seq_t):
                        neg_seq_g.append((bg_seq_t[bd], 0.992))
                    gd = SubspaceEnergyGate.fit_oof_from_sequences(
                        dom_seq_t[d], neg_seq_g, r_sub=a.subspace_rank, reg=0.25,
                        beta_ema=a.causal_ema, alpha_lin=a.hybrid_alpha, n_folds=4, warmup=8, sensor_mode=a.gate_sensor,
                    )
                g_row_table = precompute_seq_gates(gd, all_train_eval_seqs, a.gate_sensor)
                if ws_row_table is not None:
                    g_row_table = g_row_table * ws_row_table
                print(f"[Arm10/11 Cartridge:{d}] va_in={float(g_row_table[per_dom_va[d]].mean()):.4f} "
                      f"va_gen={float(g_row_table[va_gen].mean()):.6f}", flush=True)
            else:
                q_neg = 0.992 if a.entropy_gate else 0.998
                neg_groups = [(h_gen_cal, q_neg)] + [(h_dom_cal[od], 0.992 if a.entropy_gate else 0.995) for od in active_doms if od != d]
                gd = SubspaceEnergyGate.fit_multi_neg(h_dom_cal[d], neg_groups, r_sub=a.subspace_rank)
                g_row_table = None
                print(f"[Cartridge:{d}] gate_in={float(gd(h_dom_cal[d]).mean()):.4f} gate_gen={float(gd(h_gen_cal).mean()):.5f}", flush=True)

            ld = FactorizedLinearLoRA(lm_head.shape[0], lm_head.shape[1], a.head_rank, a.head_alpha, dev)
            opt_d = torch.optim.AdamW(list(ld.parameters()), lr=a.lr, weight_decay=a.wd)
            bs_d = min(a.bs, len(per_dom_tr[d]))
            steps_d = max(1, int(a.epochs * len(per_dom_tr[d]) / max(1, bs_d)))
            if a.max_steps > 0:
                steps_d = min(steps_d, a.max_steps)
            sched_d = torch.optim.lr_scheduler.OneCycleLR(opt_d, max_lr=a.lr, total_steps=steps_d, pct_start=0.1)
            best_va, best_st = float("inf"), None

            # Fast precomputed contiguous h_base cache (1 sequential pass -> kills 5-file random mmap + moe_tail/attn_res!)
            h_tr_cache = None
            h_va_cache = None
            if a.precompute_h:
                t_pre = time.perf_counter()
                h_tr_cache = PrecomputedHBaseCache.build(cache, per_dom_tr[d], W0, Wf, c, K, dev, g_row_table=g_row_table)
                h_va_cache = PrecomputedHBaseCache.build(cache, per_dom_va[d], W0, Wf, c, K, dev, g_row_table=g_row_table)
                print(f"[Cartridge:{d}] Precomputed contiguous h_base BF16: tr={h_tr_cache.n:,} va={h_va_cache.n:,} "
                      f"({(h_tr_cache.h.nbytes + h_va_cache.h.nbytes)/1e9:.2f} GB) in {time.perf_counter()-t_pre:.1f}s", flush=True)

            @torch.no_grad()
            def eval_d(rows_e, use_cart=True, h_cache_obj=None):
                rr = []
                if h_cache_obj is not None:
                    for k0 in range(0, h_cache_obj.n, 2048):
                        h, t, gv_c = h_cache_obj.batch(np.arange(k0, min(h_cache_obj.n, k0 + 2048)), dev)
                        lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
                        if use_cart:
                            gv = gv_c if gv_c is not None else gd(h.detach())
                            lg = lg + (gv * _ent_mult(lg)) * ld.delta(h, bf16_amp=a.bf16_amp)
                        rr.append(F.cross_entropy(lg, t, reduction="none").cpu())
                    return float(torch.cat(rr).mean()) if rr else float("inf")
                for k0 in range(0, len(rows_e), 2048):
                    r_ch = np.sort(rows_e[k0:k0 + 2048])
                    x, acc, p, A, Z, m, t = cache.batch(r_ch, dev)
                    h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
                    lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
                    if use_cart:
                        gv = (torch.from_numpy(g_row_table[r_ch]).to(dev)[:, None] if g_row_table is not None else gd(h.detach()))
                        lg = lg + (gv * _ent_mult(lg)) * ld.delta(h, bf16_amp=a.bf16_amp)
                    rr.append(F.cross_entropy(lg, t, reduction="none").cpu())
                return float(torch.cat(rr).mean()) if rr else float("inf")

            va0_d = eval_d(per_dom_va[d], False, h_cache_obj=h_va_cache)
            best_va = va0_d
            best_st = (ld.a.detach().clone(), ld.b.detach().clone())

            t_loop = time.perf_counter()
            io_acc = 0.0
            for st_i in range(steps_d):
                opt_d.zero_grad(set_to_none=True)
                t_io0 = time.perf_counter()
                if h_tr_cache is not None:
                    idx_b = rng.choice(h_tr_cache.n, bs_d, replace=False)
                    h, t, gv_c = h_tr_cache.batch(idx_b, dev)
                    io_acc += time.perf_counter() - t_io0
                    with torch.no_grad():
                        base_lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
                        gv = gv_c if gv_c is not None else gd(h.detach())
                        g_val = gv * _ent_mult(base_lg)
                else:
                    r_batch = sample_contiguous_blocks(per_dom_tr[d], bs_d, a.block_size, rng)
                    x, acc, p, A, Z, m, t = cache.batch(r_batch, dev)
                    io_acc += time.perf_counter() - t_io0
                    with torch.no_grad():
                        h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, m, Wf, c)
                        base_lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
                        gv = (torch.from_numpy(g_row_table[r_batch]).to(dev)[:, None] if g_row_table is not None else gd(h.detach()))
                        g_val = gv * _ent_mult(base_lg)
                delta_lg = ld.delta(h, bf16_amp=a.bf16_amp)
                if a.focal_hard_gamma > 0.0:
                    ce_tok = F.cross_entropy(base_lg + g_val * delta_lg, t, reduction="none")
                    with torch.no_grad():
                        nll_b = F.cross_entropy(base_lg, t, reduction="none")
                        w_f = 1.0 + a.focal_hard_gamma * torch.sigmoid(nll_b - 2.0)
                        w_f = w_f / w_f.mean().clamp_min(1e-6)
                    loss = (ce_tok * w_f).mean()
                else:
                    loss = F.cross_entropy(base_lg + g_val * delta_lg, t)
                if a.tr_lambda > 0:
                    # Exact algebraic Frobenius TR (0 MB vs 1.34 GB VRAM, mathematically identical to delta_lg.pow(2).mean()!)
                    loss = loss + a.tr_lambda * ld.tr_loss(h)
                loss.backward()
                torch.nn.utils.clip_grad_norm_(list(ld.parameters()), 1.0)
                opt_d.step()
                sched_d.step()
                if (st_i + 1) % 20 == 0 or st_i == steps_d - 1:
                    s_per_st = (time.perf_counter() - t_loop) / (st_i + 1)
                    print(f"[Cartridge:{d}] step={st_i+1}/{steps_d} loss={float(loss.detach()):.5f} "
                          f"s_per_step={s_per_st:.3f} io_ms={1000.0*io_acc/(st_i+1):.1f}", flush=True)
                if (st_i + 1) % max(1, steps_d // 8) == 0 or st_i == steps_d - 1:
                    vac = eval_d(per_dom_va[d], True, h_cache_obj=h_va_cache)
                    if vac < best_va:
                        best_va = vac
                        best_st = (ld.a.detach().clone(), ld.b.detach().clone())
            del h_tr_cache, h_va_cache
            with torch.no_grad():
                ld.a.copy_(best_st[0])
                ld.b.copy_(best_st[1])
            cartridges[d] = (gd, ld)
            total_steps += steps_d
            dom_logs[d] = {"val_before": va0_d, "val_after": best_va, "rel_dom": (best_va - va0_d) / va0_d, "steps": steps_d}
            print(f"[Cartridge:{d}] val {va0_d:.5f} -> {best_va:.5f} ({(best_va - va0_d) / va0_d:+.4%})", flush=True)

        bank = ModularSubspaceCartridgeBank(
            cartridges, tau_ent=tau_ent, gamma_ent=gamma_ent,
            sensor_mode=a.gate_sensor, wiki_shield=wiki_shield_gate,
        )
        @torch.no_grad()
        def eval_bank_seqs(seq_list: list[int], use_bank: bool = True) -> float | None:
            rr = []
            for si in seq_list:
                m_s = cache.meta[si]
                rows_s = np.arange(m_s["_base_row"], m_s["_base_row"] + m_s["_T"] - 1, dtype=np.int64)
                ema_st: dict[str, float] | None = None
                for k0 in range(0, len(rows_s), 2048):
                    x, acc, p, A, Z, mm, t = cache.batch(rows_s[k0:k0 + 2048], dev)
                    h = K.final_from_terms(p, K.moe_tail(acc, x, W0, c), A, Z, mm, Wf, c)
                    lg = (h @ lm_head.t()).float()
                    if use_bank:
                        d_lg, ema_st = bank.delta_sequence(h, x_sensor=x, base_logits=lg, ema_states=ema_st)
                        lg = lg + d_lg
                    rr.append(F.cross_entropy(lg, t, reduction="none").cpu())
            return float(torch.cat(rr).mean()) if rr else None

        va_dom_seqs = [i for i, m in enumerate(cache.meta) if m["role"] == "train" and is_target_domain(m, target_domains) and i in val_seq]
        va_gen_seqs = [i for i, m in enumerate(cache.meta) if m["role"] == "train" and is_gen(m) and i in val_seq]
        val0, vg0 = eval_bank_seqs(va_dom_seqs, False), eval_bank_seqs(va_gen_seqs, False)
        val1, vg1 = eval_bank_seqs(va_dom_seqs, True), eval_bank_seqs(va_gen_seqs, True)
        rel_d = (val1 - val0) / val0
        rel_g = None if (vg0 is None or vg1 is None) else (vg1 - vg0) / vg0
        n_par = sum(p.numel() for p in bank.loras.parameters())
        mode_name = (
            "Arm11_STAR_TwoStage_WikiShield_Cartridge" if a.wiki_shield else
            "Arm10_STAR_DecoupledOOF_CausalEMA_Cartridge" if a.oof_causal_ema else
            "Arm9b_STAR_EntropySubspaceCartridge" if a.entropy_gate else
            "Arm7_ModularSubspaceCartridge_TR"
        )
        ckpt = {"modular_cartridges": bank.state_payload(), "hot": [], "routed_lora": None, "head_lora": None, "final_norm": None, "W_tail_merged": None, "subspace_gate": None}
        torch.save(ckpt, out / "full_tail_wsp.pt")
        (out / "train_record.json").write_text(json.dumps({
            "args": vars(a), "mode": mode_name,
            "tau_ent": tau_ent, "sensor_mode": a.gate_sensor, "causal_ema": a.causal_ema,
            "wiki_shield": a.wiki_shield, "domains": active_doms,
            "trained_parameters": n_par, "val_before": val0, "val_after": val1,
            "val_gen_before": vg0, "val_gen_after": vg1, "rel_dom": rel_d, "rel_gen": rel_g,
            "steps": total_steps, "per_domain": dom_logs,
        }, indent=1))
        print(f"MODULAR BANK ({mode_name}) val_after={val1:.6f} rel_dom={rel_d:+.5f} rel_gen={rel_g}", flush=True)
        return 0

    # --- STANDARD / FULL-TAIL / SHARED SUBSPACE-GATE-TR PATH ---
    hot, orig_exp, r_lora, routing_share, new_routing_share = [], [], None, 0.0, 0.0
    if (a.k > 0 or a.include_new_experts) and a.routed_rank > 0:
        counts = torch.zeros(gate.shape[0], device=dev)
        for i in range(0, len(tr_dom), 4096):
            x = cache.batch(tr_dom[i:i + 4096], dev)[0]
            counts += torch.bincount(route(x)[0].reshape(-1), minlength=gate.shape[0]).float()
        if a.include_new_experts and gate.shape[0] > 896:
            k_base = min(a.k, 896)
            hot_base = counts[:896].topk(k_base).indices.tolist() if k_base > 0 else []
            hot_new = list(range(896, gate.shape[0]))
            hot = sorted(set(hot_base) | set(hot_new))
        else:
            hot = counts.topk(min(a.k, gate.shape[0])).indices.tolist()
        tot_c = counts.sum().clamp_min(1.0)
        routing_share = float(counts[hot].sum() / tot_c)
        new_routing_share = float(counts[896:].sum() / tot_c) if gate.shape[0] > 896 else 0.0
        orig_exp = [_load_exp_w1_w3(e) for e in hot]
        if dev.type == "cuda":
            torch.cuda.empty_cache()
        d_latent, d_hidden = orig_exp[0][1]
        r_lora = RoutedW2LoRA(hot, d_latent, d_hidden, a.routed_rank, a.routed_alpha, dev)
        n_new_in_hot = sum(1 for e in hot if e >= 896)
        print(f"Routed W2 LoRA: K={len(hot)} (new_experts_included={n_new_in_hot}) r={a.routed_rank} "
              f"routing_share={routing_share:.4f} new_share={new_routing_share:.4f}", flush=True)

    tail_lora, tail_norm = None, None
    if a.tail_rank > 0:
        tail_lora = {n: TT.LoRA(W0[n], a.tail_rank, a.tail_alpha) for n in TRAINABLE_TAIL}
        tail_norm = nn.Parameter(W0["routed_expert_norm"].float().clone())

    def Wcur():
        if tail_lora is None:
            return W0
        W = {n: tail_lora[n].weight() for n in TRAINABLE_TAIL}
        W["routed_expert_norm"] = tail_norm.to(W0["routed_expert_norm"].dtype)
        return W

    fn_param = nn.Parameter(Wf["norm"].float().clone()) if (a.train_final_norm and not a.gated_head) else None
    head_lora = FactorizedLinearLoRA(lm_head.shape[0], lm_head.shape[1], a.head_rank, a.head_alpha, dev) if a.head_rank > 0 else None

    # Arm-6b: Fit SubspaceEnergyGate on post-`final_norm` `h_base` (IDENTICAL to train & eval!)
    cg = None
    if a.gated_head and head_lora is not None and len(tr_gen) > 0:
        hd_cal = collect_h_base(rng.permutation(tr_dom), cap=8192)
        hg_cal = collect_h_base(rng.permutation(tr_gen), cap=8192)
        cg = SubspaceEnergyGate.fit_from_hidden(hd_cal, hg_cal, r_sub=a.subspace_rank, gen_quantile=0.998)
        print("SubspaceEnergyGate fitted on h_base:",
              "train_dom_gate=", round(float(cg(hd_cal).mean()), 4),
              "train_gen_gate=", round(float(cg(hg_cal).mean()), 5), flush=True)

    params: list[nn.Parameter] = []
    if head_lora is not None:
        params += list(head_lora.parameters())
    if fn_param is not None:
        params.append(fn_param)
    if tail_lora is not None:
        params += [p for m in tail_lora.values() for p in m.parameters() if p.requires_grad] + [tail_norm]
    if r_lora is not None:
        params += list(r_lora.parameters())
    n_par = sum(p.numel() for p in params)
    print(f"Total trainable params: {n_par:,} (tr_lambda={a.tr_lambda})", flush=True)

    def fwd_train(x, acc, p, A, Z, m, use_trained: bool = True, return_h: bool = False):
        if use_trained and r_lora is not None:
            idx, wts, xl = route(x)
            acc = acc + r_lora.delta_acc(xl, idx, wts, orig_exp, K.situ_mul)
        Wf_c = ({**Wf, "norm": fn_param.to(Wf["norm"].dtype)} if (use_trained and fn_param is not None) else Wf)
        h = K.final_from_terms(p, K.moe_tail(acc, x, Wcur() if use_trained else W0, c), A, Z, m, Wf_c, c)
        lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
        if use_trained and head_lora is not None:
            raw_d = head_lora.delta(h, bf16_amp=a.bf16_amp)
            d_lg = cg(h.detach()) * raw_d if cg is not None else raw_d
            lg = lg + d_lg
        return (lg, h) if return_h else lg

    backbone_frozen = (r_lora is None and tail_lora is None and fn_param is None and head_lora is not None)
    h_tr_dom = h_tr_gen = h_va_dom = h_va_gen = None
    if backbone_frozen and a.precompute_h:
        t_pre = time.perf_counter()
        h_tr_dom = PrecomputedHBaseCache.build(cache, tr_dom, W0, Wf, c, K, dev)
        h_va_dom = PrecomputedHBaseCache.build(cache, va_dom, W0, Wf, c, K, dev)
        if len(tr_gen) > 0:
            h_tr_gen = PrecomputedHBaseCache.build(cache, tr_gen, W0, Wf, c, K, dev)
        if len(va_gen) > 0:
            h_va_gen = PrecomputedHBaseCache.build(cache, va_gen, W0, Wf, c, K, dev)
        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
        print(f"[FastHBase] Precomputed contiguous h_base BF16 ({gb_tot:.2f} GB) in {time.perf_counter()-t_pre:.1f}s!", flush=True)

    def eval_nll(rows, use_trained: bool, h_cache_obj=None):
        res = []
        with torch.no_grad():
            if h_cache_obj is not None:
                for i in range(0, h_cache_obj.n, 2048):
                    h, t, _ = h_cache_obj.batch(np.arange(i, min(h_cache_obj.n, i + 2048)), dev)
                    lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
                    if use_trained and head_lora is not None:
                        raw_d = head_lora.delta(h, bf16_amp=a.bf16_amp)
                        lg = lg + (cg(h.detach()) * raw_d if cg is not None else raw_d)
                    res.append(F.cross_entropy(lg, t, reduction="none").cpu())
                return float(torch.cat(res).mean()) if res else None
            for i in range(0, len(rows), 2048):
                x, acc, p, A, Z, m, t = cache.batch(rows[i:i + 2048], dev)
                res.append(F.cross_entropy(fwd_train(x, acc, p, A, Z, m, use_trained), t, reduction="none").cpu())
        return float(torch.cat(res).mean()) if res else None

    val0, vg0 = eval_nll(va_dom, False, h_cache_obj=h_va_dom), eval_nll(va_gen, False, h_cache_obj=h_va_gen)
    v_id = eval_nll(va_dom, True, h_cache_obj=h_va_dom)
    print(f"val_before={val0:.6f} identity_check={v_id:.6f} val_gen_before={vg0}", flush=True)

    opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=a.wd)
    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)))
    if a.max_steps > 0:
        steps = min(steps, a.max_steps)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=steps, pct_start=0.1)
    best_val, best_snap = val0, [p.detach().cpu().clone() for p in params]
    log = []
    t_loop = time.perf_counter()
    io_acc = 0.0
    for step in range(steps):
        opt.zero_grad(set_to_none=True)
        t_io0 = time.perf_counter()
        if h_tr_dom is not None:
            h, t, _ = h_tr_dom.batch(rng.choice(h_tr_dom.n, bs_d, replace=False), dev)
            io_acc += time.perf_counter() - t_io0
            with torch.no_grad():
                base_lg = (h.to(lm_head.dtype) @ lm_head.t()).float()
            raw_d = head_lora.delta(h, bf16_amp=a.bf16_amp)
            lg_d = base_lg + (cg(h.detach()) * raw_d if cg is not None else raw_d)
            loss_d = F.cross_entropy(lg_d, t)
            if a.tr_lambda > 0:
                loss_d = loss_d + a.tr_lambda * head_lora.tr_loss(h)
            ld = float(loss_d.detach())
            loss_d.backward()
            del loss_d, lg_d, raw_d, base_lg, h, t
        else:
            r_dom_b = sample_contiguous_blocks(tr_dom, bs_d, a.block_size, rng)
            x, acc, p, A, Z, m, t = cache.batch(r_dom_b, dev)
            io_acc += time.perf_counter() - t_io0
            lg_d, h_d = fwd_train(x, acc, p, A, Z, m, True, return_h=True)
            loss_d = F.cross_entropy(lg_d, t)
            if a.tr_lambda > 0 and head_lora is not None:
                loss_d = loss_d + a.tr_lambda * head_lora.tr_loss(h_d)
            ld = float(loss_d.detach())
            loss_d.backward()
            del loss_d, lg_d, h_d, x, acc, p, A, Z, m, t
        kl_v = 0.0
        if a.kl > 0 and bs_g > 0:
            t_iog = time.perf_counter()
            if h_tr_gen is not None:
                hg, _, _ = h_tr_gen.batch(rng.choice(h_tr_gen.n, bs_g, replace=False), dev)
                io_acc += time.perf_counter() - t_iog
                with torch.no_grad():
                    base_g = (hg.to(lm_head.dtype) @ lm_head.t()).float()
                    ref = F.log_softmax(base_g, -1)
                raw_dg = head_lora.delta(hg, bf16_amp=a.bf16_amp)
                cur = F.log_softmax(base_g + (cg(hg.detach()) * raw_dg if cg is not None else raw_dg), -1)
                kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
                kl_v = float(kl.detach())
                (a.kl * kl).backward()
                del kl, cur, ref, raw_dg, base_g, hg
            else:
                r_gen_b = sample_contiguous_blocks(tr_gen, bs_g, a.block_size, rng)
                xg, accg, pg, Ag, Zg, mg, _ = cache.batch(r_gen_b, dev)
                io_acc += time.perf_counter() - t_iog
                with torch.no_grad():
                    ref = F.log_softmax(fwd_train(xg, accg, pg, Ag, Zg, mg, False), -1)
                cur = F.log_softmax(fwd_train(xg, accg, pg, Ag, Zg, mg, True), -1)
                kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
                kl_v = float(kl.detach())
                (a.kl * kl).backward()
                del kl, cur, ref, xg, accg, pg, Ag, Zg, mg
        torch.nn.utils.clip_grad_norm_(params, 1.0)
        opt.step()
        sched.step()
        if step % 20 == 0 or step == steps - 1:
            s_per_st = (time.perf_counter() - t_loop) / (step + 1)
            rec = {"step": step, "loss_domain": ld, "loss_kl": kl_v,
                   "s_per_step": round(s_per_st, 3), "io_ms": round(1000.0 * io_acc / (step + 1), 1)}
            log.append(rec)
            print(json.dumps(rec), flush=True)
        if (step + 1) % max(1, steps // 8) == 0 or step == steps - 1:
            vc = eval_nll(va_dom, True, h_cache_obj=h_va_dom)
            vgc = eval_nll(va_gen, True, h_cache_obj=h_va_gen)
            gen_ok_now = (vg0 is None or vgc is None or ((vgc - vg0) / vg0) <= 0.005)
            if vc is not None and gen_ok_now and vc < best_val:
                best_val = vc
                best_snap = [p.detach().cpu().clone() for p in params]

    with torch.no_grad():
        for p, s_t in zip(params, best_snap):
            p.copy_(s_t.to(dev))

    val1, vg1 = eval_nll(va_dom, True, h_cache_obj=h_va_dom), eval_nll(va_gen, True, h_cache_obj=h_va_gen)
    rel_d = (val1 - val0) / val0
    rel_g = None if (vg0 is None or vg1 is None) else (vg1 - vg0) / vg0
    print(f"val_after={val1:.6f} rel_dom={rel_d:+.5f} rel_gen={rel_g}", flush=True)

    W_tail_merged = ({n: tail_lora[n].merged().cpu() for n in TRAINABLE_TAIL} | {"routed_expert_norm": tail_norm.detach().to(W0["routed_expert_norm"].dtype).cpu()}) if tail_lora is not None else None
    ckpt = {
        "hot": hot,
        "routed_lora": None if r_lora is None else {"a": r_lora.a.detach().cpu(), "b": r_lora.b.detach().cpu(), "alpha": a.routed_alpha},
        "head_lora": None if head_lora is None else head_lora.state_payload(),
        "final_norm": None if fn_param is None else fn_param.detach().to(Wf["norm"].dtype).cpu(),
        "W_tail_merged": W_tail_merged,
        "subspace_gate": None if cg is None else cg.state_payload(),
        "modular_cartridges": None,
    }
    torch.save(ckpt, out / "full_tail_wsp.pt")
    (out / "train_record.json").write_text(json.dumps({
        "args": vars(a), "domains": sorted(target_domains), "trained_parameters": n_par,
        "routing_share": routing_share, "val_before": val0, "identity_check": v_id, "val_after": val1,
        "val_gen_before": vg0, "val_gen_after": vg1, "rel_dom": rel_d, "rel_gen": rel_g,
        "steps": steps, "log": log,
    }, indent=1))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())