File size: 86,093 Bytes
123d4d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Public Kroha architecture, including routed-output RMSNorm.
"""KrohaRoutedNorm: self-contained Hugging Face hybrid language model.

Only this file and configuration_kroha.py are required alongside the weights.
Transformers supplies RoPE, RMSNorm, dense SwiGLU, attention dispatch/masks,
hybrid caches, generation, causal loss and the portable gated-delta kernel.
PyTorch supplies projections, convolutions, grouped GEMMs and checkpointing.
FLA is an optional CUDA acceleration, never a CPU/import-time requirement.

The architecture-specific pieces retained here are the SharedGate router,
latent experts, recursive adapters and Block AttnRes history. They cannot be
replaced with a dense Llama/Qwen block without changing the trained function.
"""
from contextlib import contextmanager
from functools import lru_cache, partial

import torch
from torch import nn
from torch.nn import functional as F
from transformers import GenerationMixin, PreTrainedModel
from transformers.cache_utils import DynamicCache
from transformers.masking_utils import create_causal_mask
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
from transformers.models.llama.modeling_llama import (
    LlamaAttention, LlamaMLP, LlamaRMSNorm, LlamaRotaryEmbedding,
    apply_rotary_pos_emb, eager_attention_forward, repeat_kv,
)

from .configuration_kroha import KrohaRoutedNormConfig

# The HF hub-kernel decorator can select an installed CUDA FLA function even
# for CPU tensors. The explicit portable/reference path must call its original
# torch implementation; the CUDA branch below dispatches to FLA explicitly.
@lru_cache(maxsize=1)
def _torch_delta_implementation():
    # Lazy import: merely importing the model/registry must not probe CUDA or
    # import optional FLA kernels before a caller acquires its GPU lease.
    from transformers.models.qwen3_next.modeling_qwen3_next import torch_recurrent_gated_delta_rule
    return getattr(torch_recurrent_gated_delta_rule, "__wrapped__", torch_recurrent_gated_delta_rule)


class KrohaRoutedNormRMSNorm(LlamaRMSNorm):
    """HF RMSNorm, plus the trained model's explicit output-dtype boundary.

    HF returns FP32 when its weights are FP32 under BF16 autocast. This cast
    retains the former QK/activation dtype; all normalization math is HF's.
    """
    def forward(self, hidden_states):
        return super().forward(hidden_states).to(hidden_states.dtype)


class KrohaRoutedNormMLP(LlamaMLP):
    """Standard HF dense SwiGLU with KrohaRoutedNorm's trained scalar output gate."""
    def __init__(self, config):
        super().__init__(config)
        self.output_gate = KrohaRoutedNormScalarGate(config.hidden_size, config.gate_multiplier) if config.mlp_scalar_gate else None

    def forward(self, hidden_states):
        branch = super().forward(hidden_states)
        return self.output_gate(branch, hidden_states) if self.output_gate is not None else branch


class KrohaRoutedNormHeadGate(nn.Linear):
    """Standard Linear and sigmoid, identity initialized, before the O projection."""
    def __init__(self, config):
        super().__init__(config.hidden_size, config.num_attention_heads, bias=False)
        nn.init.zeros_(self.weight)



def _head_gate_values(output, hidden_states, weight):
    gate = 2 * torch.sigmoid(F.linear(hidden_states, weight))
    return output * gate.unsqueeze(-1).to(output.dtype)


class KrohaRoutedNormAttention(LlamaAttention):
    """HF projections/attention backends with QK norm and per-application cache.

    Shared physical blocks require a different cache slot on each pass. This
    small adapter is the reason vanilla LlamaAttention.forward cannot be used.
    """
    def __init__(self, config, layer_idx):
        super().__init__(config, layer_idx)
        self.num_heads, self.num_kv_heads = config.num_attention_heads, config.num_key_value_heads
        self.use_rope = layer_idx not in config.nope_layers
        self.q_norm = KrohaRoutedNormRMSNorm(self.head_dim, config.rms_norm_eps) if config.qk_norm else None
        self.k_norm = KrohaRoutedNormRMSNorm(self.head_dim, config.rms_norm_eps) if config.qk_norm else None
        self.output_gate = KrohaRoutedNormScalarGate(config.hidden_size, config.gate_multiplier) if config.attention_scalar_gate else None
        self.head_gate = KrohaRoutedNormHeadGate(config) if config.headwise_attention_gate else None

    def gate_heads(self, output, hidden_states):
        if self.head_gate is None:
            return output
        kernel = getattr(self, '_compiled_head_gate', None)
        if kernel is not None and isinstance(self.head_gate, KrohaRoutedNormHeadGate):
            return kernel(output, hidden_states, self.head_gate.weight)
        gate = 2 * torch.sigmoid(self.head_gate(hidden_states))
        return output * gate.unsqueeze(-1).to(output.dtype)

    def forward(self, hidden_states, position_embeddings, attention_mask=None,
                past_key_values=None, cache_layer_idx=None, q_adapter=None, v_adapter=None,
                document_cu_seqlens_cpu=None, **kwargs):
        shape = (*hidden_states.shape[:-1], -1, self.head_dim)
        q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
        if q_adapter is not None:
            q, v = q + q_adapter(hidden_states), v + v_adapter(hidden_states)
        q, k, v = (x.view(shape).transpose(1, 2) for x in (q, k, v))
        if self.q_norm is not None:
            q, k = self.q_norm(q), self.k_norm(k)
        if self.use_rope:
            q, k = apply_rotary_pos_emb(q, k, *position_embeddings)
        if past_key_values is not None:
            k, v = past_key_values.update(k, v, cache_layer_idx)
        interface = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, eager_attention_forward)
        # Official FlashAttention consumes standard packed cumulative lengths.
        # The caller's dense document mask is used by SDPA/eager/flex instead.
        flash = "flash_attention" in self.config._attn_implementation
        if "flash_attention_4" in self.config._attn_implementation and self.num_key_value_groups > 1:
            # Keep the established SM120-safe expanded-KV compute layout while
            # retaining native GQA cache storage. Dispatch remains HF's FA4.
            k, v = repeat_kv(k, self.num_key_value_groups), repeat_kv(v, self.num_key_value_groups)
        cu = kwargs.pop("document_cu_seqlens", None)
        maximum = kwargs.pop("document_max_seqlen", None)
        kwargs.pop("document_ids", None)
        kwargs.pop("document_ranges", None)
        if flash and cu is not None:
            b, _, t, _ = q.shape
            q, k, v = (x.transpose(1, 2).reshape(1, b*t, x.shape[1], x.shape[-1]).transpose(1, 2)
                       for x in (q, k, v))
            kwargs.update(cu_seq_lens_q=cu, cu_seq_lens_k=cu, max_length_q=maximum, max_length_k=maximum)
            # Explicit offsets, rather than token values, define isolation.
            kwargs.pop("position_ids", None)
        output, _ = interface(self, q, k, v, attention_mask,
            scaling=self.scaling, dropout=self.attention_dropout if self.training else 0., **kwargs)
        output = output.reshape(*hidden_states.shape[:-1], self.num_heads, self.head_dim)
        output = self.gate_heads(output, hidden_states)
        output = self.o_proj(output.flatten(-2).contiguous())
        return self.output_gate(output, hidden_states) if self.output_gate is not None else output


def recurrent_delta_reference(q, k, v, g, beta, initial_state=None,
                              output_final_state=False, document_ids=None, **kwargs):
    """Use Transformers' actual gated-delta implementation, with segment resets."""
    options = dict(initial_state=initial_state, output_final_state=output_final_state,
                   use_qk_l2norm_in_kernel=True)
    implementation = _torch_delta_implementation()
    if document_ids is None:
        return implementation(q, k, v, g, beta, **options)
    if initial_state is not None or output_final_state:
        raise ValueError("Packed documents cannot carry an inference state")
    rows = []
    for b, ids in enumerate(document_ids.tolist()):
        starts = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i-1]] + [len(ids)]
        pieces = []
        for start, end in zip(starts, starts[1:]):
            tensors = [x[b:b+1, start:end] for x in (q, k, v, g, beta)]
            out, _ = implementation(*tensors, use_qk_l2norm_in_kernel=True)
            pieces.append(out)
        rows.append(torch.cat(pieces, dim=1))
    return torch.cat(rows, dim=0), None


# BEGIN GENERATED ARCHITECTURE HELPERS

def document_positions(document_ids):
    positions = torch.arange(document_ids.shape[1], device=document_ids.device).expand_as(document_ids)
    starts = torch.ones_like(document_ids, dtype=torch.bool)
    starts[:, 1:] = document_ids[:, 1:] != document_ids[:, :-1]
    return positions - positions.masked_fill(~starts, 0).cummax(1).values


def document_mask(document_ids, dtype, *, causal=True, key_document_ids=None, attention_mask=None, prefix_lengths=None):
    """Portable SDPA/eager mask; real queries never see another document or padding."""
    keys = document_ids if key_document_ids is None else key_document_ids
    allowed = (document_ids[:, :, None] == keys[:, None, :]) & (keys[:, None, :] >= 0)
    if attention_mask is not None:
        allowed = allowed & attention_mask[:, None, :].bool()
    if causal:
        q = torch.arange(document_ids.shape[1], device=document_ids.device)
        k = torch.arange(keys.shape[1], device=keys.device)
        order = k[None, :] <= q[:, None]
        if prefix_lengths is not None:
            pos = document_positions(document_ids)
            prefix = prefix_lengths[:, None] if prefix_lengths.ndim == 1 else prefix_lengths
            order = order | (pos[:, :, None] < prefix[:, :, None]) & (pos[:, None, :] < prefix[:, :, None])
        allowed = allowed & order
    allowed[:, :, 0] |= document_ids < 0
    return torch.zeros(allowed.shape, dtype=dtype, device=allowed.device).masked_fill_(~allowed, -torch.inf)[:, None]


