File size: 85,721 Bytes
3337c74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
"""Recurrent-depth loop adapter serving plugin for Inkling-2-Small in SGLang (GB10 TP4/EP4).

Opt-in via environment variables (zero effect when SPARK_LOOP_ADAPTER is unset):
  SPARK_LOOP_ADAPTER   path inside container to rank-sharded adapter checkpoint dir
                       (contains adapter_rank{r}.pt + meta.json or .safetensors)
  SPARK_LOOP_DEPTH     1 | 2 | 3 (default: 2 if adapter set and not control, else 1)
  SPARK_LOOP_KV_MODE   last_loop | per_pass (default: last_loop)
                       - last_loop: Last-Loop KV Caching (Dory1.0 / arXiv:2611.13378):
                         all passes share physical KV slots 30..41 (final pass overwrites
                         earlier passes -> 0% KV growth, full 1.41M token pool!), while
                         tiny per-request sconv states stay isolated per-pass (~12 MB)
                         to prevent double-shift conv corruption on decode/verify.
                       - per_pass: isolated virtual KV & sconv layers 48..59+ per pass.
  SPARK_LOOP_CONTROL   0 | 1 (default: 0; when 1, forces T=1 with CoreLoRA + CodaLoRA)
  SPARK_LOOP_CD_OMEGA  float (default: 0.0; Apple LoopCD-Hidden arXiv:2610.02185:
                       h_cd = h_R + omega * (h_R - h_1) with FP32 RMS preservation)
  SPARK_LOOP_ZERO_GATES 0 | 1 (default: 0; ablation: zero WorkspaceEntry & CrossPassMixer gates)

Architecture (100% parity with training in src/loop_adapter.py + src/inkling_model.py):
  - Prelude (L0..29): frozen, stock kernels, zero overhead.
  - Pass 0 (L30..41): frozen stock kernels in loop mode (or CoreLoRA slot=0 in control mode),
    using physical KV & sconv layer IDs 30..41.
  - Pass p >= 1 (L30..41): WorkspaceEntry(anchor, s_{p-1}; slot) -> rewind AttnRes to prelude_blocks ->
    Core with CoreLoRA(slot) on qkvr, wo_ud, mlp.gate + CrossPassMixer at L36, using isolated
    virtual KV & sconv layer IDs `48 + (p - 1) * 12 + (lid - 30)` (preserving SWA vs Global split).
  - Optional LoopCD-Hidden on final Core state before Coda.
  - Coda (L42..47): CodaLoRA(slot=0) on qkvr, wo_ud when T >= 2 or control mode; frozen stock at T=1.
  - DSPARK auxiliary hidden states ([5,11,17,23,29,35,41,48]): captures Prelude layers once,
    Core layers [35,41] on the FINAL recurrent pass (p == T - 1), and final hidden after Coda.
  - Compatible with DENSE_P12, MEGAKERNEL, ROCE_AR, FI_MOE, FI_MXFP8, KV_NVFP4, PAGED_DECODE,
    DSPARK, and CUDA graphs (zero CPU-GPU syncs during forward/capture).

MIT License, Copyright (c) 2026 Aiden Le.
"""
from __future__ import annotations

import hashlib
import json
import logging
import os
import sys
from pathlib import Path
from typing import Any

import torch
import torch.nn.functional as F

log = logging.getLogger(__name__)

NUM_PHYSICAL_LAYERS = 48
CORE_START = 30
CORE_END = 42
CORE_LEN = CORE_END - CORE_START  # 12 layers (2 AttnRes blocks: L30..35, L36..41)
MID_CORE_LAYER = CORE_START + 6   # L36
LOCAL_LAYER_IDS = frozenset(i for i in range(NUM_PHYSICAL_LAYERS) if (i + 1) % 6 != 0)
ENTRY_EPS = 1e-6

ADAPTER_DIR = (os.environ.get("SPARK_LOOP_ADAPTER") or "").strip()
MTP_ADAPTER_DIR = (os.environ.get("SPARK_MTP_ADAPTER") or "").strip()
KV_MODE = (os.environ.get("SPARK_LOOP_KV_MODE") or "last_loop").strip().lower()
if KV_MODE not in ("last_loop", "per_pass"):
    raise ValueError(f"SPARK_LOOP_KV_MODE must be 'last_loop' or 'per_pass', got {KV_MODE!r}")
FUSE_LORA = (os.environ.get("SPARK_LOOP_FUSE_LORA") or "1").strip().lower() in ("1", "true", "yes")
TRITON_SEAMS = (os.environ.get("SPARK_LOOP_TRITON_SEAMS") or "1").strip().lower() in ("1", "true", "yes")
CONTROL_MODE = (os.environ.get("SPARK_LOOP_CONTROL") or "0").strip().lower() in ("1", "true", "yes")
ZERO_GATES = (os.environ.get("SPARK_LOOP_ZERO_GATES") or "0").strip().lower() in ("1", "true", "yes")
CD_OMEGA = float(os.environ.get("SPARK_LOOP_CD_OMEGA") or "0.0")
_raw_depth = (os.environ.get("SPARK_LOOP_DEPTH") or "").strip()
if CONTROL_MODE:
    LOOP_DEPTH = 1
elif _raw_depth:
    LOOP_DEPTH = int(_raw_depth)
else:
    LOOP_DEPTH = 2 if ADAPTER_DIR else 1

if LOOP_DEPTH < 1 or LOOP_DEPTH > 4:
    raise ValueError(f"SPARK_LOOP_DEPTH must be in 1..4, got {LOOP_DEPTH}")

EXTRA_SCONV_LAYERS = 0 if (CONTROL_MODE or LOOP_DEPTH <= 1) else (LOOP_DEPTH - 1) * CORE_LEN
EXTRA_KV_LAYERS = EXTRA_SCONV_LAYERS if KV_MODE == "per_pass" else 0
TOTAL_SCONV_LAYERS = NUM_PHYSICAL_LAYERS + EXTRA_SCONV_LAYERS
TOTAL_KV_LAYERS = NUM_PHYSICAL_LAYERS + EXTRA_KV_LAYERS


def virtual_layer_id(pass_idx: int, physical_lid: int) -> int:
    assert pass_idx >= 1 and CORE_START <= physical_lid < CORE_END
    return NUM_PHYSICAL_LAYERS + (pass_idx - 1) * CORE_LEN + (physical_lid - CORE_START)


def _pass_slot(pass_idx: int, total_passes: int, max_train_passes: int, num_slots: int) -> int:
    assert pass_idx >= 1 and total_passes >= 2
    rem = max(0, total_passes - 1 - pass_idx)
    if max_train_passes == 3:
        if pass_idx == 1 and rem == 0:
            return 0
        if pass_idx == 1 and rem >= 1:
            return 1
        return 2
    p_clamped = min(pass_idx, max_train_passes - 1)
    r_clamped = min(rem, max_train_passes - 1 - p_clamped)
    idx = 0
    for p in range(1, p_clamped):
        idx += max_train_passes - p
    return min(idx + r_clamped, num_slots - 1)


try:
    import triton
    import triton.language as tl

    _HAS_TRITON = True
except Exception:
    _HAS_TRITON = False

if _HAS_TRITON:
    @triton.jit
    def _triton_entry_pre_kernel(
        A_ptr, S_ptr, Ws_ptr, Wa_ptr, Gs_tanh_ptr, Pair_ptr, Base_ptr,
        stride_a, stride_s, stride_p, stride_b,
        D: tl.constexpr, BLOCK_D: tl.constexpr, EPS: tl.constexpr,
    ):
        row = tl.program_id(0)
        offs = tl.arange(0, BLOCK_D)
        mask = offs < D
        inv_D = 1.0 / D

        a = tl.load(A_ptr + row * stride_a + offs, mask=mask, other=0.0).to(tl.float32)
        s = tl.load(S_ptr + row * stride_s + offs, mask=mask, other=0.0).to(tl.float32)
        ws = tl.load(Ws_ptr + offs, mask=mask, other=0.0).to(tl.float32)
        wa = tl.load(Wa_ptr + offs, mask=mask, other=0.0).to(tl.float32)
        gs_t = tl.load(Gs_tanh_ptr + offs, mask=mask, other=0.0).to(tl.float32)

        inv_rms_a = tl.rsqrt(tl.sum(a * a, axis=0) * inv_D + EPS)
        rms_a = 1.0 / inv_rms_a
        inv_rms_s = tl.rsqrt(tl.sum(s * s, axis=0) * inv_D + EPS)

        ns = (s * inv_rms_s) * ws
        na = (a * inv_rms_a) * wa
        inv_rms_ns = tl.rsqrt(tl.sum(ns * ns, axis=0) * inv_D + EPS)
        s_hat = ns * (rms_a * inv_rms_ns)
        base = a + gs_t * (s_hat - a)

        tl.store(Pair_ptr + row * stride_p + offs, ns.to(tl.bfloat16), mask=mask)
        tl.store(Pair_ptr + row * stride_p + D + offs, na.to(tl.bfloat16), mask=mask)
        tl.store(Base_ptr + row * stride_b + offs, base.to(tl.bfloat16), mask=mask)

    @triton.jit
    def _triton_mixer_pre_kernel(
        C_ptr, P_ptr, Wc_ptr, Wp_ptr, Pair_ptr,
        stride_c, stride_p, stride_pair,
        D: tl.constexpr, BLOCK_D: tl.constexpr, EPS: tl.constexpr,
    ):
        row = tl.program_id(0)
        offs = tl.arange(0, BLOCK_D)
        mask = offs < D
        inv_D = 1.0 / D

        c = tl.load(C_ptr + row * stride_c + offs, mask=mask, other=0.0).to(tl.float32)
        p = tl.load(P_ptr + row * stride_p + offs, mask=mask, other=0.0).to(tl.float32)
        wc = tl.load(Wc_ptr + offs, mask=mask, other=0.0).to(tl.float32)
        wp = tl.load(Wp_ptr + offs, mask=mask, other=0.0).to(tl.float32)

        inv_rms_c = tl.rsqrt(tl.sum(c * c, axis=0) * inv_D + EPS)
        inv_rms_p = tl.rsqrt(tl.sum(p * p, axis=0) * inv_D + EPS)

        nc = (c * inv_rms_c) * wc
        np_ = (p * inv_rms_p) * wp

        tl.store(Pair_ptr + row * stride_pair + offs, nc.to(tl.bfloat16), mask=mask)
        tl.store(Pair_ptr + row * stride_pair + D + offs, np_.to(tl.bfloat16), mask=mask)

    @triton.jit
    def _triton_loop_cd_kernel(
        F_ptr, R_ptr, Out_ptr,
        stride_f, stride_r, stride_o,
        omega,
        D: tl.constexpr, BLOCK_D: tl.constexpr, EPS: tl.constexpr,
    ):
        row = tl.program_id(0)
        offs = tl.arange(0, BLOCK_D)
        mask = offs < D
        inv_D = 1.0 / D

        mf = tl.load(F_ptr + row * stride_f + offs, mask=mask, other=0.0).to(tl.float32)
        rf = tl.load(R_ptr + row * stride_r + offs, mask=mask, other=0.0).to(tl.float32)
        pushed = mf + omega * (mf - rf)
        rms_mf = tl.sqrt(tl.sum(mf * mf, axis=0) * inv_D + EPS)
        inv_rms_p = tl.rsqrt(tl.sum(pushed * pushed, axis=0) * inv_D + EPS)
        out = pushed * (rms_mf * inv_rms_p)
        tl.store(Out_ptr + row * stride_o + offs, out.to(tl.bfloat16), mask=mask)