def segmented_depthwise_conv(x, weight, document_ids, *, lag_masks=None):
    """Causal [B,C,L] depthwise convolution with zero history at every boundary."""
    length, width = (x.shape[-1], weight.shape[-1])
    result = torch.zeros_like(x)
    for lag in range(min(width, length)):
        shifted = x if lag == 0 else F.pad(x[..., :-lag], (lag, 0))
        if lag:
            valid = lag_masks[lag - 1] if lag_masks is not None else F.pad(document_ids[:, lag:] == document_ids[:, :-lag], (lag, 0))
            shifted = shifted * valid[:, None].to(x.dtype)
        result = result + shifted * weight[:, 0, width - 1 - lag].to(x.dtype)[None, :, None]
    return result


def routing_statistics(probabilities, indices, valid_mask):
    probabilities = probabilities.reshape(-1, probabilities.shape[-1]).float()
    indices = indices.reshape(probabilities.shape[0], -1)
    valid = valid_mask.reshape(-1).to(device=probabilities.device, dtype=torch.float32)
    counts = torch.zeros(probabilities.shape[-1], device=probabilities.device)
    counts.scatter_add_(0, indices.reshape(-1), valid[:, None].expand_as(indices).reshape(-1))
    return (counts, valid.sum(), (probabilities * valid[:, None]).sum(0))


class _RouterPool:

    def __init__(self, owner):
        self.owner = owner
        self.census = {}
        self.replayed = {}
        self.frozen = {}
        self.buffer = {}
        self.calls = {}
        self.current_calls = set()

    @torch.compiler.disable
    def loss(self, probabilities, indices, valid_mask, slot=0):
        counts, tokens, prob_sum = routing_statistics(probabilities, indices, valid_mask)
        phase = self.owner.phase
        if phase == 'census':
            value = torch.cat((counts, tokens[None]))
            self.census[slot] = self.census.get(slot, torch.zeros_like(value)) + value.detach()
            return (prob_sum.sum() * 0, counts)
        if not torch.is_grad_enabled() and (not self.owner.forward_only):
            raise RuntimeError('Global LBL replay requires nonreentrant checkpointing and enabled gradients')
        if self.owner.algorithm == 'buffered':
            return self.buffered_loss(probabilities, counts, tokens, prob_sum, slot)
        if phase not in ('forward', 'backward') or slot not in self.frozen:
            raise RuntimeError('Global router LBL requires a completed census for every block application')
        if phase == 'forward':
            value = torch.cat((counts, tokens[None]))
            self.replayed[slot] = self.replayed.get(slot, torch.zeros_like(value)) + value.detach()
        frequency, total_tokens = self.frozen[slot]
        scale = self.owner.accumulation_steps * self.owner.world_size / total_tokens.clamp_min(1)
        return (probabilities.shape[-1] * (frequency * prob_sum).sum() * scale, counts)

    def buffered_loss(self, probabilities, counts, tokens, prob_sum, slot):
        if self.owner.phase == 'forward':
            if slot in self.current_calls:
                raise RuntimeError('Each router application needs a distinct balance slot')
            self.current_calls.add(slot)
            current = torch.cat((counts, tokens[None])).detach()
            if self.owner.distributed:
                torch.distributed.all_reduce(current, group=self.owner.process_group)
            cumulative = self.buffer.get(slot, torch.zeros_like(current)) + current
            self.buffer[slot] = cumulative
            frequency = cumulative[:-1] / cumulative[:-1].sum().clamp_min(1)
            self.frozen[slot] = (frequency, current[-1])
            self.calls[slot] = self.calls.get(slot, 0) + 1
        elif self.owner.phase != 'backward' or slot not in self.frozen:
            raise RuntimeError('Buffered LBL requires an original differentiable forward')
        frequency, current_tokens = self.frozen[slot]
        scale = self.owner.world_size / current_tokens.clamp_min(1)
        return (probabilities.shape[-1] * (frequency * prob_sum).sum() * scale, counts)


class GlobalRouterBalance:
    """Step-scoped prefix buffering or exact census, per virtual layer.

    The distributed group, when used, must be the replicated-router data-parallel
    group, not a tensor/expert-parallel group. This does not turn train.py into a
    distributed launcher; its ordinary runner remains single-device.
    """

    def __init__(self, model, accumulation_steps, *, algorithm='exact', process_group=None, forward_only=False):
        if isinstance(accumulation_steps, bool) or not isinstance(accumulation_steps, int) or accumulation_steps < 1:
            raise ValueError('accumulation_steps must be a positive integer')
        self.model = model
        self.accumulation_steps = accumulation_steps
        if algorithm not in ('buffered', 'exact'):
            raise ValueError('Router balance algorithm must be buffered or exact')
        self.algorithm = algorithm
        self.forward_only = forward_only
        self.requires_census = algorithm == 'exact'
        self.microbatches = 0
        self.process_group = process_group
        self.distributed = torch.distributed.is_available() and torch.distributed.is_initialized()
        self.world_size = torch.distributed.get_world_size(process_group) if self.distributed else 1
        self.modules = [module for module in model.modules() if getattr(module, 'supports_global_router_balance', False)]
        if not self.modules:
            raise ValueError('The model has no supported routed experts')
        if not model.training or getattr(model.config, 'router_balance_scope', 'legacy') != 'global':
            raise ValueError('Global router balance requires training with router_balance_scope=global')
        self.phase = 'idle'
        self.pools = [_RouterPool(self) for _ in self.modules]

    def __enter__(self):
        if any((getattr(module, '_global_router_balance', None) is not None for module in self.modules)):
            raise RuntimeError('Global router balance contexts cannot be nested')
        for module, pool in zip(self.modules, self.pools):
            module._global_router_balance = pool
        return self

    def _clear_forward_state(self):
        for module in self.modules:
            if hasattr(module, 'aux_loss'):
                module.aux_loss, module.counts = (None, None)
        if hasattr(self.model.model, 'router_state'):
            self.model.model.router_state = None

    def __exit__(self, *exc):
        for module in self.modules:
            module._global_router_balance = None
        self._clear_forward_state()
        self.phase = 'closed'

    @contextmanager
    def census(self):
        if not self.requires_census:
            raise RuntimeError('Buffered global LBL does not use a census')
        if self.phase != 'idle':
            raise RuntimeError('Take exactly one routing census per optimizer step')
        self.phase = 'census'
        devices = sorted({p.device.index for p in self.model.parameters() if p.device.type == 'cuda'})
        try:
            with torch.random.fork_rng(devices=devices), torch.no_grad():
                yield
            for pool in self.pools:
                if not pool.census:
                    raise RuntimeError('Routing census missed an expert module')
                for slot, local in pool.census.items():
                    total = local.clone()
                    if self.distributed:
                        torch.distributed.all_reduce(total, group=self.process_group)
                    counts, tokens = (total[:-1], total[-1])
                    pool.frozen[slot] = (counts / counts.sum().clamp_min(1), tokens)
            self.phase = 'ready'
        finally:
            self._clear_forward_state()

    @contextmanager
    def forward(self):
        allowed = ('idle', 'backward') if not self.requires_census else ('ready', 'backward')
        if self.phase not in allowed:
            raise RuntimeError("A differentiable forward requires the step's frozen census")
        if not self.requires_census:
            if self.microbatches >= self.accumulation_steps:
                raise RuntimeError('Buffered LBL received too many microbatches for this step')
            for pool in self.pools:
                pool.current_calls.clear()
                pool.frozen.clear()
        self.phase = 'forward'
        try:
            yield
            self.microbatches += 1
        finally:
            self.phase = 'backward'

    def validate(self):
        """Fail before optimizer.step if census/replay routing or coverage differs."""
        if self.phase != 'backward':
            raise RuntimeError('Validate after every microbatch has been backpropagated')
        if not self.requires_census:
            if self.microbatches != self.accumulation_steps or any((not pool.calls or any((n != self.accumulation_steps for n in pool.calls.values())) for pool in self.pools)):
                raise RuntimeError('Buffered LBL missed a microbatch or router application; optimizer step cancelled')
            return
        differences = []
        for pool in self.pools:
            if pool.census.keys() != pool.replayed.keys():
                raise RuntimeError('Census/replay block applications differ')
            differences.extend(((value != pool.replayed[slot]).any().float() for slot, value in pool.census.items()))
        mismatches = torch.stack(differences).sum()
        if self.distributed:
            torch.distributed.all_reduce(mismatches, group=self.process_group)
        if mismatches.item():
            raise RuntimeError('Global LBL routing census differs from training replay; optimizer step cancelled')


def global_router_loss(module, probabilities, indices, valid_mask, slot=0):
    pool = getattr(module, "_global_router_balance", None)
    if pool is None:
        raise RuntimeError("Global LBL requires model.router_balance() over the optimizer step")
    return pool.loss(probabilities, indices, valid_mask, slot)



class KrohaRoutedNormScalarGate(nn.Module):
    """Content-dependent scalar gate: output = branch * multiplier * sigmoid(W x)."""

    def __init__(self, hidden_size: int, multiplier: float=2.0):
        super().__init__()
        self.projection = nn.Linear(hidden_size, 1, bias=False)
        self.multiplier = multiplier

    def forward(self, branch: torch.Tensor, residual_input: torch.Tensor) -> torch.Tensor:
        kernel = getattr(self, '_compiled_gate', None)
        if kernel is not None:
            return kernel(branch, residual_input, self.projection.weight, self.multiplier)
        return branch * self.multiplier * torch.sigmoid(self.projection(residual_input))

    def reset_parameters(self):
        nn.init.zeros_(self.projection.weight)


class KrohaRoutedNormLowRank(nn.Module):

    def __init__(self, in_features, out_features, rank, alpha):
        super().__init__()
        self.a = nn.Linear(in_features, rank, bias=False)
        self.b = nn.Linear(rank, out_features, bias=False)
        nn.init.normal_(self.a.weight, std=0.02)
        nn.init.zeros_(self.b.weight)
        self.scaling = alpha / rank

    def forward(self, x):
        return self.b(self.a(x)) * self.scaling


def swiglu(gate, up, limit):
    return F.silu(gate.clamp(max=limit)) * up.clamp(min=-limit, max=limit)


class KrohaRoutedNormMoE(nn.Module):
    supports_global_router_balance = True

    def __init__(self, config):
        super().__init__()
        self.config = config
        d, e, m = (config.hidden_size, config.num_experts, config.expert_intermediate_size)
        l = config.latent_size or d
        self.router = nn.Linear(d, e, bias=False)
        self.register_buffer('expert_bias', torch.zeros(e, dtype=torch.float32))
        self.register_buffer('step_counts', torch.zeros(e, dtype=torch.float32))
        self.register_buffer('last_load', torch.zeros(e, dtype=torch.float32))
        self.gate_up = nn.Parameter(torch.empty(e, 2 * m, l))
        self.down = nn.Parameter(torch.empty(e, l, m))
        nn.init.normal_(self.gate_up, std=0.02)
        nn.init.normal_(self.down, std=0.02)
        self.latent_down = nn.Linear(d, l, bias=False) if config.latent_size else nn.Identity()
        self.routed_norm = KrohaRoutedNormRMSNorm(l, config.rms_norm_eps)
        self.latent_up = nn.Linear(l, d, bias=False) if config.latent_size else nn.Identity()
        self.shared_gate_up = nn.Linear(d, 2 * config.shared_intermediate_size, bias=False)
        self.shared_down = nn.Linear(config.shared_intermediate_size, d, bias=False)
        self.shared_expert_gate = nn.Linear(d, 1, bias=False) if config.shared_expert_gate else None
        if self.shared_expert_gate is not None:
            nn.init.zeros_(self.shared_expert_gate.weight)
        self.output_gate = KrohaRoutedNormScalarGate(d, config.gate_multiplier) if config.mlp_scalar_gate else None
        self.valid_mask = None
        self.aux_loss = None
        self.counts = None
        self.second_router_weight = nn.Parameter(torch.zeros(e, d)) if getattr(config, 'pass2_router', False) else None
        if self.second_router_weight is not None:
            for name in ('second_expert_bias', 'second_step_counts', 'second_last_load'):
                self.register_buffer(name, torch.zeros(e, dtype=torch.float32))

    def route(self, x, *, budget=None, balance_slot=0):
        k = self.config.experts_per_token if budget is None else budget
        if isinstance(k, bool) or not isinstance(k, int) or (not 1 <= k <= self.config.num_experts):
            raise ValueError('Expert budget must be an integer in [1, num_experts]')
        with torch.autocast(device_type=x.device.type, enabled=False):
            second = self.second_router_weight is not None and balance_slot == 1
            weight = self.second_router_weight if second else self.router.weight
            bias = self.second_expert_bias if second else self.expert_bias
            logits = (self.router(x.float()) if not second and weight.dtype == torch.float32
                      else F.linear(x.float(), weight.float()))
            scores = F.softplus(logits).clamp_min(1e-20).sqrt()
            selection = scores.detach() + bias.float()
            indices = selection.argsort(dim=-1, descending=True, stable=True)[..., :k] if getattr(self.config, 'stable_expert_order', False) else selection.topk(k, dim=-1).indices
            weights = scores.gather(-1, indices)
            weights = weights / weights.sum(-1, keepdim=True).clamp_min(1e-20)
        return (scores, indices, weights * self.config.routed_scaling_factor)

    def experts(self, x, indices, weights):
        activate = getattr(self, '_compiled_swiglu', swiglu)
        flat_ids = indices.reshape(-1)
        order = flat_ids.argsort(stable=True)
        token_ids = order // indices.shape[-1]
        selected = x[token_ids]
        counts = torch.zeros(self.config.num_experts, device=x.device, dtype=torch.int32)
        counts.scatter_add_(0, flat_ids, torch.ones_like(flat_ids, dtype=torch.int32))
        use_grouped = x.is_cuda and (x.dtype == torch.bfloat16 or (torch.is_autocast_enabled('cuda') and torch.get_autocast_dtype('cuda') == torch.bfloat16))
        use_grouped = use_grouped and self.config.expert_backend != 'reference'
        if self.config.expert_backend == 'grouped' and (not use_grouped):
            raise ValueError('grouped backend requires CUDA BF16 (or BF16 autocast)')
        if use_grouped:
            grouped_mm = getattr(self, '_compiled_grouped_mm', F.grouped_mm)
            offsets = counts.cumsum(0).to(torch.int32)
            selected = selected.to(torch.bfloat16)
            gu = grouped_mm(selected, self.gate_up.to(selected.dtype).transpose(1, 2), offs=offsets)
            g, u = gu.chunk(2, dim=-1)
            h = activate(g, u, self.config.swiglu_limit)
            output = grouped_mm(h, self.down.to(h.dtype).transpose(1, 2), offs=offsets)
        else:
            chunks = selected.split(counts.tolist())
            outputs = []
            token_chunks = token_ids.split(counts.tolist())
            for i, (chunk, tokens) in enumerate(zip(chunks, token_chunks)):
                g, u = F.linear(chunk, self.gate_up[i]).chunk(2, dim=-1)
                outputs.append(F.linear(activate(g, u, self.config.swiglu_limit), self.down[i]))
            output = torch.cat(outputs)
        weighted = output * weights.reshape(-1)[order, None].to(output.dtype)
        if getattr(self.config, 'stable_expert_order', False):
            slots = torch.empty_like(weighted).index_copy(0, order, weighted)
            return slots.reshape(x.shape[0], indices.shape[-1], -1).float().sum(1).to(output.dtype)
        combined = torch.zeros(x.shape, device=x.device, dtype=output.dtype)
        return combined.index_add(0, token_ids, weighted)

    def forward(self, hidden_states, *, valid_mask=None, return_router_state=False, budget=None, router_input=None, routing_state=None, balance_slot=0):
        b, s, d = hidden_states.shape
        x = hidden_states.reshape(-1, d)
        if router_input is not None and router_input.shape != hidden_states.shape:
            raise ValueError('Router context must match hidden_states shape')
        if routing_state is None:
            route_x = x if router_input is None else router_input.reshape(-1, d)
            scores, ids, weights = self.route(route_x, budget=budget, balance_slot=balance_slot)
        else:
            scores, ids, weights = routing_state
            if scores.shape != (x.shape[0], self.config.num_experts) or ids.shape != weights.shape:
                raise ValueError('Invalid precomputed router state')
            if ids.shape != (x.shape[0], budget):
                raise ValueError('Precomputed router state differs from the block budget')
        aux_loss, counts = (None, None)
        global_balance = getattr(self.config, 'router_balance_scope', 'legacy') == 'global'
        if self.training and (torch.is_grad_enabled() or global_balance):
            valid_mask = self.valid_mask if valid_mask is None else valid_mask
            valid = torch.ones((b, s), device=x.device, dtype=torch.float32) if valid_mask is None else valid_mask.to(device=x.device, dtype=torch.float32)
            prob = scores / scores.sum(-1, keepdim=True).clamp_min(1e-20)
            if global_balance:
                if torch.is_grad_enabled() or getattr(self, '_global_router_balance', None) is not None:
                    aux_loss, counts = global_router_loss(self, prob, ids, valid, balance_slot)
            else:
                assignments = F.one_hot(ids, self.config.num_experts).sum(1).reshape(b, s, -1).float()
                assignments = assignments * valid[..., None]
                counts = assignments.sum((0, 1)).detach()
                lengths = valid.sum(1, keepdim=True).clamp_min(1)
                freq = assignments.sum(1) / (lengths * ids.shape[-1])
                prob = (prob.reshape(b, s, -1) * valid[..., None]).sum(1) / lengths
                per_seq = self.config.num_experts * (freq * prob).sum(-1)
                aux_loss = per_seq.sum() / valid.sum(1).gt(0).sum().clamp_min(1)
            if not return_router_state:
                self.aux_loss, self.counts = (aux_loss, counts)
        latent = self.latent_down(x)
        routed = self.latent_up(self.routed_norm(self.experts(latent, ids, weights)))
        g, u = self.shared_gate_up(x).chunk(2, dim=-1)
        activate = getattr(self, '_compiled_swiglu', swiglu)
        shared = self.shared_down(activate(g, u, self.config.swiglu_limit))
        if self.shared_expert_gate is not None:
            gate = getattr(self, '_compiled_shared_gate', None)
            shared = (gate(shared, x, self.shared_expert_gate.weight, 2.0) if gate is not None else
                      shared * (2 * torch.sigmoid(self.shared_expert_gate(x))))
        result = (routed + shared).reshape(b, s, d)
        result = self.output_gate(result, hidden_states) if self.output_gate is not None else result
        return (result, aux_loss, counts) if return_router_state else result