def _rms(x: torch.Tensor) -> torch.Tensor:
    return torch.sqrt(torch.mean(x * x, dim=-1, keepdim=True) + ENTRY_EPS)


def _loop_cd_hidden(final: torch.Tensor, ref: torch.Tensor, omega: float) -> torch.Tensor:
    if omega == 0.0:
        return final
    if (
        TRITON_SEAMS
        and _HAS_TRITON
        and final.is_cuda
        and final.dtype == torch.bfloat16
        and ref.dtype == torch.bfloat16
        and final.dim() == 2
        and final.shape == ref.shape
    ):
        M, D = int(final.shape[0]), int(final.shape[1])
        out = torch.empty_like(final)
        block_d = triton.next_power_of_2(D)
        _triton_loop_cd_kernel[(M,)](
            final, ref, out,
            final.stride(0), ref.stride(0), out.stride(0),
            float(omega),
            D=D, BLOCK_D=block_d, EPS=ENTRY_EPS,
            num_warps=8,
        )
        return out
    mf = final.to(torch.float32)
    rf = ref.to(torch.float32)
    pushed = mf + float(omega) * (mf - rf)
    return (pushed * (_rms(mf) / _rms(pushed))).to(final.dtype)


class _LoRAWeights:
    """Immutable FP32 LoRA tensors for CUDA-graph-safe inference."""

    __slots__ = ("A", "B", "slot_scale", "scale", "out_features", "in_features", "is_zero")

    def __init__(self, A: torch.Tensor, B: torch.Tensor, slot_scale: torch.Tensor, alpha: float, rank: int):
        self.A = A.contiguous()
        self.B = B.contiguous()
        self.slot_scale = slot_scale.contiguous()
        self.scale = float(alpha) / float(rank)
        self.in_features = int(A.shape[0])
        self.out_features = int(B.shape[1])
        self.is_zero = bool(torch.count_nonzero(self.B).item() == 0)

    def apply(self, x: torch.Tensor, slot: int) -> torch.Tensor:
        z = torch.matmul(torch.matmul(x.to(torch.float32), self.A), self.B)
        return (z * (self.scale * self.slot_scale[slot])).to(x.dtype)

    def apply_fp32(self, x: torch.Tensor, slot: int) -> torch.Tensor:
        z = torch.matmul(torch.matmul(x.to(torch.float32), self.A), self.B)
        return z * (self.scale * self.slot_scale[slot])