class KrohaRoutedNormDeltaNet(nn.Module):

    def __init__(self, config, layer_idx):
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.head_dim = config.head_dim
        self.num_heads = config.num_attention_heads
        self.num_kv_heads = config.num_key_value_heads
        self.num_query_heads = getattr(config, 'delta_num_query_heads', self.num_heads)
        self.num_value_heads = getattr(config, 'delta_num_value_heads', self.num_kv_heads)
        if any((h < 1 or self.num_heads % h for h in (self.num_query_heads, self.num_kv_heads, self.num_value_heads))):
            raise ValueError('Delta Q/K/V head counts must divide the recurrent state head count')
        self.groups = self.num_heads // self.num_kv_heads
        q_dim = self.num_query_heads * self.head_dim
        kv_dim = self.num_kv_heads * self.head_dim
        v_dim = self.num_value_heads * self.head_dim
        output_dim = self.num_heads * self.head_dim
        self.q_proj = nn.Linear(config.hidden_size, q_dim, bias=False)
        self.k_proj = nn.Linear(config.hidden_size, kv_dim, bias=False)
        self.v_proj = nn.Linear(config.hidden_size, v_dim, bias=False)
        self.o_proj = nn.Linear(output_dim, config.hidden_size, bias=False)
        self.z_proj = nn.Linear(config.hidden_size, output_dim, bias=False)
        self.a_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
        self.b_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
        conv_dim = q_dim + kv_dim + v_dim
        self.conv1d = nn.Conv1d(conv_dim, conv_dim, config.delta_conv_kernel, groups=conv_dim, bias=False)
        self.A_log = nn.Parameter(torch.empty(self.num_heads).uniform_(0.01, 16).log())
        self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
        self.gated_norm = KrohaRoutedNormRMSNorm(self.head_dim, config.rms_norm_eps)
        self.output_gate = KrohaRoutedNormScalarGate(config.hidden_size, config.gate_multiplier) if config.attention_scalar_gate else None

    def forward(self, hidden_states, position_embeddings=None, attention_mask=None, past_key_values=None, cache_layer_idx=None, q_adapter=None, v_adapter=None, valid_mask=None, document_ids=None, document_cu_seqlens=None, **kwargs):
        if past_key_values is not None and self.training and torch.is_grad_enabled():
            raise ValueError('DeltaNet training requires no mutable inference cache')
        x = hidden_states
        if valid_mask is not None:
            x = x * valid_mask[..., None].to(x.dtype)
        q, k, v = (self.q_proj(x), self.k_proj(x), self.v_proj(x))
        if q_adapter is not None:
            q, v = (q + q_adapter(x), v + v_adapter(x))
        mixed = torch.cat((q, k, v), -1).transpose(1, 2)
        initial_state = None
        if past_key_values is not None:
            layer = past_key_values.layers[cache_layer_idx]
            if layer.is_recurrent_states_initialized[0]:
                initial_state = layer.recurrent_states[0]
            mixed = past_key_values.update_conv_state(mixed, cache_layer_idx, conv_kernel_size=self.config.delta_conv_kernel)
            if initial_state is None:
                mixed = F.pad(mixed, (self.config.delta_conv_kernel - 1, 0))
        else:
            mixed = F.pad(mixed, (self.config.delta_conv_kernel - 1, 0))
        if document_ids is None:
            mixed = self.conv1d(mixed)[..., -x.shape[1]:]
        else:
            if past_key_values is not None:
                raise ValueError('Packed DeltaNet requires no inference cache')
            mixed = getattr(self, '_compiled_segmented_conv', segmented_depthwise_conv)(mixed[..., -x.shape[1]:], self.conv1d.weight, document_ids)
        mixed = F.silu(mixed).transpose(1, 2)
        q_dim = self.num_query_heads * self.head_dim
        kv_dim = self.num_kv_heads * self.head_dim
        v_dim = self.num_value_heads * self.head_dim
        q, k, v = mixed.split((q_dim, kv_dim, v_dim), -1)
        q = q.reshape(*x.shape[:2], self.num_query_heads, self.head_dim)
        if self.num_query_heads != self.num_heads:
            q = q.repeat_interleave(self.num_heads // self.num_query_heads, 2)
        k = k.reshape(*x.shape[:2], self.num_kv_heads, self.head_dim).repeat_interleave(self.groups, 2)
        v = v.reshape(*x.shape[:2], self.num_value_heads, self.head_dim)
        if self.num_value_heads != self.num_heads:
            v = v.repeat_interleave(self.num_heads // self.num_value_heads, 2)
        beta = self.b_proj(x).sigmoid()
        if getattr(self.config, 'delta_beta_multiplier', 1.0) != 1.0:
            beta = beta * self.config.delta_beta_multiplier
        g = -self.A_log.float().exp() * F.softplus(self.a_proj(x).float() + self.dt_bias)
        if valid_mask is not None:
            beta = beta * valid_mask[..., None].to(beta.dtype)
            g = g * valid_mask[..., None].to(g.dtype)
        backend = self.config.delta_backend
        if backend == 'fla' or (backend == 'auto' and q.is_cuda):
            try:
                from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
            except ImportError as exc:
                raise ImportError("CUDA DeltaNet requires the 'gdn' extra: pip install fla-core==0.5.2") from exc
            if self.training and (not torch.is_autocast_enabled('cuda')) and (q.dtype not in (torch.bfloat16, torch.float16)):
                raise ValueError('FLA training requires BF16/FP16 tensors or CUDA autocast')
            kernel = fused_recurrent_gated_delta_rule if x.shape[1] == 1 and (not self.training) else chunk_gated_delta_rule
        else:
            kernel = recurrent_delta_reference
        kernel_options = {}
        original_shape = q.shape
        if document_ids is not None:
            if backend == 'fla' or (backend == 'auto' and q.is_cuda):
                if document_cu_seqlens is None:
                    raise ValueError('Packed CUDA DeltaNet requires precomputed document_cu_seqlens')
                q, k, v = (t.reshape(1, -1, *t.shape[2:]) for t in (q, k, v))
                g, beta = (t.reshape(1, -1, t.shape[-1]) for t in (g, beta))
                kernel_options['cu_seqlens'] = document_cu_seqlens
                if kwargs.get('document_cu_seqlens_cpu') is not None:
                    kernel_options['cu_seqlens_cpu'] = kwargs['document_cu_seqlens_cpu']
            else:
                kernel_options['document_ids'] = document_ids
        output, state = kernel(q.contiguous(), k.contiguous(), v.contiguous(), g=g.contiguous(), beta=beta.contiguous(), initial_state=initial_state, output_final_state=past_key_values is not None, use_qk_l2norm_in_kernel=True, **kernel_options)
        output = output.reshape(*original_shape)
        if past_key_values is not None:
            past_key_values.update_recurrent_state(state, cache_layer_idx)
        z = self.z_proj(x).reshape_as(output)
        output = self.gated_norm(output) * z.float().sigmoid().to(output.dtype)
        if valid_mask is not None:
            output = output * valid_mask[..., None, None].to(output.dtype)
        output = self.o_proj(output.flatten(-2))
        return self.output_gate(output, hidden_states) if self.output_gate is not None else output


def _depth_attention_scores(keys, query):
    """Pure score reduction; normalized keys keep the original RMSNorm boundary."""
    return torch.stack([(key.float() * query.float()).sum(-1) for key in keys])


def _depth_attention_mix(scores, sources):
    """Pure depth softmax/value reduction, retaining every per-source dtype cast."""
    weights = scores.softmax(0)
    result = sources[0] * weights[0].unsqueeze(-1).to(sources[0].dtype)
    for i in range(1, len(sources)):
        result = result + sources[i] * weights[i].unsqueeze(-1).to(sources[i].dtype)
    return result


class KrohaRoutedNormDepthAttention(nn.Module):
    """Per-token softmax over depth; stream values instead of stacking N*B*T*D.

    A zero pseudo-query gives the paper's uniform initialization. Keys alone are
    RMS-normalized. Neither a token axis nor a document axis is ever reduced.
    """

    def __init__(self, config):
        super().__init__()
        self.query = nn.Parameter(torch.zeros(config.hidden_size))
        self.key_norm = KrohaRoutedNormRMSNorm(config.hidden_size, config.rms_norm_eps)

    def forward(self, *sources):
        if not sources:
            raise ValueError('Depth attention requires at least the token embedding')
        kernels = getattr(self, '_compiled_depth_attention', None)
        if kernels is not None:
            keys = tuple((self.key_norm(value) for value in sources))
            scores = kernels[0](keys, self.query)
            return kernels[1](scores, sources)
        scores = torch.stack([(self.key_norm(value).float() * self.query.float()).sum(-1) for value in sources])
        weights = scores.softmax(0)
        result = sources[0] * weights[0].unsqueeze(-1).to(sources[0].dtype)
        for i in range(1, len(sources)):
            result = result + sources[i] * weights[i].unsqueeze(-1).to(sources[i].dtype)
        return result

# END GENERATED ARCHITECTURE HELPERS


class KrohaRoutedNormLayer(nn.Module):
    def __init__(self, config, layer_idx, core=False):
        super().__init__()
        self.self_attn = (KrohaRoutedNormDeltaNet(config, layer_idx) if config.layer_types[layer_idx] == "linear_attention"
                          else KrohaRoutedNormAttention(config, layer_idx))
        self.mlp = KrohaRoutedNormMoE(config) if core else KrohaRoutedNormMLP(config)
        self.input_layernorm = KrohaRoutedNormRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.post_attention_layernorm = KrohaRoutedNormRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.specialized = core and config.relaxed
        if self.specialized:
            delta = config.layer_types[layer_idx] == "linear_attention"
            q_size = config.num_attention_heads * config.head_dim
            v_size = config.num_key_value_heads * config.head_dim
            self.q_adapter = KrohaRoutedNormLowRank(config.hidden_size, q_size, config.lora_rank, config.lora_alpha)
            self.v_adapter = KrohaRoutedNormLowRank(config.hidden_size, v_size, config.lora_rank, config.lora_alpha)
            self.second_input_layernorm = KrohaRoutedNormRMSNorm(config.hidden_size, config.rms_norm_eps)
            self.second_post_attention_layernorm = KrohaRoutedNormRMSNorm(config.hidden_size, config.rms_norm_eps)
            self.residual_gains = nn.Parameter(torch.ones(2))
        self.attn_res, self.mlp_res = KrohaRoutedNormDepthAttention(config), KrohaRoutedNormDepthAttention(config)


def _apply_layer(partial_block, *blocks, layer, pass_index, core, cache_index,
                 positions, mask, valid, past_key_values, options, output_hidden_states=False):
    sources = blocks + (() if partial_block is None else (partial_block,))
    hidden = layer.attn_res(*sources)
    application_input = hidden if output_hidden_states else None
    second = layer.specialized and pass_index == 1
    input_norm = layer.second_input_layernorm if second else layer.input_layernorm
    ffn_norm = layer.second_post_attention_layernorm if second else layer.post_attention_layernorm
    branch = layer.self_attn(input_norm(hidden), positions, attention_mask=mask, valid_mask=valid,
        past_key_values=past_key_values, cache_layer_idx=cache_index,
        q_adapter=layer.q_adapter if second else None, v_adapter=layer.v_adapter if second else None, **options)
    if second:
        branch = layer.residual_gains[0] * branch
    partial_block = branch if partial_block is None else partial_block + branch
    hidden = ffn_norm(layer.mlp_res(*blocks, partial_block))
    if core:
        branch, aux, counts = layer.mlp(hidden, valid_mask=valid, return_router_state=True, balance_slot=pass_index)
    else:
        branch, aux, counts = layer.mlp(hidden), None, None
    if second:
        branch = layer.residual_gains[1] * branch
    return partial_block + branch, aux, counts, application_input


class KrohaRoutedNormPreTrainedModel(PreTrainedModel):
    config_class = KrohaRoutedNormConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["KrohaRoutedNormLayer"]
    _skip_keys_device_placement = ["past_key_values"]
    _supports_sdpa = _supports_flash_attn = _supports_flex_attn = True
    _supports_attention_backend = True
    _keep_in_fp32_modules = ["router"]
    # Unlike the non-strict list, HF also honors this under BF16 loading.
    # Routing scores and recurrent decay parameters retain their FP32 contract.
    _keep_in_fp32_modules_strict = ["router", "A_log", "dt_bias"]

    def _init_weights(self, module):
        super()._init_weights(module)
        if isinstance(module, KrohaRoutedNormLowRank):
            nn.init.zeros_(module.b.weight)
        elif isinstance(module, KrohaRoutedNormHeadGate):
            nn.init.zeros_(module.weight)
        elif isinstance(module, KrohaRoutedNormMoE) and module.shared_expert_gate is not None:
            nn.init.zeros_(module.shared_expert_gate.weight)

    def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, every_n_layers=1, offload=False):
        options = {"use_reentrant": False, **(gradient_checkpointing_kwargs or {})}
        if options["use_reentrant"]:
            raise ValueError("Recursive auxiliary gradients require nonreentrant checkpointing")
        if every_n_layers != 1:
            raise ValueError("Use KrohaRoutedNorm's explicit all/core checkpoint policy")
        return super().gradient_checkpointing_enable(gradient_checkpointing_kwargs=options, every_n_layers=1, offload=offload)


class KrohaRoutedNormModel(KrohaRoutedNormPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)
        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
        self.prelude = KrohaRoutedNormLayer(config, 0)
        self.layers = nn.ModuleList(KrohaRoutedNormLayer(config, i+1, core=True) for i in range(config.num_core_layers))
        self.coda = KrohaRoutedNormLayer(config, config.num_hidden_layers-1)
        self.norm = KrohaRoutedNormRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.rotary_emb = LlamaRotaryEmbedding(config)
        self.output_res = KrohaRoutedNormDepthAttention(config)
        self.gradient_checkpointing = False
        self.checkpoint_dense_edges = True
        self.router_state = None
        self.post_init()

    def configure_checkpoint_policy(self, policy="all"):
        if policy not in ("all", "core"):
            raise ValueError("Unknown checkpoint policy")
        self.checkpoint_dense_edges = policy == "all"

    def forward(self, input_ids=None, attention_mask=None, position_ids=None,
                past_key_values=None, inputs_embeds=None, use_cache=None,
                document_ids=None, document_cu_seqlens=None, document_max_seqlen=None,
                output_hidden_states=None, output_attentions=None, return_dict=None, **kwargs):
        if (input_ids is None) == (inputs_embeds is None):
            raise ValueError("Specify exactly one of input_ids or inputs_embeds")
        if attention_mask is not None and attention_mask.ndim != 2:
            raise ValueError("Provide an ordinary 2D padding mask; document_ids controls packing")
        output_hidden_states = self.config.output_hidden_states if output_hidden_states is None else output_hidden_states
        return_dict = self.config.return_dict if return_dict is None else return_dict
        if output_attentions:
            raise NotImplementedError("DeltaNet has no dense attention matrix; dense attention-map output is unsupported")
        use_cache = (self.config.use_cache and not self.training) if use_cache is None else use_cache
        if self.gradient_checkpointing and self.training and (use_cache or past_key_values is not None):
            raise ValueError("Checkpointed training requires use_cache=False")
        hidden = self.embed_tokens(input_ids) if inputs_embeds is None else inputs_embeds
        passes = getattr(self, "inference_num_passes", None) or self.config.num_passes
        if self.training and passes != self.config.num_passes:
            raise ValueError("Reset inference passes before training")
        if document_ids is not None and (use_cache or past_key_values is not None):
            raise ValueError("Packed training cannot carry inference caches")
        if use_cache and past_key_values is None:
            past_key_values = DynamicCache(config=self.config)
        if past_key_values is not None:
            previous_passes = getattr(past_key_values, "kroha_num_passes", passes)
            if past_key_values.get_seq_length() and previous_passes != passes:
                raise ValueError("Use a fresh cache after changing inference depth")
            past_key_values.kroha_num_passes = passes
        if position_ids is None:
            if document_ids is not None:
                position_ids = document_positions(document_ids)
            elif attention_mask is not None:
                position_ids = (attention_mask.long().cumsum(-1)-1).clamp_min(0)[:, -hidden.shape[1]:]
            else:
                offset = past_key_values.get_seq_length() if past_key_values is not None else 0
                position_ids = (torch.arange(hidden.shape[1], device=hidden.device)+offset)[None]
        flash = "flash_attention" in self.config._attn_implementation
        if document_ids is not None:
            if document_cu_seqlens is None:
                starts = torch.ones_like(document_ids, dtype=torch.bool)
                starts[:, 1:] = document_ids[:, 1:] != document_ids[:, :-1]
                indices = starts.flatten().nonzero().flatten()
                document_cu_seqlens = torch.cat((indices, indices.new_tensor([document_ids.numel()]))).int()
            if document_max_seqlen is None:
                document_max_seqlen = int(document_cu_seqlens.diff().max())
            if flash and attention_mask is not None:
                raise ValueError("Flash packed documents require unpadded rows; use SDPA for padding")
            mask = None if flash else document_mask(document_ids, hidden.dtype, attention_mask=attention_mask)
        else:
            mask = create_causal_mask(config=self.config, inputs_embeds=hidden,
                attention_mask=attention_mask, past_key_values=past_key_values, position_ids=position_ids)
        positions = self.rotary_emb(hidden, position_ids)
        valid = attention_mask[:, -hidden.shape[1]:] if attention_mask is not None else None
        options = dict(kwargs, position_ids=position_ids, document_ids=document_ids,
                       document_cu_seqlens=document_cu_seqlens, document_max_seqlen=document_max_seqlen)
        blocks, partial_block, state = (hidden,), None, []
        all_hidden_states = () if output_hidden_states else None
        applications = [(self.prelude, False, 0, 0, None)]
        applications += [(layer, True, p, 1+p*self.config.num_core_layers+i, i)
                         for p in range(passes) for i, layer in enumerate(self.layers)]
        applications += [(self.coda, False, 0, self.config.num_hidden_layers-1, None)]
        for i, (layer, core, p, cache_index, physical_index) in enumerate(applications):
            function = partial(_apply_layer, layer=layer, core=core, pass_index=p, cache_index=cache_index,
                positions=positions, mask=mask, valid=valid, past_key_values=past_key_values, options=options,
                output_hidden_states=output_hidden_states)
            checkpoint = self.gradient_checkpointing and self.training and (core or self.checkpoint_dense_edges)
            partial_block, aux, counts, application_input = (self._gradient_checkpointing_func(function, partial_block, *blocks)
                if checkpoint else function(partial_block, *blocks))
            if output_hidden_states:
                all_hidden_states += (application_input,)
            if aux is not None:
                state.append((physical_index, aux, counts))
            if (2*(i+1)) % self.config.attnres_block_size == 0:
                blocks, partial_block = (*blocks, partial_block), None
        self.router_state = state if state else None
        sources = blocks + (() if partial_block is None else (partial_block,))
        hidden = (self._gradient_checkpointing_func(self.output_res, *sources)
                  if self.gradient_checkpointing and self.training else self.output_res(*sources))
        hidden = self.norm(hidden)
        if output_hidden_states:
            all_hidden_states += (hidden,)
        output = BaseModelOutputWithPast(last_hidden_state=hidden, past_key_values=past_key_values,
                                        hidden_states=all_hidden_states)
        return output if return_dict else output.to_tuple()


class KrohaRoutedNormForCausalLM(KrohaRoutedNormPreTrainedModel, GenerationMixin):
    _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}

    def __init__(self, config):
        super().__init__(config)
        self.model = KrohaRoutedNormModel(config)
        self.vocab_size = config.vocab_size
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
        self.post_init()

    def get_input_embeddings(self):
        return self.model.embed_tokens

    def set_input_embeddings(self, value):
        self.model.embed_tokens = value

    def get_output_embeddings(self):
        return self.lm_head

    @staticmethod
    def legacy_tensor_name(name):
        if name.endswith('.head_gate_weight'):
            return name.removesuffix('.head_gate_weight') + '.head_gate.weight'
        suffixes = ('.q_adapter.a', '.q_adapter.b', '.v_adapter.a', '.v_adapter.b', '.shared_expert_gate')
        return name + '.weight' if name.endswith(suffixes) else name

    def load_legacy_state_dict(self, state_dict):
        """Migrate trained tensors; validate then retire the old frequency buffer.

        HF recomputes its nonpersistent rotary buffers from configuration. Only
        that known buffer and a redundant tied LM-head alias may be absent.
        Every learned tensor must retain its original name, shape and value.
        """
        state = {self.legacy_tensor_name(name): value for name, value in state_dict.items()}
        frequencies = state.pop("model.rotary_emb.inv_freq", None)
        if frequencies is None:
            raise ValueError("Legacy checkpoint is missing its persisted RoPE frequencies")
        torch.testing.assert_close(frequencies.float().cpu(), self.model.rotary_emb.inv_freq.float().cpu(), atol=0, rtol=0)
        if self.config.tie_word_embeddings and "lm_head.weight" not in state:
            state["lm_head.weight"] = state["model.embed_tokens.weight"]
        result = self.load_state_dict(state, strict=True)
        if self.config.tie_word_embeddings and self.lm_head.weight is not self.model.embed_tokens.weight:
            raise RuntimeError("Embedding and LM head lost their shared parameter")
        return result

    def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None,
                inputs_embeds=None, labels=None, use_cache=None, logits_to_keep=0,
                output_hidden_states=None, output_attentions=None, return_dict=None, **kwargs):
        return_dict = self.config.return_dict if return_dict is None else return_dict
        outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids,
            past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache,
            output_hidden_states=output_hidden_states, output_attentions=output_attentions, return_dict=True, **kwargs)
        indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
        logits = self.lm_head(outputs.last_hidden_state[:, indices])
        loss = None
        if labels is not None:
            if logits_to_keep != 0:
                raise ValueError("Training labels require full logits")
            labels = labels.clone()
            if attention_mask is not None:
                labels.masked_fill_(~attention_mask.bool(), -100)
            if kwargs.get("document_ids") is not None:
                docs = kwargs["document_ids"]
                labels[:, 1:].masked_fill_(docs[:, 1:] != docs[:, :-1], -100)
            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size,
                                      num_items_in_batch=kwargs.get("num_items_in_batch"))
            if self.training:
                loss = loss + self.consume_router_loss()
        output = CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values,
                                       hidden_states=outputs.hidden_states)
        return output if return_dict else output.to_tuple()

    # BEGIN GENERATED TRAINING METHODS

    def set_inference_passes(self, passes=None):
        """Execute a trained core prefix without changing weights/config/cache slots.

            Load the original checkpoint first and call in eval mode. Existing caches
            must be discarded whenever this setting changes. None restores training
            depth; the override is deliberately absent from saved checkpoints.
            """
        if passes is not None:
            if self.training:
                raise ValueError('Set inference passes only in eval mode')
            if type(passes) is not int or not 1 <= passes <= self.config.num_passes:
                raise ValueError('Inference passes must be an integer within trained depth')
        self.model.inference_num_passes = passes
        return self

    def consume_router_loss(self, metrics=None):
        state = self.model.router_state
        if state is None or len(state) != self.config.num_core_layers * self.config.num_passes:
            raise RuntimeError('Consume router loss once after each training forward')
        aux = torch.stack([loss for _, loss, _ in state]).mean()
        for i, _, counts in state:
            self.model.layers[i].mlp.step_counts.add_(counts)
        self.model.router_state = None
        if metrics is not None:
            scope = 'global' if self.config.router_balance_scope == 'global' else 'seq'
            metrics[f'train/router_{scope}_aux_raw'] = aux.detach()
            metrics[f'train/router_{scope}_aux_weighted'] = aux.detach() * self.config.router_seq_aux_coef
        return aux * self.config.router_seq_aux_coef

    @torch.no_grad()
    def update_router_bias(self):
        for layer in self.model.layers:
            moe = layer.mlp
            counts = moe.step_counts
            if torch.distributed.is_initialized():
                torch.distributed.all_reduce(counts)
            mean = counts.mean()
            moe.expert_bias.add_(self.config.router_bias_speed * (mean - counts).sign())
            moe.expert_bias.sub_(moe.expert_bias.mean())
            moe.last_load.copy_(counts / mean.clamp_min(1))
            counts.zero_()

    @torch.no_grad()
    def router_metrics(self):
        result = {}
        for i, layer in enumerate(self.model.layers):
            moe = layer.mlp
            result[f'moe/layer_{i}/max_relative_load'] = moe.last_load.max()
            result[f'moe/layer_{i}/bias_abs_max'] = moe.expert_bias.abs().max()
            for e in range(self.config.num_experts):
                result[f'moe/layer_{i}/expert_{e}_relative_load'] = moe.last_load[e]
        return result

    def parameter_budget(self):
        total = sum((p.numel() for p in self.parameters()))
        routed = sum((layer.mlp.gate_up.numel() + layer.mlp.down.numel() for layer in self.model.layers))
        result = {'total': total, 'unique_blocks': self.config.num_core_layers + 2, 'block_applications': self.config.num_hidden_layers, 'pass_specialization': sum((p.numel() for name, p in self.named_parameters() if any((key in name for key in ('adapter', 'second_', 'residual_gains')))))}
        if self.config.num_passes == 1:
            result['active'] = total - routed + routed * self.config.experts_per_token // self.config.num_experts
        return result

    # END GENERATED TRAINING METHODS

    def router_balance(self, accumulation_steps=1, algorithm="buffered", **kwargs):
        return GlobalRouterBalance(self, accumulation_steps, algorithm=algorithm, **kwargs)

    def enable_optimizations(self):
        """Compile standard modules in place; no changes to parameters or code export."""
        if next(self.parameters()).device.type != "cuda":
            return 0
        torch._dynamo.config.recompile_limit = max(torch._dynamo.config.recompile_limit, 64)
        count = 0
        for module in self.modules():
            if isinstance(module, KrohaRoutedNormAttention) and module.head_gate is not None:
                module._compiled_head_gate = _head_gate_kernel()
                count += 1
            elif isinstance(module, (KrohaRoutedNormRMSNorm, KrohaRoutedNormScalarGate)):
                module.compile(dynamic=True, fullgraph=True)
                count += 1
            elif isinstance(module, KrohaRoutedNormDepthAttention):
                module._compiled_depth_attention = _depth_kernels()
                count += 1
            elif isinstance(module, KrohaRoutedNormMoE):
                module._compiled_swiglu = _swiglu_kernel()
                count += 1
        return count


@lru_cache(maxsize=1)
def _head_gate_kernel():
    return torch.compile(_head_gate_values, dynamic=True, fullgraph=True, options={"emulate_precision_casts": True})


@lru_cache(maxsize=1)
def _depth_kernels():
    return tuple(torch.compile(fn, dynamic=True, fullgraph=True, options={"emulate_precision_casts": True})
                 for fn in (_depth_attention_scores, _depth_attention_mix))


@lru_cache(maxsize=1)
def _swiglu_kernel():
    return torch.compile(swiglu, dynamic=True, fullgraph=True)


def make_kroha_trainer(**kwargs):
    """Standard HF Trainer with optimizer-wide buffered LBL and bias callbacks.

    Imports training dependencies lazily. Per-microbatch CE averaging matches
    the original recipe; the Trainer's global-token loss override is disabled.
    Tail accumulation uses Trainer.current_gradient_accumulation_steps.
    """
    from transformers import Trainer, TrainerCallback

    class RouterCallback(TrainerCallback):
        def __init__(self, trainer):
            self.trainer = trainer

        def on_pre_optimizer_step(self, args, state, control, **callback_kwargs):
            owner = self.trainer
            if owner._kroha_balance is not None:
                owner._kroha_balance.validate()
                owner._kroha_balance.__exit__(None, None, None)
                owner._kroha_balance = None

        def on_optimizer_step(self, args, state, control, **callback_kwargs):
            owner = self.trainer
            if not owner.accelerator.optimizer_step_was_skipped:
                owner.accelerator.unwrap_model(owner.model).update_router_bias()

        def on_train_end(self, args, state, control, **callback_kwargs):
            owner = self.trainer
            if owner._kroha_balance is not None:
                owner._kroha_balance.__exit__(None, None, None)
                owner._kroha_balance = None

    class KrohaRoutedNormTrainer(Trainer):
        def __init__(self, **trainer_kwargs):
            super().__init__(**trainer_kwargs)
            self._kroha_balance = None
            self.model_accepts_loss_kwargs = False
            self.add_callback(RouterCallback(self))

        def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
            base = self.accelerator.unwrap_model(model)
            if base.training and base.config.router_balance_scope == "global":
                if self._kroha_balance is None:
                    accumulation = getattr(self, "current_gradient_accumulation_steps", self.args.gradient_accumulation_steps)
                    self._kroha_balance = base.router_balance(accumulation, algorithm="buffered")
                    self._kroha_balance.__enter__()
                with self._kroha_balance.forward():
                    return super().compute_loss(model, inputs, return_outputs=return_outputs, num_items_in_batch=None)
            return super().compute_loss(model, inputs, return_outputs=return_outputs, num_items_in_batch=None)

    return KrohaRoutedNormTrainer(**kwargs)