class _LoadedLoopAdapter:
    """Rank-local loaded InklingLoopAdapter weights (FP32 on GPU, zero syncs in forward)."""

    def __init__(self, adapter_dir: str, tp_rank: int, device: torch.device, tp_size: int = 4):
        root = Path(adapter_dir)
        univ_st = root / "adapter_model.safetensors"
        univ_cfg = root / "adapter_config.json"
        pt_path = root / f"adapter_rank{tp_rank}.pt"
        meta_path = root / "meta.json"
        st_path = root / f"adapter_rank{tp_rank}.safetensors"
        manifest_path = root / f"manifest_rank{tp_rank}.json"

        if univ_st.is_file() and univ_cfg.is_file():
            from safetensors.torch import load_file

            meta = json.loads(univ_cfg.read_text())
            actual_sha = hashlib.sha256(univ_st.read_bytes()).hexdigest()
            expected_sha = meta.get("sha256")
            if expected_sha and actual_sha != expected_sha:
                raise RuntimeError(
                    f"loop_depth: SHA-256 mismatch for {univ_st}: expected {expected_sha}, got {actual_sha}"
                )
            full_splits = [int(x) for x in meta.get("qkvr_full_splits", [6144, 1024, 1024, 768, 6144, 48])]
            full_raw = load_file(str(univ_st), device="cpu")
            raw = {}
            for k, t in full_raw.items():
                if "qkvr." in k and k.endswith(".B"):
                    parts = t.split(full_splits, dim=-1)
                    local_parts = []
                    for p in parts:
                        assert p.shape[-1] % tp_size == 0
                        chunk = p.shape[-1] // tp_size
                        local_parts.append(p[..., tp_rank * chunk : (tp_rank + 1) * chunk])
                    sh = torch.cat(local_parts, dim=-1)
                    pad = -sh.shape[-1] % 8
                    if pad:
                        sh = torch.cat([sh, torch.zeros((*sh.shape[:-1], pad), dtype=sh.dtype)], dim=-1)
                    raw[k] = sh.to(device=device)
                elif "wo." in k and k.endswith(".A"):
                    assert t.shape[0] % tp_size == 0
                    chunk = t.shape[0] // tp_size
                    raw[k] = t[tp_rank * chunk : (tp_rank + 1) * chunk].to(device=device)
                else:
                    raw[k] = t.to(device=device)
            weight_path = univ_st
        elif pt_path.is_file() and meta_path.is_file():
            meta = json.loads(meta_path.read_text())
            actual_sha = hashlib.sha256(pt_path.read_bytes()).hexdigest()
            expected_sha = (meta.get("sha256") or {}).get(pt_path.name)
            if expected_sha and actual_sha != expected_sha:
                raise RuntimeError(
                    f"loop_depth: SHA-256 mismatch for {pt_path}: expected {expected_sha}, got {actual_sha}"
                )
            blob = torch.load(str(pt_path), map_location=device, weights_only=True)
            if isinstance(blob, dict) and "state_dict" in blob:
                if int(blob.get("tp_rank", tp_rank)) != tp_rank:
                    raise ValueError(f"loop_depth: ckpt tp_rank={blob.get('tp_rank')} != {tp_rank}")
                raw = blob["state_dict"]
            else:
                raw = blob
            weight_path = pt_path
        elif st_path.is_file() and manifest_path.is_file():
            from safetensors.torch import load_file

            meta = json.loads(manifest_path.read_text())
            if meta.get("format") != "inkling2-loop-v1":
                raise ValueError(f"loop_depth: unsupported format {meta.get('format')!r} in {manifest_path}")
            if int(meta.get("tp_rank", -1)) != tp_rank:
                raise ValueError(f"loop_depth: manifest tp_rank={meta.get('tp_rank')} != {tp_rank}")
            actual_sha = hashlib.sha256(st_path.read_bytes()).hexdigest()
            expected_sha = meta.get("sha256")
            if expected_sha and actual_sha != expected_sha:
                raise RuntimeError(
                    f"loop_depth: SHA-256 mismatch for {st_path}: expected {expected_sha}, got {actual_sha}"
                )
            raw = load_file(str(st_path), device=str(device))
            weight_path = st_path
        else:
            raise FileNotFoundError(
                f"loop_depth: missing adapter shard for rank {tp_rank} in {root} "
                f"(expected adapter_rank{tp_rank}.pt + meta.json or adapter_rank{tp_rank}.safetensors)"
            )

        cfg = meta["config"]
        self.cfg = cfg
        self.step = int(meta.get("step", -1))
        self.core_start = int(cfg.get("core_start", CORE_START))
        self.core_end = int(cfg.get("core_end", CORE_END))
        self.max_train_passes = int(cfg.get("max_train_passes", 3))
        self.num_slots = max(1, (self.max_train_passes * (self.max_train_passes - 1)) // 2)
        if self.core_start != CORE_START or self.core_end != CORE_END:
            raise ValueError(
                f"loop_depth: adapter core [{self.core_start},{self.core_end}) != [{CORE_START},{CORE_END})"
            )

        td = {k: v.to(device=device, dtype=torch.float32).contiguous() for k, v in raw.items()}

        # WorkspaceEntry (plus pre-folded BF16 matrices for fused Triton seam kernel)
        self.e_ws = td["entry.w_s"]
        self.e_wa = td["entry.w_a"]
        self.e_gs = td["entry.gs"]
        self.e_gm = td["entry.gm"]
        self.e_A = td["entry.A"]
        self.e_B = td["entry.B"]
        self.e_gs_tanh = torch.tanh(self.e_gs).contiguous()
        self.e_A_bf16 = self.e_A.to(torch.bfloat16).contiguous()
        self.e_B_scaled_bf16 = [
            (self.e_B * self.e_gm[s].unsqueeze(0)).to(torch.bfloat16).contiguous()
            for s in range(self.num_slots)
        ]
        self.entry_zero = [
            bool(torch.count_nonzero(self.e_gs[s]).item() == 0 and torch.count_nonzero(self.e_gm[s]).item() == 0)
            for s in range(self.num_slots)
        ]

        # Optional CrossPassMixer at L36 (plus pre-folded BF16 matrices)
        self.has_mixer = "mid_mixer.gate" in td
        if self.has_mixer:
            self.m_wprev = td["mid_mixer.w_prev"]
            self.m_wcurr = td["mid_mixer.w_curr"]
            self.m_gate = td["mid_mixer.gate"]
            self.m_A = td["mid_mixer.A"]
            self.m_B = td["mid_mixer.B"]
            self.m_A_bf16 = self.m_A.to(torch.bfloat16).contiguous()
            self.m_B_scaled_bf16 = [
                (self.m_B * torch.tanh(self.m_gate[s]).unsqueeze(0)).to(torch.bfloat16).contiguous()
                for s in range(self.num_slots)
            ]
            self.mixer_zero = [
                bool(torch.count_nonzero(self.m_gate[s]).item() == 0)
                for s in range(self.num_slots)
            ]
        else:
            self.mixer_zero = [True] * self.num_slots

        r_attn = int(cfg.get("lora_rank_attn", 32))
        a_attn = float(cfg.get("lora_alpha_attn", 32.0))
        r_router = int(cfg.get("lora_rank_router", 16))
        a_router = float(cfg.get("lora_alpha_router", 16.0))

        self.core_qkvr: dict[int, _LoRAWeights] = {}
        self.core_wo: dict[int, _LoRAWeights] = {}
        self.core_router: dict[int, _LoRAWeights] = {}
        for lid in range(CORE_START, CORE_END):
            self.core_qkvr[lid] = _LoRAWeights(
                td[f"core_qkvr.{lid}.A"], td[f"core_qkvr.{lid}.B"], td[f"core_qkvr.{lid}.slot_scale"], a_attn, r_attn
            )
            self.core_wo[lid] = _LoRAWeights(
                td[f"core_wo.{lid}.A"], td[f"core_wo.{lid}.B"], td[f"core_wo.{lid}.slot_scale"], a_attn, r_attn
            )
            self.core_router[lid] = _LoRAWeights(
                td[f"core_router.{lid}.A"], td[f"core_router.{lid}.B"], td[f"core_router.{lid}.slot_scale"],
                a_router, r_router,
            )

        self.coda_qkvr: dict[int, _LoRAWeights] = {}
        self.coda_wo: dict[int, _LoRAWeights] = {}
        for lid in range(CORE_END, NUM_PHYSICAL_LAYERS):
            self.coda_qkvr[lid] = _LoRAWeights(
                td[f"coda_qkvr.{lid}.A"], td[f"coda_qkvr.{lid}.B"], td[f"coda_qkvr.{lid}.slot_scale"], a_attn, r_attn
            )
            self.coda_wo[lid] = _LoRAWeights(
                td[f"coda_wo.{lid}.A"], td[f"coda_wo.{lid}.B"], td[f"coda_wo.{lid}.slot_scale"], a_attn, r_attn
            )

        n_params = sum(t.numel() for t in td.values())
        # Pre-compile fused Triton seam kernels before any CUDA graph capture
        if TRITON_SEAMS and _HAS_TRITON and device.type == "cuda":
            D_warm = int(self.e_ws.shape[0])
            dummy_a = torch.ones((1, D_warm), dtype=torch.bfloat16, device=device)
            dummy_s = torch.ones((1, D_warm), dtype=torch.bfloat16, device=device)
            _ = self.apply_entry(dummy_a, dummy_s, 0)
            if self.has_mixer:
                _ = self.apply_mid_mixer(dummy_a, dummy_s, 0)
            _ = _loop_cd_hidden(dummy_a, dummy_s, 0.3)
        log.warning(
            "[loop_depth] rank %d loaded %s (step=%d, %.2fM params, depth=%d, kv_mode=%s, control=%s, omega=%.3f, zero_gates=%s, triton_seams=%s)",
            tp_rank, weight_path, self.step, n_params / 1e6, LOOP_DEPTH, KV_MODE, CONTROL_MODE, CD_OMEGA, ZERO_GATES,
            bool(TRITON_SEAMS and _HAS_TRITON),
        )

    def pass_slot(self, pass_idx: int, total_passes: int) -> int:
        return _pass_slot(pass_idx, total_passes, self.max_train_passes, self.num_slots)

    def apply_entry(self, anchor: torch.Tensor, s: torch.Tensor, slot: int) -> torch.Tensor:
        if ZERO_GATES or self.entry_zero[slot]:
            return anchor
        if (
            TRITON_SEAMS
            and _HAS_TRITON
            and anchor.is_cuda
            and anchor.dtype == torch.bfloat16
            and s.dtype == torch.bfloat16
            and anchor.dim() == 2
            and anchor.shape == s.shape
        ):
            M, D = int(anchor.shape[0]), int(anchor.shape[1])
            pair = torch.empty((M, 2 * D), dtype=torch.bfloat16, device=anchor.device)
            base = torch.empty((M, D), dtype=torch.bfloat16, device=anchor.device)
            block_d = triton.next_power_of_2(D)
            _triton_entry_pre_kernel[(M,)](
                anchor, s, self.e_ws, self.e_wa, self.e_gs_tanh[slot], pair, base,
                anchor.stride(0), s.stride(0), pair.stride(0), base.stride(0),
                D=D, BLOCK_D=block_d, EPS=ENTRY_EPS,
                num_warps=8,
            )
            mid = torch.mm(pair, self.e_A_bf16)
            return torch.addmm(base, mid, self.e_B_scaled_bf16[slot])
        af = anchor.to(torch.float32)
        sf = s.to(torch.float32)
        rms_af = _rms(af)
        rms_sf = _rms(sf)
        ns = (sf / rms_sf) * self.e_ws
        na = (af / rms_af) * self.e_wa
        s_hat = ns * (rms_af / _rms(ns))
        pair = torch.cat((ns, na), dim=-1)
        delta = torch.matmul(torch.matmul(pair, self.e_A), self.e_B)
        out = af + torch.tanh(self.e_gs[slot]) * (s_hat - af) + self.e_gm[slot] * delta
        return out.to(anchor.dtype)

    def apply_mid_mixer(self, curr: torch.Tensor, prev: torch.Tensor, slot: int) -> torch.Tensor:
        if not self.has_mixer or ZERO_GATES or self.mixer_zero[slot]:
            return curr
        if (
            TRITON_SEAMS
            and _HAS_TRITON
            and curr.is_cuda
            and curr.dtype == torch.bfloat16
            and prev.dtype == torch.bfloat16
            and curr.dim() == 2
            and curr.shape == prev.shape
        ):
            M, D = int(curr.shape[0]), int(curr.shape[1])
            pair = torch.empty((M, 2 * D), dtype=torch.bfloat16, device=curr.device)
            block_d = triton.next_power_of_2(D)
            _triton_mixer_pre_kernel[(M,)](
                curr, prev, self.m_wcurr, self.m_wprev, pair,
                curr.stride(0), prev.stride(0), pair.stride(0),
                D=D, BLOCK_D=block_d, EPS=ENTRY_EPS,
                num_warps=8,
            )
            mid = torch.mm(pair, self.m_A_bf16)
            return torch.addmm(curr, mid, self.m_B_scaled_bf16[slot])
        cf = curr.to(torch.float32)
        pf = prev.to(torch.float32)
        nc = (cf / _rms(cf)) * self.m_wcurr
        np_ = (pf / _rms(pf)) * self.m_wprev
        delta = torch.matmul(torch.matmul(torch.cat((nc, np_), dim=-1), self.m_A), self.m_B)
        return (cf + torch.tanh(self.m_gate[slot]) * delta).to(curr.dtype)


class _ActiveLoRAState:
    """Thread-local/main-thread dispatch state mutated only by Inkling2CausalLLM.forward."""

    __slots__ = ("qkvr", "wo", "router", "slot")

    def __init__(self) -> None:
        self.qkvr: _LoRAWeights | None = None
        self.wo: _LoRAWeights | None = None
        self.router: _LoRAWeights | None = None
        self.slot: int = 0

    def clear(self) -> None:
        self.qkvr = None
        self.wo = None
        self.router = None
        self.slot = 0


_ACTIVE = _ActiveLoRAState()


# ---------------------------------------------------------------------------
# 1. Config & KV / Sconv Pool Hooks
# ---------------------------------------------------------------------------

def install_inkling_config(mod: Any) -> None:
    """Expand InklingModelConfig conv_layer_ids (always when T>=2) and full_attention_layer_ids (per_pass only)."""
    if EXTRA_SCONV_LAYERS <= 0:
        return
    cls = mod.InklingModelConfig
    if getattr(cls, "_loop_depth_patched", False):
        return

    stock_conv = cls.conv_layer_ids.fget
    stock_full = cls.full_attention_layer_ids.fget

    @property
    def conv_layer_ids(self) -> list[int]:
        if getattr(self, "num_hidden_layers", 0) == NUM_PHYSICAL_LAYERS:
            return list(range(TOTAL_SCONV_LAYERS))
        return stock_conv(self)

    @property
    def full_attention_layer_ids(self) -> list[int]:
        if EXTRA_KV_LAYERS > 0 and getattr(self, "num_hidden_layers", 0) == NUM_PHYSICAL_LAYERS:
            return list(range(TOTAL_KV_LAYERS))
        return stock_full(self)

    cls.conv_layer_ids = conv_layer_ids
    cls.full_attention_layer_ids = full_attention_layer_ids
    cls._loop_depth_patched = True
    log.warning(
        "[loop_depth] InklingModelConfig armed: kv_mode=%s, kv_layers=0..%d, sconv_layers=0..%d (T=%d)",
        KV_MODE, TOTAL_KV_LAYERS - 1, TOTAL_SCONV_LAYERS - 1, LOOP_DEPTH,
    )


def install_kv_configurator(mod: Any) -> None:
    """In last_loop mode, keep KV at 0..47 while giving Mamba/sconv req pool all 0..TOTAL_SCONV_LAYERS-1."""
    if EXTRA_SCONV_LAYERS <= 0 or KV_MODE != "last_loop":
        return
    cls = mod.KVCacheConfigurator
    if getattr(cls._get_mamba_layer_ids_for_req_pool, "_loop_depth_patched", False):
        return
    stock = cls._get_mamba_layer_ids_for_req_pool

    def _get_mamba_layer_ids_for_req_pool(self) -> list:
        archs = getattr(self.model_config.hf_config, "architectures", None) or ()
        if (
            not self.is_draft_worker
            and "Inkling2ForConditionalGeneration" in archs
            and self.layer_info.start_layer == 0
            and self.layer_info.end_layer == NUM_PHYSICAL_LAYERS
        ):
            layers = list(self.mambaish_config.mamba2_cache_params.layers)
            log.warning(
                "[loop_depth] last_loop KV mode: KV stays 48L (full stock pool!), sconv pool gets %d layers",
                len(layers),
            )
            return layers
        return stock(self)

    _get_mamba_layer_ids_for_req_pool.__wrapped__ = stock
    _get_mamba_layer_ids_for_req_pool._loop_depth_patched = True
    cls._get_mamba_layer_ids_for_req_pool = _get_mamba_layer_ids_for_req_pool


def install_model_config(mod: Any) -> None:
    """Append virtual SWA & Global layer IDs in get_hybrid_layer_ids (per_pass KV mode only)."""
    if EXTRA_KV_LAYERS <= 0:
        return
    if getattr(mod.get_hybrid_layer_ids, "_loop_depth_patched", False):
        return
    stock = mod.get_hybrid_layer_ids

    def get_hybrid_layer_ids(model_architectures, hf_text_config):
        swa_ids, full_ids = stock(model_architectures, hf_text_config)
        is_target_inkling2 = (
            "Inkling2ForConditionalGeneration" in (model_architectures or ())
            and "Inkling2ForConditionalGenerationMTP" not in (model_architectures or ())
            and getattr(hf_text_config, "num_hidden_layers", 0) == NUM_PHYSICAL_LAYERS
        )
        if not is_target_inkling2:
            return swa_ids, full_ids
        swa_out = list(swa_ids)
        full_out = list(full_ids)
        local_set = set(getattr(hf_text_config, "local_layer_ids", LOCAL_LAYER_IDS))
        for p in range(1, LOOP_DEPTH):
            for lid in range(CORE_START, CORE_END):
                vid = virtual_layer_id(p, lid)
                if lid in local_set:
                    swa_out.append(vid)
                else:
                    full_out.append(vid)
        return swa_out, full_out

    get_hybrid_layer_ids.__wrapped__ = stock
    get_hybrid_layer_ids._loop_depth_patched = True
    mod.get_hybrid_layer_ids = get_hybrid_layer_ids


def install_layer_setup(mod: Any) -> None:
    """Expand ModelLayerInfo end_layer & num_effective_layers (per_pass KV mode only)."""
    if EXTRA_KV_LAYERS <= 0:
        return
    if getattr(mod.resolve_layer_indices, "_loop_depth_patched", False):
        return
    stock = mod.resolve_layer_indices

    def resolve_layer_indices(*, model, model_config, is_draft_worker, draft_model_idx=None):
        info = stock(
            model=model,
            model_config=model_config,
            is_draft_worker=is_draft_worker,
            draft_model_idx=draft_model_idx,
        )
        archs = getattr(model_config.hf_config, "architectures", None) or ()
        if (
            not is_draft_worker
            and "Inkling2ForConditionalGeneration" in archs
            and info.start_layer == 0
            and info.end_layer == NUM_PHYSICAL_LAYERS
        ):
            owned = range(info.start_layer, TOTAL_KV_LAYERS)
            swa_ids, full_ids = mod._resolve_local_hybrid_swa_layer_ids(
                model_config=model_config, owned_layers=owned
            )
            log.warning(
                "[loop_depth] ModelLayerInfo expanded (per_pass): 0..%d (swa=%d, full=%d)",
                TOTAL_KV_LAYERS,
                len(swa_ids) if swa_ids is not None else 0,
                len(full_ids) if full_ids is not None else 0,
            )
            return mod.ModelLayerInfo(
                start_layer=info.start_layer,
                end_layer=TOTAL_KV_LAYERS,
                num_effective_layers=TOTAL_KV_LAYERS - info.start_layer,
                swa_attention_layer_ids=swa_ids,
                full_attention_layer_ids=full_ids,
                draft_owns_its_depth=info.draft_owns_its_depth,
            )
        return info

    resolve_layer_indices.__wrapped__ = stock
    resolve_layer_indices._loop_depth_patched = True
    mod.resolve_layer_indices = resolve_layer_indices


def install_nvfp4_kv(mod: Any) -> None:
    """Map virtual global/SWA layer IDs 48..59+ to their physical Core K-smoothing means (per_pass only)."""
    if EXTRA_KV_LAYERS <= 0:
        return
    if getattr(mod.load_means, "_loop_depth_patched", False):
        return
    stock_load = mod.load_means

    def load_means(*args, **kwargs):
        means = stock_load(*args, **kwargs)
        added = 0
        for p in range(1, LOOP_DEPTH):
            for lid in range(CORE_START, CORE_END):
                vid = virtual_layer_id(p, lid)
                if lid in means and vid not in means:
                    means[vid] = means[lid]
                    added += 1
        if added:
            log.warning("[loop_depth] nvfp4_kv K-smoothing aliased for %d virtual layers", added)
        return means

    load_means.__wrapped__ = stock_load
    load_means._loop_depth_patched = True
    mod.load_means = load_means


# ---------------------------------------------------------------------------
# 2. Zero-Overhead Pre-Merged LoRA Builder (DENSE_P12 + Megakernel Router)
# ---------------------------------------------------------------------------

def _merge_linear_module(
    module: Any,
    lora: _LoRAWeights,
    slot: int,
    split_sizes: list[int] | None = None,
    keep_bf16: bool = True,
) -> tuple[Any | None, torch.nn.Parameter | None, int]:
    """Pre-merge LoRA into a linear layer (re-packing into DENSE_P12 if active).

    Returns (q_p12_or_None, weight_param_or_None, extra_bytes).
    When `keep_bf16=False` and `_p12` is active, only the exact 12-bit `_p12` copy is retained
    and marked `freed=True` using dense_p12's shared 49 MB scratch buffer for prefill — saving
    ~540 MB/rank on Pass-1 Core layers while keeping all 48 base layers in zero-unpack BF16!
    """
    with torch.no_grad():
        q_orig = module.__dict__.get("_p12")
        delta_t = (
            torch.matmul(lora.A, lora.B).transpose(0, 1) * (lora.scale * lora.slot_scale[slot])
        )  # [N, K] fp32
        if q_orig is not None:
            import dense_p12

            n, k = q_orig.a.shape
            if q_orig.freed:
                w_bf16 = torch.empty((n, k), dtype=torch.bfloat16, device=q_orig.a.device)
                dense_p12.unpack_into(q_orig, w_bf16)
            else:
                w_bf16 = module.weight.data
            w_merged = (w_bf16.to(torch.float32) + delta_t).to(torch.bfloat16).contiguous()
            del delta_t
            if q_orig.freed:
                del w_bf16
            q_new = dense_p12.pack(w_merged)
            if split_sizes is not None and q_orig.by_source is not None and sum(split_sizes) == n:
                ranges, at = [], 0
                for idx, sz in enumerate(split_sizes):
                    ranges.append((at, at + sz, idx if idx in (1, 2) else 0))
                    at += sz
                q_new.set_sources(ranges)
            if q_new.slots > dense_p12.MAX_SLOTS:
                log.warning(
                    "[loop_depth] merged P12 exceeded MAX_SLOTS (%d > %d), keeping BF16 fallback",
                    q_new.slots, dense_p12.MAX_SLOTS,
                )
                del q_new
                p = torch.nn.Parameter(w_merged, requires_grad=False)
                return None, p, w_merged.numel() * 2
            if q_orig.freed or not keep_bf16:
                q_new.freed = True
                q_new.scratch = q_orig.scratch if q_orig.scratch is not None else dense_p12._scratch((n, k), q_orig.a.device)
                del w_merged
                return q_new, None, q_new.nbytes()
            p = torch.nn.Parameter(w_merged, requires_grad=False)
            return q_new, p, q_new.nbytes() + w_merged.numel() * 2

        w_merged = (module.weight.data.to(torch.float32) + delta_t).to(torch.bfloat16).contiguous()
        del delta_t
        p = torch.nn.Parameter(w_merged, requires_grad=False)
        return None, p, w_merged.numel() * 2


def _merge_inplace(module: Any, lora: _LoRAWeights, slot: int, split_sizes: list[int] | None = None) -> None:
    """Fold LoRA permanently into a module that ALWAYS runs with that LoRA (Coda, or Control mode)."""
    if lora.is_zero:
        return
    q_new, p_new, _ = _merge_linear_module(module, lora, slot, split_sizes=split_sizes)
    if q_new is not None:
        module._p12 = q_new
        if p_new is not None:
            module.weight.data.copy_(p_new.data)
            del p_new
    elif p_new is not None:
        # Remove _p12 if fallback to BF16 occurred
        if "_p12" in module.__dict__:
            del module.__dict__["_p12"]
        module.weight.data = p_new.data


def _build_fused_weights(llm: Any, adapter: _LoadedLoopAdapter) -> dict[str, Any]:
    """Fold CodaLoRA in-place (0 MB, 0 ms) and pre-merge CoreLoRA Pass weights (~0.48 GB/rank, 0 ms)."""
    fused: dict[str, Any] = {"core_slots": {}, "orig_core": {}, "bytes": 0}
    if not CONTROL_MODE and LOOP_DEPTH <= 1:
        return fused

    with torch.no_grad():
        # 1. Coda (L42..47): ALWAYS runs once with slot=0 -> fold in-place (0 extra VRAM, 0 runtime cost!)
        for lid in range(CORE_END, NUM_PHYSICAL_LAYERS):
            layer = llm.layers[lid]
            _merge_inplace(layer.attn.qkvr, adapter.coda_qkvr[lid], 0, split_sizes=layer.attn.split_sizes)
            _merge_inplace(layer.attn.wo_ud, adapter.coda_wo[lid], 0)

        # 2. Control mode: Core (L30..41) also runs once with slot=0 -> fold ALL Core weights in-place!
        if CONTROL_MODE:
            for lid in range(CORE_START, CORE_END):
                layer = llm.layers[lid]
                _merge_inplace(layer.attn.qkvr, adapter.core_qkvr[lid], 0, split_sizes=layer.attn.split_sizes)
                _merge_inplace(layer.attn.wo_ud, adapter.core_wo[lid], 0)
                if not adapter.core_router[lid].is_zero:
                    r_lora = adapter.core_router[lid]
                    delta_t = (
                        torch.matmul(r_lora.A, r_lora.B).transpose(0, 1) * (r_lora.scale * r_lora.slot_scale[0])
                    )
                    layer.mlp.gate.weight.data.copy_(
                        (layer.mlp.gate.weight.data.to(torch.float32) + delta_t).to(torch.bfloat16)
                    )
                    del delta_t
            torch.cuda.empty_cache()
            log.warning("[loop_depth] CONTROL mode: folded all 18 Core+Coda LoRAs in-place (0 MB extra, 0 ms overhead)")
            return fused

        # 3. Looped mode (T >= 2): pre-merge Core (L30..41) for every distinct active pass slot
        active_slots = sorted({adapter.pass_slot(p, LOOP_DEPTH) for p in range(1, LOOP_DEPTH)})
        total_bytes = 0
        for lid in range(CORE_START, CORE_END):
            layer = llm.layers[lid]
            qkvr = layer.attn.qkvr
            wo = layer.attn.wo_ud
            gate = layer.mlp.gate
            fused["orig_core"][lid] = (
                qkvr.__dict__.get("_p12"),
                qkvr._parameters["weight"],
                wo.__dict__.get("_p12"),
                wo._parameters["weight"],
                gate._parameters["weight"],
            )
            for slot in active_slots:
                q_qkvr, p_qkvr, b1 = _merge_linear_module(
                    qkvr, adapter.core_qkvr[lid], slot, split_sizes=layer.attn.split_sizes, keep_bf16=False
                )
                q_wo, p_wo, b2 = _merge_linear_module(wo, adapter.core_wo[lid], slot, keep_bf16=False)
                r_lora = adapter.core_router[lid]
                if not r_lora.is_zero:
                    delta_t = (
                        torch.matmul(r_lora.A, r_lora.B).transpose(0, 1) * (r_lora.scale * r_lora.slot_scale[slot])
                    )
                    w_gate = (gate.weight.data.to(torch.float32) + delta_t).to(torch.bfloat16).contiguous()
                    del delta_t
                    p_gate = torch.nn.Parameter(w_gate, requires_grad=False)
                    b3 = w_gate.numel() * 2
                else:
                    p_gate = gate._parameters["weight"]
                    b3 = 0
                fused["core_slots"][(lid, slot)] = (q_qkvr, p_qkvr, q_wo, p_wo, p_gate)
                total_bytes += b1 + b2 + b3
        fused["bytes"] = total_bytes
        # Drop raw LoRA A/B tensors now that all active slots are pre-merged into P12 + megakernel weights
        adapter.core_qkvr.clear()
        adapter.core_wo.clear()
        adapter.core_router.clear()
        adapter.coda_qkvr.clear()
        adapter.coda_wo.clear()
        torch.cuda.empty_cache()
        log.warning(
            "[loop_depth] pre-merged Coda in-place + %d Core slots into DENSE_P12 & megakernel router "
            "(%.1f MB/rank, 0 runtime LoRA kernels!)",
            len(active_slots), total_bytes / 1e6,
        )
    return fused


# ---------------------------------------------------------------------------
# 3. Model Forward & LoRA Runtime Hooks (installed after weights load)
# ---------------------------------------------------------------------------

def _attach_runtime_hooks(llm: Any, adapter: _LoadedLoopAdapter) -> None:
    """Wrap model forward and either pre-merge LoRAs (FUSE_LORA=1) or attach Python LoRA hooks."""
    from sglang.kernels.ops.inkling2.route import route_topk
    from sglang.srt.models.inkling_common import inkling2_attn as attn_mod
    from sglang.srt.models.inkling_common.inkling2_attn_res import Inkling2AttnResState

    # Validate adapter dims against actual model layers before hooking anything
    for lid in range(CORE_START, NUM_PHYSICAL_LAYERS):
        layer = llm.layers[lid]
        qkvr_out = sum(layer.attn.split_sizes)
        wo_in = layer.attn.head_dim * layer.attn.num_tp_heads
        if lid < CORE_END:
            assert adapter.core_qkvr[lid].out_features == qkvr_out, (
                f"L{lid} core_qkvr out mismatch: {adapter.core_qkvr[lid].out_features} != {qkvr_out}"
            )
            assert adapter.core_wo[lid].in_features == wo_in, (
                f"L{lid} core_wo in mismatch: {adapter.core_wo[lid].in_features} != {wo_in}"
            )
        else:
            assert adapter.coda_qkvr[lid].out_features == qkvr_out, (
                f"L{lid} coda_qkvr out mismatch: {adapter.coda_qkvr[lid].out_features} != {qkvr_out}"
            )
            assert adapter.coda_wo[lid].in_features == wo_in, (
                f"L{lid} coda_wo in mismatch: {adapter.coda_wo[lid].in_features} != {wo_in}"
            )

    fused = _build_fused_weights(llm, adapter) if FUSE_LORA else None
    if FUSE_LORA and CONTROL_MODE:
        # All 18 layers folded permanently in-place; stock Inkling2CausalLLM.forward runs untouched!
        return

    if not FUSE_LORA:
        # Unfused Python LoRA fallback hooks (SPARK_LOOP_FUSE_LORA=0)
        attn_cls = attn_mod.Inkling2Attention
        if not getattr(attn_cls._project_sources, "_loop_depth_patched", False):
            prev_project_sources = attn_cls._project_sources

            def _project_sources_with_lora(self, sources):
                q, k, v, r, gate, sinks = prev_project_sources(self, sources)
                lora = _ACTIVE.qkvr
                if lora is None or lora.is_zero:
                    return q, k, v, r, gate, sinks
                slot = _ACTIVE.slot
                if len({id(sources.q), id(sources.k), id(sources.v)}) == 3:
                    stacked = attn_mod._stacked(sources)
                    dq_p, dk_p, dv_p = (
                        chunk.split(self.split_sizes, dim=-1)[:6]
                        for chunk in lora.apply(stacked, slot).chunk(3)
                    )
                    q.add_(dq_p[0])
                    k.add_(dk_p[1])
                    v.add_(dv_p[2])
                    r.add_(dq_p[3])
                    gate.add_(dq_p[4])
                    sinks.add_(dq_p[5])
                    return q, k, v, r, gate, sinks
                dq_p = lora.apply(sources.q, slot).split(self.split_sizes, dim=-1)[:6]
                dk_p = dq_p if sources.k is sources.q else lora.apply(sources.k, slot).split(self.split_sizes, dim=-1)[:6]
                dv_p = (
                    dq_p if sources.v is sources.q
                    else dk_p if sources.v is sources.k
                    else lora.apply(sources.v, slot).split(self.split_sizes, dim=-1)[:6]
                )
                q.add_(dq_p[0])
                k.add_(dk_p[1])
                v.add_(dv_p[2])
                r.add_(dq_p[3])
                gate.add_(dq_p[4])
                sinks.add_(dq_p[5])
                return q, k, v, r, gate, sinks

            _project_sources_with_lora.__wrapped__ = prev_project_sources
            _project_sources_with_lora._loop_depth_patched = True
            attn_cls._project_sources = _project_sources_with_lora

        for lid in range(CORE_START, NUM_PHYSICAL_LAYERS):
            wo = llm.layers[lid].attn.wo_ud
            if not getattr(wo.forward, "_loop_depth_patched", False):
                prev_wo_fwd = wo.forward

                def _make_wo_wrapper(orig_fn):
                    def _wo_fwd(input_, *args, **kwargs):
                        out, bias = orig_fn(input_, *args, **kwargs)
                        lora = _ACTIVE.wo
                        if lora is not None and not lora.is_zero:
                            delta = lora.apply(input_, _ACTIVE.slot)
                            out_buf = kwargs.get("output_tensor")
                            if out_buf is None and len(args) >= 1:
                                out_buf = args[0]
                            if out_buf is not None:
                                out_buf.add_(delta)
                                out = out_buf
                            else:
                                out = out + delta
                        return out, bias
                    _wo_fwd.__wrapped__ = orig_fn
                    _wo_fwd._loop_depth_patched = True
                    return _wo_fwd

                wo.forward = _make_wo_wrapper(prev_wo_fwd)

        for lid in range(CORE_START, CORE_END):
            gate = llm.layers[lid].mlp.gate
            if not getattr(gate.forward, "_loop_depth_patched", False):
                prev_gate_fwd = gate.forward

                def _make_gate_wrapper(gate_mod, orig_fn):
                    def _gate_fwd(x):
                        lora = _ACTIVE.router
                        if lora is None or lora.is_zero:
                            return orig_fn(x)
                        logits = F.linear(x.to(gate_mod.weight.dtype), gate_mod.weight).to(torch.float32)
                        logits = logits + lora.apply_fp32(x, _ACTIVE.slot)
                        partials = logits.unsqueeze(0)
                        _, ids, weights = route_topk(
                            partials, gate_mod.bias, gate_mod.topk, gate_mod.route_scale, gate_mod._one
                        )
                        return weights, ids
                    _gate_fwd.__wrapped__ = orig_fn
                    _gate_fwd._loop_depth_patched = True
                    return _gate_fwd

                gate.forward = _make_gate_wrapper(gate, prev_gate_fwd)

    # Pre-cache stateful submodule tuples for L30..41 so virtual layer_id swaps are zero-allocation.
    # In last_loop mode, ONLY sconv submodules swap to virtual IDs (preventing double-shift conv corruption),
    # while RadixAttention (attn / attn_padded) stays on physical lid 30..41 so the final loop overwrites KV!
    stateful_submods: dict[int, tuple[Any, ...]] = {}
    for lid in range(CORE_START, CORE_END):
        layer = llm.layers[lid]
        subs = [
            layer.attn.k_sconv,
            layer.attn.v_sconv,
            layer.attn_sconv,
            layer.mlp_sconv,
        ]
        if KV_MODE == "per_pass":
            subs.append(layer.attn.attn)
            if layer.attn.attn_padded is not None:
                subs.append(layer.attn.attn_padded)
        stateful_submods[lid] = tuple(subs)

    # Hook (D): Inkling2CausalLLM.forward loop driver
    if getattr(llm.forward, "_loop_depth_patched", False):
        return
    from sglang.srt.layers.aux_hidden_states import AuxHiddenStatePacker
    from sglang.srt.models import inkling2 as inkling2_mod

    mega = sys.modules.get("megakernel")
    has_mega_glue = (
        mega is not None
        and getattr(mega, "enabled", lambda _: False)("glue")
        and getattr(mega, "get_lib", lambda: None)() is not None
        and hasattr(mega, "post_attn_glue")
        and hasattr(mega, "post_moe_glue")
    )
    if has_mega_glue:
        log.warning("[loop_depth] megakernel layer_glue integrated into looped forward (58/60 layers fused!)")

    # Eagerly pre-warm ALL Triton prefill_glue binaries (both rows%16==0 AND rows%16!=0) at boot while GPU is idle,
    # preventing GB10 CUDA driver `cuModuleLoadData` ("operation not permitted") crashes on odd remainder chunks!
    try:
        import fused_stream as _fs
        import fused_epilogue as _fe

        _dev = llm.embed_tokens.weight.device
        _d = int(llm.embed_tokens.weight.shape[1])
        with torch.no_grad():
            for _toks in (16, 17):
                _b = torch.zeros((_toks, _d), dtype=torch.bfloat16, device=_dev)
                _w = torch.ones((_d,), dtype=torch.bfloat16, device=_dev)
                _q1 = torch.zeros((1, _d), dtype=torch.float32, device=_dev)
                _q3 = torch.zeros((3, _d), dtype=torch.float32, device=_dev)
                for _n in range(1, 10):
                    _blks = [_b] * _n
                    _fs.fused_attn_res_norm(_blks, None, _q1, (_w,), 1e-6)
                    _fs.fused_attn_res_norm(_blks, _b, _q1, (_w,), 1e-6)
                    if _n in (2, 3, 4, 5, 6, 7, 8, 9):
                        _fs.fused_attn_res_norm(_blks, None, _q3, (_w, _w, _w), 1e-6)
                _cw = torch.zeros((_d, 4), dtype=torch.bfloat16, device=_dev)
                _cc = torch.zeros((2, 3, _d), dtype=torch.bfloat16, device=_dev)
                _meta = {
                    "safe_idx": torch.zeros((1,), dtype=torch.int32, device=_dev),
                    "cache_mask": torch.zeros((1,), dtype=torch.bool, device=_dev),
                    "cu": torch.tensor([0, _toks], dtype=torch.int32, device=_dev),
                    "si": torch.zeros((_toks,), dtype=torch.int32, device=_dev),
                }
                _fe.fused_epilogue(_b, _cw, _cc, _meta, _b, None)
                _fe.fused_epilogue(_b, _cw, _cc, _meta, _b, _b)
            torch.cuda.synchronize(_dev)
        log.warning("[loop_depth] pre-warmed fused_stream + fused_epilogue Triton binaries (rows=16 & 17)")
    except Exception as _exc:
        log.warning("[loop_depth] prefill_glue warmup skipped: %s", _exc)

    sg = sys.modules.get("spark_gate")
    has_spark_gate_mask = (
        sg is not None
        and "mask" in getattr(sg, "PARTS", ())
        and hasattr(sg, "_s")
    )
    if has_spark_gate_mask:
        log.warning(
            "[loop_depth] spark_gate row-masking + roce_live (%s) integrated into looped forward!",
            getattr(sg, "_LIVE", None) is not None,
        )

    orig_llm_forward = llm.forward

    def _run_layer_glued_body(
        i: int,
        layer: Any,
        state: Any,
        attn_input: Any,
        positions: torch.Tensor,
        forward_batch: Any,
        *,
        next_layer: Any,
        is_last: bool,
        is_decode: bool,
        is_verify: bool,
        routed: bool,
        final_norm_ok: bool,
        tokens: int,
        D: int,
    ) -> tuple[Any, torch.Tensor | None]:
        """Execute one Inkling2DecoderLayer with megakernel post_attn_glue + post_moe_glue."""
        if attn_input is None:
            streams = state.attention_input(layer.layer_id)
            if layer.is_local:
                attn_input = layer.attn_norm(streams[0])
            else:
                stacked = streams[0].new_empty(
                    (3, *streams[0].shape),
                    dtype=layer.q_input_norm.output_dtype or streams[0].dtype,
                )
                attn_input = inkling2_mod.AttentionSources(
                    layer.q_input_norm(streams[0], out=stacked[0]),
                    layer.k_input_norm(streams[1], out=stacked[1]),
                    layer.v_input_norm(streams[2], out=stacked[2]),
                )

        attention = layer.attn(attn_input, positions, forward_batch)
        is_boundary = llm.attn_res.is_block_boundary(i)

        # ---- Post-Attn Glue: attn_sconv + attn_res(mlp_input) + mlp_norm ----
        meta_a = layer.attn_sconv._conv_state(forward_batch)
        cache_a = layer.attn_sconv._sconv_cache()
        pre_a = meta_a.precomputed
        win_a = layer.attn_sconv._intermediate_window() if is_verify else None

        if mega._check_sconv_runtime(cache_a, pre_a, win_a, is_decode):
            w_a = layer.attn_sconv.weight.squeeze(1)
            srcs = [*state.blocks, state.partial]
            attn_conv, mlp_input = mega.post_attn_glue(
                attention,
                w_a,
                cache_a,
                pre_a["safe_idx"],
                pre_a["cache_mask"],
                srcs,
                is_boundary,
                llm.attn_res.scaled_query("mlp", i),
                layer.mlp_norm.weight,
                verify_window=win_a,
                cu_seqlens=pre_a.get("cu"),
                seq_idx=pre_a.get("si"),
                track_mask=forward_batch.mamba_track_mask if is_decode else None,
                track_indices=meta_a.track_cache_indices if is_decode else None,
                is_decode=is_decode,
                sconv_scale=mega.STATIC_SCONV_SCALE,
                rms_eps=mega._norm_eps(layer.mlp_norm),
            )
        else:
            attn_conv = layer.attn_sconv(attention, positions, forward_batch)
            mlp_input = layer.mlp_norm(state.mlp_input(i, attn_conv))

        # ---- MoE MLP ----
        mlp = layer.mlp(mlp_input, forward_batch, combine=not routed)
        mlp_tensor = None
        if isinstance(mlp, inkling2_mod.RoutedOutput):
            if (
                mlp.top_k in (0, 1)
                and isinstance(mlp.rows, torch.Tensor)
                and mlp.rows.shape == (tokens, D)
                and mlp.rows.dtype in (torch.float32, torch.bfloat16)
            ):
                mlp_tensor = mlp.rows
        elif isinstance(mlp, torch.Tensor) and mlp.shape == (tokens, D) and mlp.dtype in (torch.float32, torch.bfloat16):
            mlp_tensor = mlp

        # ---- Post-MoE Glue (only when next_layer is direct successor or final output layer) ----
        meta_m = layer.mlp_sconv._conv_state(forward_batch)
        cache_m = layer.mlp_sconv._sconv_cache()
        pre_m = meta_m.precomputed
        win_m = layer.mlp_sconv._intermediate_window() if is_verify else None

        can_post_moe = (
            (next_layer is not None or is_last)
            and mlp_tensor is not None
            and mega._check_sconv_runtime(cache_m, pre_m, win_m, is_decode)
            and (not is_last or final_norm_ok)
        )
        if can_post_moe:
            old_partial = state.partial
            if is_boundary:
                state.blocks.append(old_partial)
            if not is_last:
                nxt = next_layer
                next_res_q = llm.attn_res.scaled_query("attn", nxt.layer_id)
                if nxt.is_local:
                    next_norm_ws = (nxt.attn_norm.weight,)
                    next_eps = mega._norm_eps(nxt.attn_norm)
                else:
                    next_norm_ws = (nxt.q_input_norm.weight, nxt.k_input_norm.weight, nxt.v_input_norm.weight)
                    next_eps = mega._norm_eps(nxt.q_input_norm)
            else:
                nxt = None
                next_res_q = llm.attn_res.scaled_query("output", 0)
                next_norm_ws = (llm.norm.weight,)
                next_eps = mega._norm_eps(llm.norm)

            w_m = layer.mlp_sconv.weight.squeeze(1)
            new_partial, next_norm_out = mega.post_moe_glue(
                mlp_tensor,
                attn_conv,
                old_partial,
                w_m,
                cache_m,
                pre_m["safe_idx"],
                pre_m["cache_mask"],
                state.blocks,
                is_boundary,
                next_res_q,
                next_norm_ws,
                verify_window=win_m,
                cu_seqlens=pre_m.get("cu"),
                seq_idx=pre_m.get("si"),
                track_mask=forward_batch.mamba_track_mask if is_decode else None,
                track_indices=meta_m.track_cache_indices if is_decode else None,
                is_decode=is_decode,
                sconv_scale=mega.STATIC_SCONV_SCALE,
                rms_eps=next_eps,
            )
            state.partial = new_partial
            if nxt is not None:
                next_attn_in = (
                    next_norm_out[0]
                    if nxt.is_local
                    else inkling2_mod.AttentionSources(next_norm_out[0], next_norm_out[1], next_norm_out[2])
                )
                return next_attn_in, None
            return None, next_norm_out[0]

        # Seam layer (e.g. L41 before WorkspaceEntry/LoopCD, or L35 before CrossPassMixer): finalize cleanly
        if isinstance(mlp, torch.Tensor):
            mlp = inkling2_mod.RoutedOutput(mlp, None, 0)
        if isinstance(mlp, inkling2_mod.RoutedOutput):
            state.finalize_layer_with(
                i,
                lambda partial, _m=mlp, _a=attn_conv, _l=layer: _l.mlp_sconv.routed_decode_epilogue(
                    _m, _a, partial, forward_batch
                ),
            )
        else:
            mlp_out = layer.mlp_sconv(mlp, positions, forward_batch)
            state.finalize_layer(i, attn_conv, mlp_out)
        return None, None

    def _run_layer_fused(
        lid: int,
        layer: Any,
        state: Any,
        positions: torch.Tensor,
        forward_batch: Any,
        *,
        slot: int,
        vid: int,
        glued_ctx: dict[str, Any] | None = None,
        attn_input: Any = None,
        next_layer: Any = None,
    ) -> tuple[Any, torch.Tensor | None]:
        q_qkvr, p_qkvr, q_wo, p_wo, p_gate = fused["core_slots"][(lid, slot)]
        oq_qkvr, op_qkvr, oq_wo, op_wo, op_gate = fused["orig_core"][lid]
        qkvr = layer.attn.qkvr
        wo = layer.attn.wo_ud
        gate = layer.mlp.gate
        subs = stateful_submods[lid]

        if q_qkvr is not None:
            qkvr._p12 = q_qkvr
        elif "_p12" in qkvr.__dict__:
            del qkvr.__dict__["_p12"]
        if p_qkvr is not None:
            qkvr._parameters["weight"] = p_qkvr

        if q_wo is not None:
            wo._p12 = q_wo
        elif "_p12" in wo.__dict__:
            del wo.__dict__["_p12"]
        if p_wo is not None:
            wo._parameters["weight"] = p_wo

        gate._parameters["weight"] = p_gate
        for m in subs:
            m.layer_id = vid
        try:
            if glued_ctx is not None:
                return _run_layer_glued_body(
                    lid, layer, state, attn_input, positions, forward_batch,
                    next_layer=next_layer, is_last=False, **glued_ctx,
                )
            layer(state, positions, forward_batch)
            return None, None
        finally:
            for m in subs:
                m.layer_id = lid
            if oq_qkvr is not None:
                qkvr._p12 = oq_qkvr
            elif "_p12" in qkvr.__dict__:
                del qkvr.__dict__["_p12"]
            qkvr._parameters["weight"] = op_qkvr
            if oq_wo is not None:
                wo._p12 = oq_wo
            elif "_p12" in wo.__dict__:
                del wo.__dict__["_p12"]
            wo._parameters["weight"] = op_wo
            gate._parameters["weight"] = op_gate

    def _run_layer_with_lora(
        lid: int,
        layer: Any,
        state: Any,
        positions: torch.Tensor,
        forward_batch: Any,
        *,
        qkvr: _LoRAWeights | None,
        wo: _LoRAWeights | None,
        router: _LoRAWeights | None,
        slot: int,
        vid: int | None,
    ) -> None:
        _ACTIVE.qkvr = qkvr
        _ACTIVE.wo = wo
        _ACTIVE.router = router
        _ACTIVE.slot = slot
        subs = stateful_submods[lid] if vid is not None else None
        if subs is not None:
            for m in subs:
                m.layer_id = vid
        try:
            layer(state, positions, forward_batch)
        finally:
            if subs is not None:
                for m in subs:
                    m.layer_id = lid
            _ACTIVE.clear()

    def _loop_llm_forward(input_ids, positions, forward_batch, input_embeds=None):
        # Fast exact stock path when T == 1 and not control_mode
        if not CONTROL_MODE and LOOP_DEPTH <= 1:
            return orig_llm_forward(input_ids, positions, forward_batch, input_embeds=input_embeds)

        # Preserve spark_gate verify-row masking (_s["src"]) + roce_live (_LIVE.begin/end)
        # across all 60 layers (Prelude + Pass 0 + Pass 1..T-1 + Coda)!
        gate_active = False
        if has_spark_gate_mask:
            ep = sg._s.get("epilogue")
            rows = input_ids.shape[0] if input_ids is not None else -1
            if (
                ep is not None
                and rows >= 0
                and forward_batch.forward_mode.is_target_verify()
                and forward_batch.batch_size <= ep.max_bs
                and rows == forward_batch.batch_size * ep.stride
            ):
                index = sg._s["index"].get(rows)
                if index is None:
                    row = torch.arange(rows, device=input_ids.device)
                    index = sg._s["index"][rows] = (row, row % ep.stride, row // ep.stride, row - row % ep.stride)
                row, pos, req, anchor = index
                k = ep.verify_lens_buf.index_select(0, req)
                live = (pos < k) | (k == 0)
                sg._s["src"] = torch.where(live, row, anchor)
                if sg._LIVE is not None:
                    sg._LIVE.begin(live)
                gate_active = True

        try:
            return _loop_llm_forward_inner(input_ids, positions, forward_batch, input_embeds=input_embeds)
        finally:
            if gate_active:
                sg._s["src"] = None
                if sg._LIVE is not None:
                    sg._LIVE.end()

    def _loop_llm_forward_inner(input_ids, positions, forward_batch, input_embeds=None):
        hidden = (
            llm.get_input_embeddings()(input_ids)
            if input_embeds is None
            else input_embeds
        )
        captures = (
            AuxHiddenStatePacker.for_batch(forward_batch, len(llm.layers_to_capture))
            if llm.layers_to_capture
            else None
        )
        if hidden.shape[0] == 0:
            if captures is not None:
                for _ in llm.layers_to_capture:
                    captures.append(hidden.to(llm.lm_head.weight.dtype))
                return hidden, captures.finalize()
            return hidden

        capture_set = set(llm.layers_to_capture) if captures is not None else ()
        cap_dtype = llm.lm_head.weight.dtype if captures is not None else None

        # Decide whether to use megakernel layer_glue (decode & verify, M <= 64, fused LoRAs)
        mode = forward_batch.forward_mode
        is_decode = bool(mode.is_decode())
        is_verify = bool(mode.is_target_verify())
        tokens, D = int(hidden.shape[0]), int(hidden.shape[1])
        use_glue = (
            has_mega_glue
            and fused is not None
            and not CONTROL_MODE
            and (is_decode or is_verify)
            and hidden.is_cuda
            and hidden.dtype == torch.bfloat16
            and hidden.dim() == 2
            and 0 < tokens <= mega.MAX_DECODE_TOKENS
            and D % 16 == 0
            and mega._check_glue_model_compat(llm)
        )
        if use_glue:
            if getattr(llm.attn_res, "_scaled_queries", None) is None:
                if torch.cuda.is_current_stream_capturing():
                    use_glue = False
                else:
                    llm.attn_res.scale_queries()
        if use_glue and not hidden.is_contiguous():
            hidden = hidden.contiguous()

        glued_ctx = None
        if use_glue:
            verify_routed_max = getattr(inkling2_mod, "VERIFY_ROUTED_EPILOGUE_MAX_TOKENS", 32)
            glued_ctx = {
                "is_decode": is_decode,
                "is_verify": is_verify,
                "routed": is_decode or (is_verify and tokens <= verify_routed_max),
                "final_norm_ok": (
                    getattr(llm.norm, "pre_weight", None) is None
                    and llm.norm.weight is not None
                    and llm.norm.weight.dtype == torch.bfloat16
                    and getattr(llm.norm, "output_dtype", None) in (None, torch.bfloat16)
                ),
                "tokens": tokens,
                "D": D,
            }

        state = Inkling2AttnResState(llm.attn_res, hidden)
        attn_input = None
        final_hidden = None

        # 1. Frozen Prelude (L0..29)
        _ACTIVE.clear()
        for i in range(CORE_START):
            if captures is not None and i in capture_set:
                captures.append(state.partial.to(cap_dtype))
            if glued_ctx is not None:
                attn_input, _ = _run_layer_glued_body(
                    i, llm.layers[i], state, attn_input, positions, forward_batch,
                    next_layer=llm.layers[i + 1], is_last=False, **glued_ctx,
                )
            else:
                llm.layers[i](state, positions, forward_batch)

        # 2. Control mode (unfused fallback; fused control returns early in _attach_runtime_hooks)
        if CONTROL_MODE:
            for i in range(CORE_START, CORE_END):
                if captures is not None and i in capture_set:
                    captures.append(state.partial.to(cap_dtype))
                _run_layer_with_lora(
                    i, llm.layers[i], state, positions, forward_batch,
                    qkvr=adapter.core_qkvr[i], wo=adapter.core_wo[i], router=adapter.core_router[i],
                    slot=0, vid=None,
                )
            for i in range(CORE_END, NUM_PHYSICAL_LAYERS):
                if captures is not None and i in capture_set:
                    captures.append(state.partial.to(cap_dtype))
                _run_layer_with_lora(
                    i, llm.layers[i], state, positions, forward_batch,
                    qkvr=adapter.coda_qkvr[i], wo=adapter.coda_wo[i], router=None,
                    slot=0, vid=None,
                )
            hidden = llm.norm(state.compute_output())
            if captures is not None:
                captures.append(hidden.to(cap_dtype))
                return hidden, captures.finalize()
            return hidden

        # 3. Recurrent Loop mode (T >= 2)
        prelude_blocks = list(state.blocks)
        anchor_partial = state.partial

        # Pass 0: Frozen Core (L30..41), physical layer IDs 30..41 (no captures yet; capture on final pass!)
        mid_prev = None
        for i in range(CORE_START, CORE_END):
            if i == MID_CORE_LAYER:
                mid_prev = state.partial
            if glued_ctx is not None:
                nxt = llm.layers[i + 1] if i < CORE_END - 1 else None
                attn_input, _ = _run_layer_glued_body(
                    i, llm.layers[i], state, attn_input, positions, forward_batch,
                    next_layer=nxt, is_last=False, **glued_ctx,
                )
            else:
                llm.layers[i](state, positions, forward_batch)
        s_first = state.partial
        s_prev = s_first

        # Passes p = 1 .. T - 1: WorkspaceEntry + CoreLoRA + CrossPassMixer + virtual sconv (and optional virtual KV)
        for p_idx in range(1, LOOP_DEPTH):
            slot = adapter.pass_slot(p_idx, LOOP_DEPTH)
            entry_partial = adapter.apply_entry(anchor_partial, s_prev, slot)
            state = Inkling2AttnResState(llm.attn_res, entry_partial, list(prelude_blocks))
            attn_input = None
            next_mid_prev = None
            is_final_pass = (p_idx == LOOP_DEPTH - 1)
            for i in range(CORE_START, CORE_END):
                if i == MID_CORE_LAYER:
                    next_mid_prev = state.partial
                    if mid_prev is not None:
                        state.partial = adapter.apply_mid_mixer(state.partial, mid_prev, slot)
                        attn_input = None
                if is_final_pass and captures is not None and i in capture_set:
                    captures.append(state.partial.to(cap_dtype))
                vid = virtual_layer_id(p_idx, i)
                if fused is not None:
                    if glued_ctx is not None:
                        # Fuse into next layer except right before CrossPassMixer (L35) or loop/CD seam (L41)
                        if i == MID_CORE_LAYER - 1 and adapter.has_mixer and not ZERO_GATES:
                            nxt = None
                        elif i < CORE_END - 1:
                            nxt = llm.layers[i + 1]
                        elif is_final_pass and CD_OMEGA == 0.0:
                            nxt = llm.layers[CORE_END]
                        else:
                            nxt = None
                    else:
                        nxt = None
                    attn_input, _ = _run_layer_fused(
                        i, llm.layers[i], state, positions, forward_batch,
                        slot=slot, vid=vid, glued_ctx=glued_ctx, attn_input=attn_input, next_layer=nxt,
                    )
                else:
                    _run_layer_with_lora(
                        i, llm.layers[i], state, positions, forward_batch,
                        qkvr=adapter.core_qkvr[i], wo=adapter.core_wo[i], router=adapter.core_router[i],
                        slot=slot, vid=vid,
                    )
            mid_prev = next_mid_prev
            if not is_final_pass:
                s_prev = state.partial

        # Apple LoopCD-Hidden (arXiv:2610.02185): contrast final loop (h_R) against first loop (h_1)
        if CD_OMEGA != 0.0:
            state.partial = _loop_cd_hidden(state.partial, s_first, CD_OMEGA)
            attn_input = None

        # 4. Coda (L42..47): already merged in-place when fused (0 overhead!), else CodaLoRA(slot=0)
        for i in range(CORE_END, NUM_PHYSICAL_LAYERS):
            if captures is not None and i in capture_set:
                captures.append(state.partial.to(cap_dtype))
            if glued_ctx is not None:
                is_last = (i == NUM_PHYSICAL_LAYERS - 1)
                nxt = None if is_last else llm.layers[i + 1]
                attn_input, final_hidden = _run_layer_glued_body(
                    i, llm.layers[i], state, attn_input, positions, forward_batch,
                    next_layer=nxt, is_last=is_last, **glued_ctx,
                )
            elif fused is not None:
                llm.layers[i](state, positions, forward_batch)
            else:
                _run_layer_with_lora(
                    i, llm.layers[i], state, positions, forward_batch,
                    qkvr=adapter.coda_qkvr[i], wo=adapter.coda_wo[i], router=None,
                    slot=0, vid=None,
                )

        if final_hidden is None:
            final_hidden = llm.norm(state.compute_output())
        if captures is not None:
            captures.append(final_hidden.to(cap_dtype))
            return final_hidden, captures.finalize()
        return final_hidden

    _loop_llm_forward.__wrapped__ = orig_llm_forward
    _loop_llm_forward._loop_depth_patched = True
    llm.forward = _loop_llm_forward


def install_model(mod: Any) -> None:
    """Wrap Inkling2ForConditionalGeneration.load_weights to attach the loop adapter once loaded."""
    if not ADAPTER_DIR:
        return
    cls = mod.Inkling2ForConditionalGeneration
    if getattr(cls.load_weights, "_loop_depth_patched", False):
        return
    stock_load = cls.load_weights

    def load_weights(self, weights):
        out = stock_load(self, weights)
        llm = getattr(self, "llm", None)
        if llm is not None and not getattr(llm, "_loop_adapter_loaded", False):
            from sglang.srt.runtime_context import get_parallel

            tp_rank = int(get_parallel().attn_tp_rank)
            tp_size = int(get_parallel().attn_tp_size)
            device = llm.embed_tokens.weight.device
            adapter = _LoadedLoopAdapter(ADAPTER_DIR, tp_rank=tp_rank, device=device, tp_size=tp_size)
            _attach_runtime_hooks(llm, adapter)
            llm._loop_adapter = adapter
            llm._loop_adapter_loaded = True

            # Zero-quality-loss memory saver #3: ranks 1..N-1 never run self.visual (rank 0 encodes & broadcasts),
            # only reading next(self.visual.parameters()).device -> free 655 MB of dead BF16 weights on ranks 1..3!
            vis = getattr(self, "visual", None)
            if tp_rank > 0 and vis is not None:
                freed_bytes = 0
                with torch.no_grad():
                    for p in vis.parameters():
                        if p.numel() > 0:
                            freed_bytes += p.numel() * p.element_size()
                            p.data = p.data.new_empty((0,))
                if freed_bytes > 0:
                    torch.cuda.empty_cache()
                    log.warning(
                        "[loop_depth] rank %d freed %.1f MB of unused visual encoder weights (rank 0 encodes & broadcasts)",
                        tp_rank, freed_bytes / 1e6,
                    )
        return out

    load_weights.__wrapped__ = stock_load
    load_weights._loop_depth_patched = True
    cls.load_weights = load_weights

    # Single outer post-prefill allocator trim (runs once per chunk after lm_head / captures return on EXTEND >= 512)
    if not getattr(cls.forward, "_loop_trim_patched", False):
        stock_top_forward = cls.forward

        def forward_with_trim(self, input_ids, positions, forward_batch, *args, **kwargs):
            out = stock_top_forward(self, input_ids, positions, forward_batch, *args, **kwargs)
            if (
                forward_batch.forward_mode.is_extend()
                and not torch.cuda.is_current_stream_capturing()
            ):
                n_tok = int(input_ids.shape[0]) if input_ids is not None else (
                    int(positions.shape[0]) if positions is not None else 0
                )
                if n_tok >= 512:
                    dev = input_ids.device if input_ids is not None else positions.device
                    if (torch.cuda.memory_reserved(dev) - torch.cuda.memory_allocated(dev)) >= 512 * 1024 * 1024:
                        torch.cuda.empty_cache()
            return out

        forward_with_trim.__wrapped__ = stock_top_forward
        forward_with_trim._loop_trim_patched = True
        cls.forward = forward_with_trim

    # Fallback unpack guard for freed lm_head.weight (zero-quality-loss memory saver #5)
    lp_cls = getattr(mod, "Inkling2LogitsProcessor", None)
    if lp_cls is not None and not getattr(lp_cls._compute_lm_head, "_loop_lmhead_freed_patched", False):
        prev_lm_head = lp_cls._compute_lm_head

        def _compute_lm_head_with_unpack(self, hidden_states, lm_head, embedding_bias=None, *, out=None):
            q = lm_head.__dict__.get("_p12_head")
            if (
                q is not None
                and lm_head.weight.numel() == 0
                and (hidden_states.shape[0] > 64 or embedding_bias is not None)
            ):
                import dense_p12

                tmp_w = torch.empty(q.a.shape, dtype=torch.bfloat16, device=q.a.device)
                dense_p12.unpack_into(q, tmp_w)
                orig_empty = lm_head.weight.data
                lm_head.weight.data = tmp_w
                try:
                    return prev_lm_head(self, hidden_states, lm_head, embedding_bias, out=out)
                finally:
                    lm_head.weight.data = orig_empty
                    del tmp_w
            return prev_lm_head(self, hidden_states, lm_head, embedding_bias, out=out)

        _compute_lm_head_with_unpack.__wrapped__ = prev_lm_head
        _compute_lm_head_with_unpack._loop_lmhead_freed_patched = True
        lp_cls._compute_lm_head = _compute_lm_head_with_unpack


def install_mtp(mod: Any) -> None:
    """Zero-overhead load-time merge of an aligned MTP drafter checkpoint (`SPARK_MTP_ADAPTER`).

    Folds updated `fuse_weight`, `markov_head`, and 5-layer DFlash LoRA deltas directly into the
    BF16 `Inkling2ForConditionalGenerationMTP` parameters right inside `load_weights` (BEFORE
    `dense_i8` / `markov_i8` quantize the drafter) -> literally 0.00 ms runtime overhead!
    """
    if not MTP_ADAPTER_DIR:
        return
    cls = mod.Inkling2ForConditionalGenerationMTP
    if getattr(cls.load_weights, "_mtp_align_patched", False):
        return
    stock_load = cls.load_weights

    def load_weights(self, weights):
        loaded = stock_load(self, weights)
        from sglang.srt.runtime_context import get_parallel

        tp_rank = int(get_parallel().attn_tp_rank)
        root = Path(MTP_ADAPTER_DIR)
        pt_path = root / f"mtp_align_rank{tp_rank}.pt"
        meta_path = root / "meta.json"
        if not pt_path.is_file():
            raise FileNotFoundError(f"loop_depth: missing MTP align shard {pt_path}")
        if meta_path.is_file():
            meta = json.loads(meta_path.read_text())
            exp = (meta.get("sha256") or {}).get(pt_path.name)
            if exp:
                got = hashlib.sha256(pt_path.read_bytes()).hexdigest()
                if got != exp:
                    raise RuntimeError(f"loop_depth: MTP align SHA-256 mismatch on {pt_path}")
        blob = torch.load(str(pt_path), map_location=self.fuse_weight.device, weights_only=True)
        sd = blob["state_dict"] if isinstance(blob, dict) and "state_dict" in blob else blob
        params = dict(self.named_parameters())

        with torch.no_grad():
            n_direct = 0
            n_lora = 0
            for k, v in sd.items():
                if k.startswith("delta."):
                    continue
                if k in params:
                    params[k].data.copy_(v.to(device=params[k].device, dtype=params[k].dtype))
                    n_direct += 1
            for k in list(sd.keys()):
                if k.startswith("delta.") and k.endswith(".A"):
                    base_key = k[len("delta.") : -len(".A")]
                    if base_key not in params:
                        continue
                    A = sd[k].to(device=params[base_key].device, dtype=torch.float32)
                    B = sd[f"delta.{base_key}.B"].to(device=params[base_key].device, dtype=torch.float32)
                    scale = float(sd[f"delta.{base_key}.scale"].item())
                    delta_w = (B.t() @ A.t()) * scale
                    params[base_key].data.copy_((params[base_key].data.to(torch.float32) + delta_w).to(params[base_key].dtype))
                    n_lora += 1
            # Recompute fuse_alpha after updating fuse_weight!
            fuse_alpha = torch.softmax(self.fuse_weight.float(), dim=-1).to(self.fuse_weight.dtype)
            if self._fuse_alpha is None:
                self._fuse_alpha = fuse_alpha
            else:
                self._fuse_alpha.copy_(fuse_alpha)
        log.warning(
            "[loop_depth] rank %d merged aligned MTP drafter %s (direct=%d, lora_folded=%d, 0.00 ms runtime overhead!)",
            tp_rank, pt_path.name, n_direct, n_lora,
        )
        return loaded

    load_weights.__wrapped__ = stock_load
    load_weights._mtp_align_patched = True
    cls.load_weights = load_weights

    # Zero-quality-loss memory saver #5: after attach_shared_modules folds markov_head into lm_head,
    # free the redundant 463.2 MB BF16 copy of lm_head.weight (decode/verify/prefill M<=64 use exact 12-bit _p12_head,
    # draft uses INT8 _i8_head, and rare M>64 prompt logprobs unpack _p12_head transiently!).
    if not getattr(cls.attach_shared_modules, "_loop_lmhead_free_patched", False):
        stock_attach = cls.attach_shared_modules

        def attach_shared_modules(self, *, embed_tokens, lm_head):
            res = stock_attach(self, embed_tokens=embed_tokens, lm_head=lm_head)
            if lm_head.__dict__.get("_p12_head") is not None and lm_head.weight.numel() > 0:
                freed_mb = lm_head.weight.numel() * lm_head.weight.element_size() / 1e6
                lm_head.weight.data = lm_head.weight.data.new_empty((0, lm_head.weight.shape[1]))
                torch.cuda.empty_cache()
                log.warning(
                    "[loop_depth] freed redundant %.1f MB BF16 lm_head.weight (exact 12-bit _p12_head + INT8 _i8_head active)",
                    freed_mb,
                )
            return res

        attach_shared_modules.__wrapped__ = stock_attach
        attach_shared_modules._loop_lmhead_free_patched = True
        cls.attach_shared_modules = attach_shared_modules


def _rss_mb() -> float:
    try:
        with open("/proc/self/statm") as f:
            pages = int(f.read().split()[1])
        return pages * os.sysconf("SC_PAGE_SIZE") / (1024 * 1024)
    except Exception:
        return 0.0


def _malloc_trim() -> None:
    try:
        import ctypes

        ctypes.CDLL("libc.so.6").malloc_trim(0)
    except Exception:
        pass


def _strip_mm_features_for_broadcast(data: Any) -> tuple[list[tuple[Any, Any]], int]:
    """Temporarily detach MultimodalDataItem.feature tensors before broadcasting to ranks 1..N-1.

    Inkling2ForConditionalGeneration.get_image_feature ONLY reads item.feature on rank 0
    (ranks 1..N-1 read vision_grid_thw and receive rank 0's broadcast embeddings). Stripping
    dead pixel tensors avoids shipping multi-GB images + 3x pickle copies onto ranks 1..N-1!
    """
    saved: list[tuple[Any, Any]] = []
    stripped_bytes = 0
    if not isinstance(data, (list, tuple)):
        return saved, 0

    def _visit(req: Any) -> None:
        nonlocal stripped_bytes
        batch = getattr(req, "batch", None)
        if isinstance(batch, (list, tuple)):
            for sub in batch:
                _visit(sub)
            return
        mm = getattr(req, "mm_inputs", None)
        if mm is None:
            return
        items = getattr(mm, "mm_items", None)
        if not items:
            return
        for item in items:
            feat = getattr(item, "feature", None)
            if feat is None:
                continue
            # Only strip IMAGE items whose hash/pad_value are already materialized
            mod_obj = getattr(item, "modality", None)
            if mod_obj is None or getattr(mod_obj, "name", "") != "IMAGE":
                continue
            if getattr(item, "pad_value", None) is None:
                continue
            if isinstance(feat, torch.Tensor):
                stripped_bytes += feat.numel() * feat.element_size()
            elif isinstance(getattr(feat, "data", None), (bytes, bytearray)):
                stripped_bytes += len(feat.data)
            elif isinstance(feat, (list, tuple)):
                for t in feat:
                    if isinstance(t, torch.Tensor):
                        stripped_bytes += t.numel() * t.element_size()
            saved.append((item, feat))
            item.feature = None

    for req in data:
        _visit(req)
    return saved, stripped_bytes


def install_request_receiver(mod: Any) -> None:
    """Zero-copy broadcast_pyobj + strip dead IMAGE item.feature tensors on ranks 1..N-1 + RSS spike tracer."""
    if getattr(mod, "_loop_bcast_patched", False):
        return
    orig_bcast = getattr(mod, "broadcast_pyobj", None)
    if orig_bcast is None:
        return
    import pickle
    import warnings
    import torch.distributed as dist

    def _fast_broadcast_pyobj(data, rank, dist_group=None, src=0, force_cpu_device=True):
        device = torch.device("cpu") if force_cpu_device or not torch.cuda.is_available() else torch.device("cuda")
        r0_rss = _rss_mb()
        if rank == src:
            if not data:
                tensor_size = torch.tensor([0], dtype=torch.long, device=device)
                dist.broadcast(tensor_size, src=src, group=dist_group)
                return data
            saved, stripped_bytes = _strip_mm_features_for_broadcast(data)
            try:
                serialized_data = pickle.dumps(data, protocol=pickle.HIGHEST_PROTOCOL)
            finally:
                for item, feat in saved:
                    item.feature = feat
            size = len(serialized_data)
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", UserWarning)
                tensor_data = torch.frombuffer(serialized_data, dtype=torch.uint8)
                if device.type != "cpu":
                    tensor_data = tensor_data.to(device)
            tensor_size = torch.tensor([size], dtype=torch.long, device=device)
            dist.broadcast(tensor_size, src=src, group=dist_group)
            dist.broadcast(tensor_data, src=src, group=dist_group)
            del tensor_data, serialized_data
            if size >= 8 * 1024 * 1024 or stripped_bytes >= 8 * 1024 * 1024:
                _malloc_trim()
            if size >= 2 * 1024 * 1024 or stripped_bytes > 0:
                log.warning(
                    "[loop_depth] broadcast_pyobj rank=%d sent=%.1f MB (stripped %d mm_items = %.1f MB from ranks 1..3) rss=%.0f->%.0f MB",
                    rank, size / 1e6, len(saved), stripped_bytes / 1e6, r0_rss, _rss_mb(),
                )
            return data
        else:
            tensor_size = torch.tensor([0], dtype=torch.long, device=device)
            dist.broadcast(tensor_size, src=src, group=dist_group)
            size = int(tensor_size.item())
            if size == 0:
                return []
            tensor_data = torch.empty(size, dtype=torch.uint8, device=device)
            dist.broadcast(tensor_data, src=src, group=dist_group)
            buf = tensor_data if device.type == "cpu" else tensor_data.cpu()
            res = pickle.loads(memoryview(buf.numpy()))
            del buf, tensor_data
            if size >= 8 * 1024 * 1024:
                _malloc_trim()
            if size >= 2 * 1024 * 1024:
                log.warning(
                    "[loop_depth] broadcast_pyobj rank=%d recv=%.1f MB rss=%.0f->%.0f MB",
                    rank, size / 1e6, r0_rss, _rss_mb(),
                )
            return res

    _fast_broadcast_pyobj.__wrapped__ = orig_bcast
    mod.broadcast_pyobj = _fast_broadcast_pyobj
    mod._loop_bcast_patched = True
    log.warning("[loop_depth] installed zero-copy broadcast_pyobj + rank 1..3 dead mm_feature strip")


def install_rss_tracer(mod: Any) -> None:
    """Lightweight RSS-spike detector on ScheduleBatch.prepare_for_extend (logs only jumps >= 512 MB)."""
    sb_cls = getattr(mod, "ScheduleBatch", None)
    if sb_cls is None or getattr(sb_cls.prepare_for_extend, "_loop_rss_patched", False):
        return
    orig_prep = sb_cls.prepare_for_extend

    def prepare_for_extend_traced(self, *args, **kwargs):
        r0 = _rss_mb()
        out = orig_prep(self, *args, **kwargs)
        r1 = _rss_mb()
        if r1 - r0 >= 512.0:
            log.warning(
                "[loop_depth] RSS spike in prepare_for_extend: +%.0f MB (%.0f->%.0f MB, reqs=%d, tokens=%d)",
                r1 - r0, r0, r1, len(getattr(self, "reqs", ())), int(getattr(self, "extend_num_tokens", 0)),
            )
        return out

    prepare_for_extend_traced.__wrapped__ = orig_prep
    prepare_for_extend_traced._loop_rss_patched = True
    sb_cls.prepare_for_extend = prepare_for_extend_traced