KrohaRoutedNormModel.register_for_auto_class("AutoModel")
KrohaRoutedNormForCausalLM.register_for_auto_class("AutoModelForCausalLM")

# BEGIN BAKED STANDALONE TOKENIZER CODECS

# chat.py SHA-256: adb13223e488d8cb02c489bf64d1f3b5cb1331f3b6d12491e6a3f933db35b38b

import copy

import json

import re

BASE_TOKENS = ["<pad>", "<s>", "</s>", "<unk>"]

ACTIVE_TOKENS = BASE_TOKENS + [
    "<|im_start|>", "<|im_end|>", "<tool_call>", "</tool_call>",
    "<think>", "</think>", "<|fim_prefix|>", "<|fim_middle|>", "<|fim_suffix|>",
]

RESERVED_TOKENS = [f"<|reserved_{i:03d}|>" for i in range(64 - len(ACTIVE_TOKENS))]

CONTROL_TOKENS = ACTIVE_TOKENS + RESERVED_TOKENS

VISIBLE_MARKERS = {"<tool_call>", "</tool_call>", "<think>", "</think>"}

TOOL_INSTRUCTIONS = (
    "Available tools are described by the following JSON schemas. "
    'To call a tool, emit <tool_call>{"id":"call_0","name":"tool_name",'
    '"arguments":{}}</tool_call>. Use a unique id for every call. '
    "Wait for matching tool results before continuing. Call tools only when needed.\n"
)

NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_.:-]{0,127}\Z")

CALL_ID = re.compile(r"[A-Za-z0-9_-]{1,64}\Z")

def json_text(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)

def _pairs(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate JSON key: {key}")
        result[key] = value
    return result

def _constant(value):
    raise ValueError(f"Non-finite JSON value: {value}")

def _valid_name(value):
    if not isinstance(value, str) or not NAME.fullmatch(value):
        raise ValueError("Invalid function name")
    return value

def _valid_id(value):
    if not isinstance(value, str) or not CALL_ID.fullmatch(value):
        raise ValueError("Invalid tool_call_id")
    return value

def prepare_chat(messages, tools=None, *, add_generation_prompt=False):
    """Validate history; normalize API argument strings exactly once.

    Pending calls may end a training record, but cannot be followed by a new
    assistant/user turn until all results arrive. Missing call IDs are assigned
    reproducibly; tool result IDs must refer to the resulting IDs.
    """
    if not messages:
        raise ValueError("A conversation must contain at least one message")
    messages, tools = copy.deepcopy(messages), copy.deepcopy(tools or [])
    names = set()
    for tool in tools:
        if not isinstance(tool, dict) or tool.get("type") != "function":
            raise ValueError("Tools must be function JSON Schema objects")
        function = tool.get("function", {})
        name = _valid_name(function.get("name"))
        if name in names:
            raise ValueError("Duplicate tool definition")
        names.add(name)
        parameters = function.get("parameters", {})
        if not isinstance(parameters, dict) or parameters.get("type", "object") != "object":
            raise ValueError("Tool parameters must describe a JSON object")
    json_text(tools)  # Fail before rendering non-JSON metadata.
    pending, seen = {}, set()
    for mi, message in enumerate(messages):
        role = message.get("role")
        if role not in {"system", "developer", "user", "assistant", "tool"}:
            raise ValueError("Unknown message role")
        if pending and role != "tool":
            raise ValueError("Unresolved tool calls before next conversation turn")
        content = message.get("content")
        if content is None:
            content = ""
        if not isinstance(content, str):
            raise ValueError("This protocol accepts text content only")
        message["content"] = content
        reasoning = message.get("reasoning_content")
        if reasoning is not None and not isinstance(reasoning, str):
            raise ValueError("reasoning_content must be text")
        if role != "assistant" and (reasoning or message.get("tool_calls")):
            raise ValueError("Only assistant messages can contain reasoning/tool_calls")
        if role == "tool":
            call_id = _valid_id(message.get("tool_call_id"))
            if call_id not in pending:
                raise ValueError("Orphan or duplicate tool result")
            expected_name = pending.pop(call_id)
            if message.get("name", expected_name) != expected_name:
                raise ValueError("Tool result name does not match call")
            message["name"] = expected_name
        calls = message.get("tool_calls") or []
        if not isinstance(calls, list):
            raise ValueError("tool_calls must be a list")
        for ci, call in enumerate(calls):
            if call.get("type", "function") != "function":
                raise ValueError("Only function calls are supported")
            function = call.get("function", {})
            name = _valid_name(function.get("name"))
            if tools and name not in names:
                raise ValueError("Call refers to an undefined tool")
            arguments = function.get("arguments", {})
            if isinstance(arguments, str):
                arguments = json.loads(arguments, object_pairs_hook=_pairs, parse_constant=_constant)
            if not isinstance(arguments, dict):
                raise ValueError("Function arguments must be a JSON object")
            json_text(arguments)
            call_id = _valid_id(call.get("id", f"call_{mi}_{ci}"))
            if call_id in seen:
                raise ValueError("Duplicate tool call id")
            seen.add(call_id)
            pending[call_id] = name
            call.update(id=call_id, type="function", function={"name": name, "arguments": arguments})
        message["tool_calls"] = calls
    if add_generation_prompt and pending:
        raise ValueError("Cannot generate assistant response before tool results arrive")
    return messages, tools

def _segments(messages, tools, add_generation_prompt, enable_thinking, content_segments=None):
    """Yield (text, inserted_control, generated_by_assistant)."""
    def content(message, field, generated):
        if content_segments is None:
            yield message.get(field) or "", False, generated
        else:
            yield from content_segments(message, field, generated)

    if tools:
        yield "<|im_start|>", True, False
        yield "system\n", False, False
        # These two markers belong to our fixed protocol instructions. Schema
        # descriptions, in contrast, are always encoded as literal content.
        before, example = TOOL_INSTRUCTIONS.split("<tool_call>", 1)
        example, after = example.split("</tool_call>", 1)
        yield before, False, False
        yield "<tool_call>", True, False
        yield example, False, False
        yield "</tool_call>", True, False
        yield after + json_text(tools), False, False
        yield "<|im_end|>", True, False
        yield "\n", False, False
    for message in messages:
        role = message["role"]
        generated = role == "assistant"
        yield "<|im_start|>", True, False
        header = role
        if role == "tool":
            header += " name=" + message["name"] + " tool_call_id=" + message["tool_call_id"]
        yield header + "\n", False, False
        if generated and message.get("reasoning_content"):
            yield "<think>", True, True
            yield from content(message, "reasoning_content", True)
            yield "</think>", True, True
        yield from content(message, "content", generated)
        for call in message["tool_calls"]:
            payload = {"id": call["id"], **call["function"]}
            yield "<tool_call>", True, True
            yield json_text(payload), False, True
            yield "</tool_call>", True, True
        yield "<|im_end|>", True, generated
        yield "\n", False, False
    if add_generation_prompt:
        yield "<|im_start|>", True, False
        yield "assistant\n", False, False
        if enable_thinking:
            yield "<think>", True, False

class ChatCodec:
    """Encode raw documents or structured chats without content/control confusion.

    The tokenizer is cloned once, not mutated. No truncation/padding is applied;
    callers must pack/pad input_ids, attention_mask and labels together.
    """
    def __init__(self, tokenizer):
        from tokenizers import Tokenizer
        self.tokenizer = tokenizer
        value = json.loads(tokenizer.backend_tokenizer.to_str())
        value["added_tokens"] = []
        value["post_processor"] = None
        value["padding"] = None
        value["truncation"] = None
        self.raw = Tokenizer.from_str(json.dumps(value))
        self.control_ids = {token: tokenizer.convert_tokens_to_ids(token) for token in CONTROL_TOKENS}
        if len(set(self.control_ids.values())) != 64 or any(
            self.control_ids[token] != i for i, token in enumerate(CONTROL_TOKENS)
        ):
            raise ValueError("ChatCodec requires the multilingual B64 v2 control pool")

    def encode_document(self, text, *, append_eos=True):
        ids = self.raw.encode(text, add_special_tokens=False).ids
        if append_eos:
            ids.append(self.control_ids["</s>"])
        return ids

    def encode_fim(self, prefix, suffix, middle=None):
        """PSM infilling prompt; an optional known middle is followed by EOS."""
        ids = [self.control_ids["<|fim_prefix|>"]]
        ids += self.encode_document(prefix, append_eos=False)
        ids += [self.control_ids["<|fim_suffix|>"]]
        ids += self.encode_document(suffix, append_eos=False)
        ids += [self.control_ids["<|fim_middle|>"]]
        if middle is not None:
            ids += self.encode_document(middle)
        return ids

    def render(self, messages, tools=None, *, add_generation_prompt=False, enable_thinking=False):
        messages, tools = prepare_chat(messages, tools, add_generation_prompt=add_generation_prompt)
        return "".join(text for text, _, _ in _segments(messages, tools, add_generation_prompt, enable_thinking))

    def encode(self, messages, tools=None, *, add_generation_prompt=False, enable_thinking=False):
        messages, tools = prepare_chat(messages, tools, add_generation_prompt=add_generation_prompt)
        return self._encode_segments(_segments(messages, tools, add_generation_prompt, enable_thinking))

    def _encode_segments(self, segments):
        """Shared SFT encoder; explicit atomic items can be control names or IDs."""
        ids, mask, buffer, spans = [], [], "", []

        def flush():
            nonlocal buffer, spans
            if buffer:
                encoded = self.raw.encode(buffer, add_special_tokens=False)
                ids.extend(encoded.ids)
                mask.extend(int(any(a < end and start < b for a, b in spans))
                            for start, end in encoded.offsets)
            buffer, spans = "", []

        for text, control, generated in segments:
            if control:
                flush()
                ids.append(text if isinstance(text, int) else self.control_ids[text])
                mask.append(int(generated))
            else:
                if generated and text:
                    spans.append((len(buffer), len(buffer) + len(text)))
                buffer += text
        flush()
        return {"input_ids": ids, "attention_mask": [1] * len(ids), "assistant_masks": mask,
                "labels": [token if generated else -100 for token, generated in zip(ids, mask)]}

class IncompleteToolCall(ValueError):
    """Buffer more generated text before trying the final-message parser again."""

def parse_assistant(text):
    """Parse a complete generated assistant body, never execute it.

    raw_decode respects quoted closing tags, nested arguments and Unicode. This
    validates the envelope, not tool-specific JSON Schema or argument semantics.
    IncompleteToolCall is retryable; no partial call is returned for execution.
    """
    if text.endswith("<|im_end|>"):
        text = text[:-len("<|im_end|>")]
    reasoning = None
    if text.startswith("<think>"):
        end = text.find("</think>", len("<think>"))
        if end < 0:
            raise IncompleteToolCall("Unclosed reasoning block")
        reasoning, text = text[len("<think>"):end], text[end + len("</think>"):]
    decoder = json.JSONDecoder(object_pairs_hook=_pairs, parse_constant=_constant)
    calls, content, seen = [], [], set()
    while "<tool_call>" in text:
        prefix, text = text.split("<tool_call>", 1)
        content.append(prefix)
        text = text.lstrip()
        try:
            payload, end = decoder.raw_decode(text)
        except json.JSONDecodeError as exc:
            raise IncompleteToolCall("Incomplete or invalid tool JSON") from exc
        remainder = text[end:].lstrip()
        if not remainder.startswith("</tool_call>"):
            if "</tool_call>".startswith(remainder):
                raise IncompleteToolCall("Unclosed tool call")
            raise ValueError("Expected closing tool_call immediately after JSON")
        if not isinstance(payload, dict) or set(payload) != {"id", "name", "arguments"}:
            raise ValueError("Tool call needs exactly id, name and arguments")
        call_id, name = _valid_id(payload["id"]), _valid_name(payload["name"])
        if call_id in seen or not isinstance(payload["arguments"], dict):
            raise ValueError("Duplicate call id or non-object arguments")
        seen.add(call_id)
        calls.append({"id": call_id, "type": "function", "function": {
            "name": name, "arguments": payload["arguments"]}})
        text = remainder[len("</tool_call>"):]
    content.append(text)
    result = {"role": "assistant", "content": "".join(content), "tool_calls": calls}
    if reasoning is not None:
        result["reasoning_content"] = reasoning
    return result

# dna.py SHA-256: adb54fc1d8bc17059ad7274b7a38507de9c6d0ffe798d11303c81cc13d6c85ce

import itertools

import re

BASE_VOCAB_SIZE = 65536

K = 6

CANONICAL = "ACGT"

ALPHABET = "ACGTURYSWKMBDHVN"

DNA_BEGIN = "<dna>"

DNA_END = "</dna>"

DNA_BEGIN_ID = BASE_VOCAB_SIZE

DNA_END_ID = BASE_VOCAB_SIZE + 1

KMER_START = BASE_VOCAB_SIZE + 2

BASE_START = KMER_START + 4 ** K

VOCAB_SIZE = BASE_START + len(ALPHABET)

LEFT, RIGHT = "⟦", "⟧"

TAG = re.compile(r"</?dna>")

def kmer_token(sequence):
    return "DNA6" + LEFT + sequence + RIGHT

def base_token(symbol):
    return "DNABASE" + LEFT + symbol + RIGHT

def dna_tokens():
    return [DNA_BEGIN, DNA_END] + [kmer_token("".join(chars))
        for chars in itertools.product(CANONICAL, repeat=K)] + [base_token(c) for c in ALPHABET]

def checked_spans(text, spans):
    """Unicode character offsets; refuse overlap, reordering and invalid bounds."""
    previous = 0
    for span in spans:
        if isinstance(span, dict):
            start, end = span["start"], span["end"]
        else:
            start, end = span
        if type(start) is not int or type(end) is not int or not previous <= start <= end <= len(text):
            raise ValueError("DNA spans must be ordered, disjoint character offsets within content")
        previous = end
        yield start, end

def split_tagged(text):
    """Yield (body, is_dna) for explicitly tagged input; validate tag balance."""
    cursor, opened = 0, False
    for match in TAG.finditer(text):
        if match.group() == DNA_BEGIN:
            if opened:
                raise ValueError("Nested DNA tags")
            yield text[cursor:match.start()], False
            opened = True
        else:
            if not opened:
                raise ValueError("Closing DNA tag without opening tag")
            yield text[cursor:match.start()], True
            opened = False
        cursor = match.end()
    if opened:
        raise ValueError("Unclosed DNA tag")
    yield text[cursor:], False

class DNACodec(ChatCodec):
    """B64-compatible raw text/chat, with opt-in DNA sequence/span encoding.

    Six-character windows are taken from the exact input. Only a full uppercase
    A/C/G/T window becomes a 6-mer. A noncanonical window or short tail falls
    back character by character. IUPAC uppercase symbols have dedicated DNA IDs;
    lowercase, whitespace, gaps and any other Unicode use the unchanged raw BPE.
    There is no uppercasing, stripping, U->T conversion or dropped remainder.
    """
    def __init__(self, tokenizer):
        super().__init__(tokenizer)
        if len(tokenizer) != VOCAB_SIZE:
            raise ValueError(f"DNA6 codec requires vocabulary {VOCAB_SIZE}")
        for i, token in enumerate(dna_tokens(), BASE_VOCAB_SIZE):
            if tokenizer.convert_tokens_to_ids(token) != i:
                raise ValueError("DNA6 token mapping differs from the saved protocol")
        self.control_ids.update({DNA_BEGIN: DNA_BEGIN_ID, DNA_END: DNA_END_ID})
        self._base_ids = {c: BASE_START + i for i, c in enumerate(ALPHABET)}
        self._digits = {c: i for i, c in enumerate(CANONICAL)}

    def encode_sequence(self, sequence, *, phase=0, include_markers=True):
        """Return IDs, exact character offsets and IUPAC-base offsets.

        bp_offsets count IUPAC letters (case-insensitive, including U), while
        whitespace/gaps/other characters have zero base width. They are still
        preserved in input_ids. Offset metadata is for this sequence only.
        """
        if not isinstance(sequence, str):
            raise TypeError("DNA sequence must be a string")
        if type(phase) is not int or not 0 <= phase < K:
            raise ValueError("DNA phase must be an integer in 0..5")
        ids, offsets, bp_offsets, bp_lengths = [], [], [], []
        bp = 0

        def append(token_id, start, end, bases):
            nonlocal bp
            ids.append(token_id)
            offsets.append((start, end))
            bp_offsets.append((bp, bp + bases))
            bp_lengths.append(bases)
            bp += bases

        def fallback(start, end):
            for pos in range(start, end):
                char = sequence[pos]
                bases = int(char in ALPHABET + ALPHABET.lower())
                if char in self._base_ids:
                    append(self._base_ids[char], pos, pos + 1, 1)
                else:
                    encoded = self.raw.encode(char, add_special_tokens=False)
                    for index, token_id in enumerate(encoded.ids):
                        append(token_id, pos, pos + 1, bases if index == 0 else 0)

        if include_markers:
            append(DNA_BEGIN_ID, 0, 0, 0)
        prefix = min(phase, len(sequence))
        fallback(0, prefix)
        for start in range(prefix, len(sequence), K):
            block = sequence[start:start + K]
            if len(block) == K and all(c in self._digits for c in block):
                rank = 0
                for char in block:
                    rank = rank * 4 + self._digits[char]
                append(KMER_START + rank, start, start + K, K)
            else:
                fallback(start, start + len(block))
        if include_markers:
            append(DNA_END_ID, len(sequence), len(sequence), 0)
        return {"input_ids": ids, "attention_mask": [1] * len(ids),
                "offset_mapping": offsets, "bp_offset_mapping": bp_offsets,
                "bp_lengths": bp_lengths, "num_bases": bp, "phase": phase}

    def decode_sequence(self, ids):
        """Remove only DNA boundaries, retaining every encoded content byte."""
        return self.tokenizer.decode([i for i in ids if i not in (DNA_BEGIN_ID, DNA_END_ID)],
                                     skip_special_tokens=False, clean_up_tokenization_spaces=False)

    def _content_parts(self, text, *, dna_mode=False, dna_spans=None):
        if type(dna_mode) is not bool:
            raise TypeError("dna_mode must be a boolean")
        if dna_spans is not None:
            cursor = 0
            for start, end in checked_spans(text, dna_spans):
                yield text[cursor:start], False
                yield text[start:end], True
                cursor = end
            yield text[cursor:], False
        elif dna_mode:
            yield from split_tagged(text)
        else:
            yield text, False

    def _content_segments(self, text, generated, *, dna_mode=False, dna_spans=None, phase=0):
        for body, is_dna in self._content_parts(text, dna_mode=dna_mode, dna_spans=dna_spans):
            if is_dna:
                for token_id in self.encode_sequence(body, phase=phase)["input_ids"]:
                    yield token_id, True, generated
            else:
                yield body, False, generated

    def encode_document(self, text, *, append_eos=True, dna_mode=False, dna_spans=None, phase=0):
        """Default is exactly old text BPE. dna_mode=True parses explicit tags.

        dna_spans inserts DNA markers around indexed substrings of untagged text.
        Decode those IDs with skip_special_tokens=True to recover untagged text.
        """
        if not dna_mode and dna_spans is None:
            return super().encode_document(text, append_eos=append_eos)
        result = self._encode_segments(self._content_segments(text, False, dna_mode=dna_mode,
                                      dna_spans=dna_spans, phase=phase))["input_ids"]
        if append_eos:
            result.append(self.control_ids["</s>"])
        return result

    def encode(self, messages, tools=None, *, add_generation_prompt=False, enable_thinking=False,
               dna_mode=False, phase=0):
        """Encode text/DNA chats with the existing assistant-only mask.

        Explicit message `dna_spans` and `reasoning_dna_spans` use Unicode offsets.
        A message's `dna_mode` can override the conversation default. Tool schemas
        and JSON call payloads remain text; content/reasoning/tool results can
        contain explicitly marked DNA. No automatic DNA detection is performed.
        """
        messages, tools = prepare_chat(messages, tools, add_generation_prompt=add_generation_prompt)

        def content(message, field, generated):
            spans_key = "dna_spans" if field == "content" else "reasoning_dna_spans"
            yield from self._content_segments(message.get(field) or "", generated,
                dna_mode=message.get("dna_mode", dna_mode), dna_spans=message.get(spans_key), phase=phase)

        return self._encode_segments(_segments(messages, tools, add_generation_prompt, enable_thinking, content))

    def render(self, messages, tools=None, *, add_generation_prompt=False, enable_thinking=False,
               dna_mode=False, phase=0):
        encoded = self.encode(messages, tools, add_generation_prompt=add_generation_prompt,
                              enable_thinking=enable_thinking, dna_mode=dna_mode, phase=phase)
        return self.tokenizer.decode(encoded["input_ids"], skip_special_tokens=False,
                                     clean_up_tokenization_spaces=False)

# END BAKED STANDALONE TOKENIZER CODECS