File size: 77,999 Bytes
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
f34fab5
84d5f5d
f34fab5
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
84d5f5d
 
 
 
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
f34fab5
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34fab5
 
84d5f5d
 
f34fab5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
f34fab5
 
 
84d5f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""HybridGPT: a decoder-only LM mixing sliding-window attention and gated delta-rule memory.

Standalone module: it needs only PyTorch and imports nothing from other project files.
flash-linear-attention (fla) is optional and only speeds up the delta scan on CUDA;
without FlexAttention, attention falls back to dense SDPA. It defines the model, the loss
and the optimizers; training and data loading live in the calling script.

Model: x0 lambdas, relu^2 MLPs, zero-initialized output projections, U-Net skips between
the encoder and decoder halves plus a token-dependent mix of all encoder outputs
(routed_skips; skip_mix starts at 0, so the model starts as a plain U-Net), smear gate,
backout, value embeddings, 30*tanh logit softcap and an optional log-unigram output bias.
Attention ("A"): MQA, QK-norm, RoPE, output gate, value residual, causal sliding window
masked to the current document (FlexAttention on CUDA).
Delta memory ("D"): gated delta rule with exclusive reads and induction-style shifted keys
(token t stores its value under the key of t-1; query and key share a projection), gates
from t and t-1, tanh-bounded values, and per-head half-lives spread geometrically from 1
to delta_max_half_life across all delta layers.

layout: one char per layer. "-" identity (x0 lambdas only), "M" MLP,
"A" sliding-window attention + MLP, "D" delta memory + MLP.
"-AAAAAAMAAAA" with routed_skips=False is attention-only.

Streaming (HybridMemory): memory means "the next chunk continues this stream". Never carry
it into unrelated samples (independent batches, a new prompt): attention would read the
previous samples' keys and the delta memory their writes. Pass memory=None, call
memory.reset(rows), or, with the defaults attn_doc_mask=True and delta_reset="hard", start
each sample with eos_token. Every carried quantity is exact, so a stream fed in chunks of
any size (training rows with TBPTT via memory.detach(), eval windows, one token at a time
in generate) gives the same logits as one pass over the whole stream, up to rounding:
    attention: the last attn_window keys (QK-normed, before RoPE) and values with their
        doc ids; RoPE is re-applied per chunk, so positions never grow.
    delta: matrix state + the last input (for the shifted key and gates).
    smear: the previous token.
State per sequence is constant: ~2.6 MB of KV (bf16) + ~2 MB of delta state (fp32) at
the defaults.

Documents: eos_token starts a document. With attn_doc_mask, attention and smear never
cross a document start; delta_reset="hard" also clears the delta memory there, "none" lets
the decay gate (which sees EOS) learn it. For streams where EOS separates related parts
(sessions, turns), use attn_doc_mask=False and delta_reset="none".
The loss is computed in chunks of tokens (softcap_cross_entropy) and generate keeps only
the last position's logits, so neither holds [T, vocab] logits.
Attention windows must not exceed attn_window (the cache size): forward rejects larger
ones, and attn_window_schedule stays within it.

Kernels: model.select_backends() (call it eagerly before torch.compile) picks, per GPU
architecture, faster kernels for the same computation where they are installed and pass a
numerical check against fp32: FlashAttention varlen (FA3 on Hopper: one sequence per document,
the first one including the cached keys of the continued document), FlexAttention's FLASH
backend (FA4) and FlashQLA for the delta scan (its sequence split made exact). Everything
else, and any GPU without them, keeps FlexAttention/Triton and fla. Parameters and
checkpoints do not depend on the kernels.
"""

import math
import warnings
from dataclasses import dataclass
from typing import NamedTuple, Optional

import torch
from torch import Tensor, nn
from torch.nn import functional as F

try:
    from torch.nn.attention.flex_attention import BlockMask, create_block_mask, flex_attention
except ImportError:  # old torch: dense attention only
    BlockMask = create_block_mask = flex_attention = None
try:  # flash-linear-attention Triton kernels (CUDA); tools/colab_run.py pins the tested version
    from fla.ops.gated_delta_rule import chunk_gated_delta_rule as _fla_delta_rule
except Exception:
    _fla_delta_rule = None
try:  # its forward and backward, wrapped below as custom ops (see _register_fla_ops)
    from fla.ops.gated_delta_rule.chunk import chunk_gated_delta_rule_bwd as _fla_bwd
    from fla.ops.gated_delta_rule.chunk import chunk_gated_delta_rule_fwd as _fla_fwd
except Exception:
    _fla_fwd = _fla_bwd = None

# The PyTorch fallback scan (CPU, tests) runs outside torch.compile, and each graph break
# makes every Block its own compiled frame: more variants than dynamo's default limit of 8,
# beyond which it falls back to eager.
for _attr in ("recompile_limit", "cache_size_limit"):
    if hasattr(torch._dynamo.config, _attr):
        setattr(torch._dynamo.config, _attr, max(getattr(torch._dynamo.config, _attr), 128))

# Wrapped once at import; compilation happens on first use.
if flex_attention is not None:
    _flex_attention = torch.compile(flex_attention, dynamic=False)
    _create_block_mask = torch.compile(create_block_mask, dynamic=False)

RESET_LOG_DECAY = -30.0   # exp(-30) ~ 1e-13: clears the memory without inf - inf in chunk sums
EMPTY_DOC = -(2**40)      # doc id of an unused KV cache slot: never equal to a real id
FLEX_MIN_QUERIES = 128    # below this (decoding), the dense path is cheaper than a block mask
FLEX_BLOCK_SIZE = 128


def _aligned_window_block_mask(qdocs: Tensor, kdocs: Tensor, window, past: int, mask_mod):
    """Classify aligned tiles using document and distance bounds, without a token-pair mask."""
    block = FLEX_BLOCK_SIZE
    q_start = torch.arange(0, qdocs.size(1), block, device=qdocs.device)[:, None] + past
    k_start = torch.arange(0, kdocs.size(1), block, device=kdocs.device)[None, :]
    min_dist = q_start - (k_start + block - 1)
    max_dist = q_start + block - 1 - k_start
    q_first, q_last = qdocs[:, ::block, None], qdocs[:, block - 1::block, None]
    k_first, k_last = kdocs[:, None, ::block], kdocs[:, None, block - 1::block]
    # Document IDs are nondecreasing. Every legal pair must satisfy these bounds.
    possible = (min_dist < window) & (max_dist >= 0) & (q_first <= k_last) & (k_first <= q_last)
    full = (min_dist >= 0) & (max_dist < window) & (q_first == q_last) & (q_first == k_first) & (k_first == k_last)

    def ordered(tiles):
        tiles = tiles[:, None].to(torch.int32)
        counts = tiles.sum(-1, dtype=torch.int32)
        indices = tiles.argsort(dim=-1, descending=True, stable=True).to(torch.int32)
        return counts, indices

    # Boundary tiles still use the exact per-pair mask in FlexAttention.
    return BlockMask.from_kv_blocks(*ordered(possible & ~full), *ordered(full),
                                    BLOCK_SIZE=block, mask_mod=mask_mod)


# ----------------------------------------------------------------------------- FlashAttention varlen
# The same attention as the FlexAttention mask (same document, 0 <= q - k < window) through
# FlashAttention's variable-length kernels: one sequence per document, FA's causal sliding
# window (left = window - 1, aligned to the end of each key span) and native MQA. The kernels
# behind torch.ops.aten._flash_attention_* are FA2, or FA3 on Hopper once activated through
# torch.nn.attention.activate_flash_attention_impl (select_backends does that).

@torch.library.custom_op("hgpt::varlen_attn_fwd", mutates_args=())
def _varlen_attn_fwd(q: Tensor, k: Tensor, v: Tensor, cu_q: Tensor, cu_k: Tensor, meta: Tensor,
                     scale: float) -> tuple[Tensor, Tensor]:
    """q [T, H, D]; k, v [P + T, 1, D]; meta (CPU int64): key offset, max query and key span,
    left window. The host values travel in a CPU tensor, so torch.compile never specializes on
    them (no recompile per row)."""
    start, max_q, max_k, left = meta.tolist()
    out, lse = torch.ops.aten._flash_attention_forward(
        q, k[start:], v[start:], cu_q, cu_k, max_q, max_k, 0.0, False, False,
        scale=scale, window_size_left=left, window_size_right=0)[:2]
    return out, lse


@_varlen_attn_fwd.register_fake
def _(q, k, v, cu_q, cu_k, meta, scale):
    return torch.empty_like(q), q.new_empty((q.size(1), q.size(0)), dtype=torch.float32)


@torch.library.custom_op("hgpt::varlen_attn_bwd", mutates_args=())
def _varlen_attn_bwd(do: Tensor, q: Tensor, k: Tensor, v: Tensor, out: Tensor, lse: Tensor, cu_q: Tensor,
                     cu_k: Tensor, meta: Tensor, scale: float) -> tuple[Tensor, Tensor, Tensor]:
    start, max_q, max_k, left = meta.tolist()
    rng = torch.zeros(2, dtype=torch.uint64, device=q.device)  # no dropout: unused by the kernel
    unused = torch.empty(0, device=q.device)
    dq, dk, dv = torch.ops.aten._flash_attention_backward(
        do.contiguous(), q, k[start:], v[start:], out, lse, cu_q, cu_k, max_q, max_k, 0.0, False, rng, unused,
        scale=scale, window_size_left=left, window_size_right=0)
    pad = k.new_zeros(start, *k.shape[1:])  # cached keys no query can see
    return dq, torch.cat((pad, dk.to(k.dtype))), torch.cat((pad, dv.to(v.dtype)))


@_varlen_attn_bwd.register_fake
def _(do, q, k, v, out, lse, cu_q, cu_k, meta, scale):
    return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)


def _varlen_setup_context(ctx, inputs, output):
    q, k, v, cu_q, cu_k, meta, scale = inputs
    ctx.save_for_backward(q, k, v, output[0], output[1], cu_q, cu_k, meta)
    ctx.scale = scale


def _varlen_backward(ctx, dout, _dlse):
    q, k, v, out, lse, cu_q, cu_k, meta = ctx.saved_tensors
    dq, dk, dv = _varlen_attn_bwd(dout, q, k, v, out, lse, cu_q, cu_k, meta, ctx.scale)
    return dq, dk, dv, None, None, None, None


_varlen_attn_fwd.register_autograd(_varlen_backward, setup_context=_varlen_setup_context)


@torch.compiler.disable
def _varlen_layout(qdocs: Tensor, kdocs: Tensor, window, past: int):
    """Segments of one row for FlashAttention varlen: one per document present in the queries.
    The first also takes the cached keys of the document the memory ended in: the trailing
    cache slots with the first query's doc id (doc ids never decrease, unused slots hold
    EMPTY_DOC), so its keys start at slot past - m of the past + T keys. A query's legal keys
    all lie in its own segment, where FA's causal window (left = window - 1, aligned to the
    segment end) leaves exactly the pairs with 0 <= q - k < window.
    One host sync per forward, outside the compiled graph (the only graph break it adds)."""
    qd = qdocs[0]
    T = qd.numel()
    change = torch.ones_like(qd, dtype=torch.bool)
    change[1:] = qd[1:] != qd[:-1]
    cached = (kdocs[0, :past] == qd[0]).sum().view(1) if past else qd.new_zeros(1)
    width = window.reshape(1).to(qd) if isinstance(window, Tensor) else qd.new_full((1,), int(window))
    host = torch.cat((torch.nonzero(change).flatten(), cached, width)).cpu().tolist()
    bounds, m, width = host[:-2] + [T], host[-2], host[-1]
    lengths = [b - a for a, b in zip(bounds, bounds[1:])]
    cu_q = torch.tensor(bounds, dtype=torch.int32)
    cu_k = cu_q + m
    cu_k[0] = 0
    meta = torch.tensor([past - m, max(lengths), max(max(lengths), lengths[0] + m), width - 1], dtype=torch.int64)
    cu_q, cu_k = cu_q.to(qd.device), cu_k.to(qd.device)
    for t in (cu_q, cu_k):  # the number of documents changes from row to row
        torch._dynamo.maybe_mark_dynamic(t, 0)
    return cu_q, cu_k, meta


@dataclass
class HybridConfig:
    vocab_size: int = 50304
    n_layer: int = 12
    n_head: int = 6
    n_embd: int = 768
    layout: str = "-DADADAMDADA"
    delta_heads: int = 6
    delta_head_dim: int = 128          # fla supports head dims up to 256
    delta_max_half_life: float = 65536.0
    delta_reset: str = "hard"          # "hard": clear delta memory at EOS; "none": learned
    attn_doc_mask: bool = True         # attention and smear never cross an EOS
    attn_window: int = 1024            # largest attention window = KV cache size
    routed_skips: bool = True
    eos_token: int = 50256
    backout_layer: int = 8
    flex_kernel_options: dict | None = None


class DeltaCarry(NamedTuple):
    state: Tensor  # [B, H, Dk, Dv], fp32 (fp64 for fp64 models)
    last: Tensor   # [B, d] normalized mixer input at the last position


class KVCarry(NamedTuple):
    k: Tensor      # [B, W, head_dim] QK-normed keys before RoPE
    v: Tensor      # [B, W, head_dim] values after value-embedding / residual mixing


class HybridMemory(NamedTuple):
    delta: tuple   # DeltaCarry per "D" layer
    attn: tuple    # KVCarry per "A" layer
    docs: Tensor   # [B, W] doc id per cached key, relative to the last token (0); EMPTY_DOC if unused
    prev_token: Tensor  # [B] last token (smear gate)
    has_prev: Tensor    # [B] bool: prev_token is real

    def reset(self, rows: Tensor | None = None) -> "HybridMemory":
        """Start new streams in the selected rows (bool [B]; None = all rows): their memory
        becomes empty, equivalent to passing no memory for them. Use it whenever a
        row's next chunk does not continue that row's previous chunk."""
        if rows is None:
            rows = torch.ones_like(self.has_prev)
        keep = ~rows

        def clear(t):
            return t * keep.view(-1, *([1] * (t.dim() - 1))).to(t.dtype)
        return HybridMemory(
            tuple(DeltaCarry(clear(c.state), clear(c.last)) for c in self.delta),
            tuple(KVCarry(clear(c.k), clear(c.v)) for c in self.attn),
            torch.where(rows[:, None], torch.full_like(self.docs, EMPTY_DOC), self.docs),
            self.prev_token * keep, self.has_prev & keep,
        )

    def detach(self) -> "HybridMemory":
        """TBPTT boundary: call between training chunks."""
        return HybridMemory(
            tuple(DeltaCarry(c.state.detach(), c.last.detach()) for c in self.delta),
            tuple(KVCarry(c.k.detach(), c.v.detach()) for c in self.attn),
            self.docs, self.prev_token, self.has_prev,
        )

    def resize_attention(self, window: int) -> "HybridMemory":
        """Keep the newest cached tokens and mask any newly added slots."""
        if window < 1:
            raise ValueError("attention cache size must be positive")
        extra = window - self.docs.size(1)
        if extra == 0:
            return self
        if extra > 0:
            docs = F.pad(self.docs, (extra, 0), value=EMPTY_DOC)
            attn = tuple(KVCarry(F.pad(c.k, (0, 0, extra, 0)), F.pad(c.v, (0, 0, extra, 0)))
                         for c in self.attn)
        else:
            docs = self.docs[:, -window:].clone()
            attn = tuple(KVCarry(c.k[:, -window:].clone(), c.v[:, -window:].clone())
                         for c in self.attn)
        return self._replace(attn=attn, docs=docs)


def detach_memory(memory):
    return None if memory is None else memory.detach()


def attn_window_schedule(step: int, num_iterations: int, cfg: HybridConfig, start: int = 256,
                         block: int = 256) -> int:
    """Attention window for a training step: grows linearly from start to cfg.attn_window,
    rounded down to a multiple of block but never below start, and reaches cfg.attn_window
    at step == num_iterations. start is clipped to the cache size, so a cache smaller than
    start keeps its full size, and one that is not a multiple of block is still used in
    full at the end."""
    end = cfg.attn_window
    start = max(min(start, end), 1)
    frac = min(max(step / max(num_iterations, 1), 0.0), 1.0)
    raw = start + frac * (end - start)
    if raw >= end:
        return end
    return max(block * int(raw // block), start)


def norm(x: Tensor) -> Tensor:
    return F.rms_norm(x, (x.size(-1),))


def value_embed_layout(n_layer: int):
    """Value-embedding table per layer (None: none): tables 1, 2 at layers 1-2 and
    tables 0, 1, 2 at the last three layers."""
    assert n_layer >= 6, "value-embedding layout needs at least 6 layers"
    return [None, 1, 2] + [None] * (n_layer - 6) + [0, 1, 2]


class CastedLinear(nn.Linear):
    """Bias-free Linear that starts at exactly zero."""

    def __init__(self, in_features, out_features):
        super().__init__(in_features, out_features, bias=False)

    def reset_parameters(self):
        with torch.no_grad():
            self.weight.zero_()


def _uniform_(lin: nn.Linear, fan_in: int):
    bound = 3**0.5 * 0.5 * fan_in**-0.5
    with torch.no_grad():
        lin.weight.uniform_(-bound, bound)


# ----------------------------------------------------------------------------- delta rule

def _delta_scan(query, key, value, log_decay, beta, initial, chunk: int = 64):
    """Chunked (WY form) gated delta rule with exclusive reads.

    S_t = a_t (I - b_t k_t k_t^T) S_{t-1} + b_t k_t v_t^T,  o_t = S_{t-1}^T q_t.
    [B, T, H, D] inputs, [B, T, H] gates (log_decay = log a, beta = b), [B, H, Dk, Dv] state.
    """
    batch, length, heads, _ = key.shape
    chunk = min(chunk, length)
    pad = -length % chunk
    q, k, v = (x.transpose(1, 2) for x in (query, key, value))
    g, b = log_decay.transpose(1, 2), beta.transpose(1, 2)
    if pad:
        q, k, v = (F.pad(x, (0, 0, 0, pad)) for x in (q, k, v))
        g, b = F.pad(g, (0, pad)), F.pad(b, (0, pad))
    q, k, v = (x.unflatten(2, (-1, chunk)) for x in (q, k, v))
    g, b = g.unflatten(2, (-1, chunk)), b.unflatten(2, (-1, chunk))

    cumulative = g.cumsum(-1)
    exclusive = cumulative - g
    strict = torch.ones(chunk, chunk, dtype=torch.bool, device=k.device).tril(-1)
    decay = (cumulative.unsqueeze(-1) - cumulative.unsqueeze(-2)).masked_fill(~strict, -torch.inf).exp()
    read_decay = (exclusive.unsqueeze(-1) - cumulative.unsqueeze(-2)).masked_fill(~strict, -torch.inf).exp()
    system = b.unsqueeze(-1) * (k @ k.transpose(-1, -2)) * decay
    solve = lambda rhs: torch.linalg.solve_triangular(system, rhs, upper=False, unitriangular=True)
    new_value = solve(b.unsqueeze(-1) * v)
    new_key = solve((b * cumulative.exp()).unsqueeze(-1) * k)
    attention = (q @ k.transpose(-1, -2)) * read_decay
    query_decayed = q * exclusive.exp().unsqueeze(-1)
    key_to_end = k * (cumulative[..., -1:] - cumulative).exp().unsqueeze(-1)
    chunk_decay = cumulative[..., -1].exp()[..., None, None]

    state, outputs = initial, []
    for n in range(k.size(2)):
        update = new_value[:, :, n] - new_key[:, :, n] @ state
        outputs.append(query_decayed[:, :, n] @ state + attention[:, :, n] @ update)
        state = chunk_decay[:, :, n] * state + key_to_end[:, :, n].transpose(-1, -2) @ update
    out = torch.stack(outputs, 2).flatten(2, 3)[:, :, :length]
    return out.transpose(1, 2), state


@torch.compiler.disable
def _delta_scan_torch(q, k, v, log_decay, beta, initial):
    dtype = torch.promote_types(v.dtype, torch.float32)  # fp32, or fp64 for fp64 inputs
    out, final = _delta_scan(*(t.to(dtype) for t in (q, k, v, log_decay, beta, initial)))
    return out.to(v.dtype), final


def _register_fla_ops():
    """fla's chunked forward and backward as two custom ops with an autograd formula, so
    torch.compile keeps the whole model in one graph. fla's own entry point is
    torch.compiler.disable'd: with it, the 5 delta layers split every step into 22 graphs,
    and the gradients of tensors crossing those boundaries (x0, the encoder outputs, the
    value embeddings) were summed one eager add at a time (~6% of an L4 step, plus ~6% of
    eager elementwise kernels). The backward reuses what fla's autograd.Function saves (the
    solved WY matrix A), so nothing is recomputed. Mirrors ChunkGatedDeltaRuleFunction with
    its defaults; tied to fla's internal API (tested with fla-core 0.6.0)."""
    if _fla_fwd is None or _fla_bwd is None:
        return None
    if hasattr(torch.ops.hgpt, "gated_delta_fwd"):  # this file imported twice in one process
        return torch.ops.hgpt.gated_delta_fwd

    @torch.library.custom_op("hgpt::gated_delta_fwd", mutates_args=())
    def fwd(q: Tensor, k: Tensor, v: Tensor, g: Tensor, beta: Tensor, h0: Tensor
            ) -> tuple[Tensor, Tensor, Tensor, Tensor]:
        q, k, v, g, beta, h0 = (t.contiguous() for t in (q, k, v, g, beta, h0))
        g_cum, o, A, final, _, _ = _fla_fwd(q=q, k=k, v=v, g=g, beta=beta, scale=1.0,
                                           initial_state=h0, output_final_state=True)
        return o.to(q.dtype), final, g_cum, A

    @fwd.register_fake
    def _(q, k, v, g, beta, h0):
        return (torch.empty_like(v, dtype=q.dtype), torch.empty_like(h0, dtype=torch.float32),
                torch.empty_like(g, dtype=torch.float32), k.new_empty(*k.shape[:3], 64))

    @torch.library.custom_op("hgpt::gated_delta_bwd", mutates_args=())
    def bwd(q: Tensor, k: Tensor, v: Tensor, g_cum: Tensor, beta: Tensor, A: Tensor, h0: Tensor,
            do: Tensor, dht: Optional[Tensor]) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
        q, k, v, g_cum, beta, A, h0, do = (t.contiguous() for t in (q, k, v, g_cum, beta, A, h0, do))
        dht = None if dht is None else dht.contiguous()
        dq, dk, dv, db, dg, dh0, _, _ = _fla_bwd(q=q, k=k, v=v, g=g_cum, beta=beta, A=A, scale=1.0,
                                                 initial_state=h0, do=do, dht=dht)
        return (dq.to(q.dtype), dk.to(k.dtype), dv.to(v.dtype), dg.to(g_cum.dtype),
                db.to(beta.dtype), dh0.to(h0.dtype))

    @bwd.register_fake
    def _(q, k, v, g_cum, beta, A, h0, do, dht):
        return tuple(torch.empty_like(t) for t in (q, k, v, g_cum, beta, h0))

    def setup_context(ctx, inputs, output):
        q, k, v, _, beta, h0 = inputs
        ctx.save_for_backward(q, k, v, output[2], beta, output[3], h0)

    def backward(ctx, do, dfinal, _dg_cum, _dA):  # g_cum and A are internal: no gradient
        return bwd(*ctx.saved_tensors, do, dfinal)

    fwd.register_autograd(backward, setup_context=setup_context)
    return fwd


_FLA_OP = _register_fla_ops()


def _delta_scan_fla_op(q, k, v, log_decay, beta, initial):
    """fla's kernel is inclusive (o_t = S_t^T q). Passing q_{t+1} in slot t
    yields the exclusive read of position t+1; position 0 reads the carry.
    Traced by torch.compile; the kernels run inside the custom op."""
    shifted = torch.cat((q[:, 1:], torch.zeros_like(q[:, :1])), dim=1)
    out, final, _, _ = _FLA_OP(shifted, k, v, log_decay.float(), beta.to(q.dtype), initial.float())
    first = torch.einsum("bhkv,bhk->bhv", initial.float(), q[:, 0].float()).to(out.dtype).unsqueeze(1)
    return torch.cat((first, out[:, :-1]), dim=1), final


@torch.compiler.disable
def _delta_scan_fla_eager(q, k, v, log_decay, beta, initial):
    """The same through fla's public entry point (a graph break): used when fla's internal
    forward/backward are not importable (another fla version)."""
    shifted = torch.cat((q[:, 1:], torch.zeros_like(q[:, :1])), dim=1)
    out, final = _fla_delta_rule(
        shifted, k, v, log_decay.float(), beta.to(q.dtype), scale=1.0,
        initial_state=initial.float().contiguous(), output_final_state=True,
    )
    first = torch.einsum("bhkv,bhk->bhv", initial.float(), q[:, 0].float()).to(out.dtype).unsqueeze(1)
    return torch.cat((first, out[:, :-1]), dim=1), final


_delta_scan_fla = _delta_scan_fla_op if _FLA_OP is not None else _delta_scan_fla_eager


# ----------------------------------------------------------------------------- FlashQLA delta scan

QLA_MIN_TOKENS = 4096   # FlashQLA only for long rows (training/eval); shorter calls keep fla
QLA_NO_TRUNCATION = -1e30
_QLA = {"module": None, "checked": False, "error": None}


def _flash_qla():
    """flash_qla (FlashQLA: fused TileLang gated-delta kernels for SM90/SM100 that split one
    long sequence into sub-sequences, so B=1 x 6 heads fills the GPU instead of 12-24 CTAs
    walking 2048 chunks one after another). Imported on first use: it inspects the GPU.

    Its split is made exact here. By default a sub-sequence whose last chunks already decay
    below exp(-10) starts from those chunks alone and drops the incoming state (an
    approximation). With the threshold at -1e30 no sub-sequence is ever truncated: each one
    gets its full state transition matrix, so the split is only a re-association of the same
    recurrence (rounding aside). Returns None when flash_qla cannot be used."""
    if not _QLA["checked"]:
        _QLA["checked"] = True
        try:
            import functools
            import importlib
            module = importlib.import_module("flash_qla")
            chunk = importlib.import_module("flash_qla.ops.gated_delta_rule.chunk")
            for name in ("get_warmup_chunks", "get_warmup_chunks_bidi"):
                setattr(chunk, name, functools.partial(getattr(chunk, name), threshold=QLA_NO_TRUNCATION))
            _QLA["module"] = module
        except Exception as error:  # not installed, unsupported GPU, TileLang/CUDA mismatch
            _QLA["error"] = f"{type(error).__name__}: {error}"
    return _QLA["module"]


@torch.library.custom_op("hgpt::qla_fwd", mutates_args=())
def _qla_fwd(q: Tensor, k: Tensor, v: Tensor, g: Tensor, beta: Tensor, h0: Tensor
             ) -> tuple[Tensor, Tensor, Tensor, Tensor]:
    """FlashQLA forward with the same contract as hgpt::gated_delta_fwd: o, final state,
    chunk-local cumulative log-decay and the solved WY matrix A (reused by the backward)."""
    q, k, v, g, beta, h0 = (t.contiguous() for t in (q, k, v, g, beta, h0))
    g_cum, A, o, _, final, _ = _flash_qla().chunk_gated_delta_rule_fwd(
        q=q, k=k, v=v, g=g, beta=beta, scale=1.0, initial_state=h0, output_final_state=True,
        output_h=False, auto_cp=True, enable_fwd_cp_cache=False, is_train=True)
    return o.to(q.dtype), final.float(), g_cum.float(), A


@_qla_fwd.register_fake
def _(q, k, v, g, beta, h0):
    return (torch.empty_like(v, dtype=q.dtype), torch.empty_like(h0, dtype=torch.float32),
            torch.empty_like(g, dtype=torch.float32), k.new_empty(*k.shape[:3], 64))


@torch.library.custom_op("hgpt::qla_bwd", mutates_args=())
def _qla_bwd(q: Tensor, k: Tensor, v: Tensor, g_cum: Tensor, beta: Tensor, A: Tensor, h0: Tensor,
             do: Tensor, dht: Optional[Tensor]) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
    """The backward recomputes the sub-sequence entry states (no forward cache to carry
    between custom ops); the dg it returns is for the per-token log-decay, as fla's."""
    q, k, v, g_cum, beta, A, h0, do = (t.contiguous() for t in (q, k, v, g_cum, beta, A, h0, do))
    dht = None if dht is None else dht.contiguous()
    dq, dk, dv, db, dg, dh0 = _flash_qla().chunk_gated_delta_rule_bwd(
        q=q, k=k, v=v, g=g_cum, beta=beta, A=A, do=do, dht=dht, scale=1.0, initial_state=h0,
        auto_cp=True, cp_cache=None)
    dh0 = torch.zeros_like(h0) if dh0 is None else dh0
    return (dq.to(q.dtype), dk.to(k.dtype), dv.to(v.dtype), dg.to(g_cum.dtype),
            db.to(beta.dtype), dh0.to(h0.dtype))


@_qla_bwd.register_fake
def _(q, k, v, g_cum, beta, A, h0, do, dht):
    return tuple(torch.empty_like(t) for t in (q, k, v, g_cum, beta, h0))


def _qla_setup_context(ctx, inputs, output):
    q, k, v, _, beta, h0 = inputs
    ctx.save_for_backward(q, k, v, output[2], beta, output[3], h0)


def _qla_backward(ctx, do, dfinal, _dg_cum, _dA):
    return _qla_bwd(*ctx.saved_tensors, do, dfinal)


_qla_fwd.register_autograd(_qla_backward, setup_context=_qla_setup_context)


def _delta_scan_qla(q, k, v, log_decay, beta, initial):
    """Exclusive reads through FlashQLA, exactly as _delta_scan_fla_op does through fla."""
    shifted = torch.cat((q[:, 1:], torch.zeros_like(q[:, :1])), dim=1)
    out, final, _, _ = _qla_fwd(shifted, k, v, log_decay.float(), beta.to(q.dtype), initial.float())
    first = torch.einsum("bhkv,bhk->bhv", initial.float(), q[:, 0].float()).to(out.dtype).unsqueeze(1)
    return torch.cat((first, out[:, :-1]), dim=1), final


def _qla_supports(q: Tensor) -> bool:
    """Shapes FlashQLA's kernels take (and whole 64-token chunks, so every sub-sequence of
    its split is whole chunks and gets an exact transition matrix)."""
    return (q.is_cuda and q.dtype in (torch.bfloat16, torch.float16) and q.size(-1) == 128
            and q.size(1) >= QLA_MIN_TOKENS and q.size(1) % 64 == 0)


_warned_slow_scan = False


@torch.compiler.disable
def _warn_slow_delta_scan():
    """Once per process: the PyTorch scan was ~40x slower than fla on an RTX 4060."""
    global _warned_slow_scan
    if not _warned_slow_scan:
        _warned_slow_scan = True
        warnings.warn("flash-linear-attention is not installed, so the delta scan on CUDA uses "
                      "the much slower PyTorch fallback (pip install flash-linear-attention)",
                      stacklevel=3)


def _delta_step(q, k, v, log_decay, beta, state):
    """One token (decoding): the recurrence itself, in the state's precision."""
    q, k, v = (t[:, 0].to(state.dtype) for t in (q, k, v))
    a = log_decay[:, 0].to(state.dtype).exp()[..., None, None]
    b = beta[:, 0].to(state.dtype)[..., None, None]
    out = torch.einsum("bhkv,bhk->bhv", state, q)
    recalled = torch.einsum("bhk,bhkv->bhv", k, state)
    state = a * (state - b * k[..., :, None] * recalled[..., None, :]) + b * k[..., :, None] * v[..., None, :]
    return out.unsqueeze(1), state


def _half_life_bias(half_lives: Tensor) -> Tensor:
    """Decay-gate bias with softplus(bias) = ln2 / half_life: at zero gate input the memory
    halves every half_life tokens."""
    return torch.expm1(math.log(2) / half_lives).log()


class DeltaMixer(nn.Module):
    """Gated delta-rule memory as a sequence mixer (layout "D")."""

    def __init__(self, cfg: HybridConfig, slot: int, n_slots: int, use_value_embed: bool):
        super().__init__()
        d, H, D = cfg.n_embd, cfg.delta_heads, cfg.delta_head_dim
        self.H, self.D = H, D
        self.c_qk = CastedLinear(d, H * D)    # query at t, key at t-1: induction-style recall
        self.c_v = CastedLinear(d, H * D)
        self.val_proj = CastedLinear(d, H * D) if use_value_embed else None
        self.lamb = nn.Parameter(torch.tensor(0.5)) if use_value_embed else None
        for lin in (self.c_qk, self.c_v, self.val_proj):
            if lin is not None:
                _uniform_(lin, d)
        self.c_gate = CastedLinear(d, 4 * H)  # [decay, write] from t, then from t-1; zero init
        self.out_gate = CastedLinear(12, H)
        self.c_proj = CastedLinear(H * D, d)
        # Heads of all delta layers interleave on one geometric spectrum 1 .. max_half_life.
        total = H * n_slots
        index = torch.arange(H, dtype=torch.float64) * n_slots + slot
        half_lives = cfg.delta_max_half_life ** (index / max(total - 1, 1))
        self.decay_bias = nn.Parameter(_half_life_bias(half_lives).float())
        # "auto": fla on CUDA when installed (or what HybridGPT.select_backends chose); "torch";
        # "fla"; "qla" (FlashQLA, SM90/SM100; calls it cannot take go to fla)
        self.backend = "auto"
        self.auto_backend = "fla"  # select_backends may set "qla"

    def _scan(self, *args):
        q = args[0]
        if q.size(1) == 1:
            return _delta_step(*args)
        backend = self.backend
        if backend == "auto":
            backend = self.auto_backend if q.is_cuda else "torch"
        if backend == "qla":
            # Under torch.compile only an already imported flash_qla is used (select_backends
            # imports it eagerly); tracing an import would break the graph.
            loaded = _QLA["module"] is not None or (not torch.compiler.is_compiling() and _flash_qla() is not None)
            if loaded and _qla_supports(q):
                return _delta_scan_qla(*args)
            backend = "fla"
        if backend == "fla" and _fla_delta_rule is None:
            if self.backend == "fla":
                raise RuntimeError("backend='fla' needs flash-linear-attention")
            _warn_slow_delta_scan()
            backend = "torch"
        return (_delta_scan_fla if backend == "fla" else _delta_scan_torch)(*args)

    def forward(self, x: Tensor, ve: Tensor | None, carry: DeltaCarry | None, reset: Tensor | None):
        """reset: [B, T] doc starts to clear the memory at, or None (learned forgetting)."""
        B, T, d = x.shape
        H, D = self.H, self.D
        f32 = torch.promote_types(x.dtype, torch.float32)  # gates and state: fp32 (fp64 for fp64 inputs)
        last = x.new_zeros(B, d) if carry is None else carry.last.to(x.dtype)
        state = x.new_zeros(B, H, D, D, dtype=f32) if carry is None else carry.state.to(f32)

        # Query/key map, values and gates in one GEMM (separate parameters, as Muon needs).
        weight = torch.cat((self.c_qk.weight, self.c_v.weight, self.c_gate.weight))
        sizes = (H * D, H * D, 4 * H)
        qk, v, own = F.linear(x, weight).split(sizes, dim=-1)
        qk_last, _, gate_last = F.linear(last, weight).split(sizes, dim=-1)
        q = F.normalize(qk.view(B, T, H, D).to(f32), dim=-1)
        k = torch.cat((qk_last.unsqueeze(1), qk[:, :-1]), dim=1)
        k = F.normalize(k.view(B, T, H, D).to(f32), dim=-1)
        if self.val_proj is not None and ve is not None:
            v = (1 - self.lamb) * v + self.lamb * self.val_proj(ve)
        v = torch.tanh(v).view(B, T, H, D)

        own = own.to(f32)
        preceding = torch.cat((gate_last.to(f32).unsqueeze(1), own[:, :-1]), dim=1)
        decay = own[..., :H] + preceding[..., 2 * H:3 * H]
        write = own[..., H:2 * H] + preceding[..., 3 * H:]
        log_decay = -F.softplus(decay + self.decay_bias.to(f32))
        beta = torch.sigmoid(write)

        if reset is not None:
            # Doc start s: S_{s-1} -> 0 so s reads an empty memory; no write at s-1
            # (nobody in the old doc reads it) and none at s (its key is the old doc's token).
            # S_{s-1} is read only by s itself, so looking one token ahead leaks nothing; a
            # stream split before s gets the same result from the state reset at t = 0.
            following = torch.cat((reset[:, 1:], torch.zeros_like(reset[:, :1])), dim=1)
            log_decay = log_decay + RESET_LOG_DECAY * following.unsqueeze(-1)
            beta = beta * (~(reset | following)).unsqueeze(-1)
            state = state * (~reset[:, 0]).view(B, 1, 1, 1)

        o, final = self._scan(q.to(v.dtype), k.to(v.dtype), v, log_decay, beta, state)
        # Explicit eps: F.rms_norm defaults to the input dtype's eps, which would normalize
        # weak reads differently in fp32 and fp64 runs.
        o = F.rms_norm(o.to(f32), (D,), eps=1e-6).to(v.dtype)
        o = o * torch.sigmoid(self.out_gate(x[..., :12])).unsqueeze(-1)
        return self.c_proj(o.reshape(B, T, H * D)), DeltaCarry(final, x[:, -1].clone())


# ----------------------------------------------------------------------------- attention / MLP

class Rotary(nn.Module):
    """RoPE tables for positions 0 .. length-1. With a KV cache the keys take positions
    0 .. P+T-1 and the queries P .. P+T-1 in every chunk: only differences matter."""

    def __init__(self, dim, base=10000):
        super().__init__()
        self.dim, self.base = dim, base
        self._key, self._cos, self._sin = None, None, None

    def tables(self, length: int, device, dtype):
        """Cached in eager mode only. Under torch.compile the tables are computed in the graph
        (two tiny kernels): a cache attribute that changes with the length (training rows
        with a KV cache vs. evaluation rows without) made every switch recompile the model,
        ~2 minutes after each evaluation on an L4."""
        work = torch.float64 if dtype == torch.float64 else torch.float32
        key = (length, str(device), work)
        compiling = torch.compiler.is_compiling()
        if compiling or self._key != key:
            t = torch.arange(length, device=device, dtype=work)
            inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=work) / self.dim))
            freqs = torch.outer(t, inv_freq)
            cos, sin = freqs.cos()[None, :, None, :], freqs.sin()[None, :, None, :]
            if compiling:
                return cos.to(dtype), sin.to(dtype)
            self._cos, self._sin, self._key = cos, sin, key
        return self._cos.to(dtype), self._sin.to(dtype)


def apply_rope(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor:
    x1, x2 = x.chunk(2, dim=3)
    return torch.cat((x1 * cos + x2 * sin, x2 * cos - x1 * sin), dim=3).type_as(x)


class AttentionMixer(nn.Module):
    """Causal sliding-window MQA (layout "A") with an optional KV cache."""

    def __init__(self, cfg: HybridConfig, use_value_embed: bool):
        super().__init__()
        d = cfg.n_embd
        self.n_head, self.head_dim = cfg.n_head, d // cfg.n_head
        self.c_q = CastedLinear(d, d)
        self.c_k = CastedLinear(d, self.head_dim)  # MQA
        self.c_v = CastedLinear(d, self.head_dim)
        self.val_proj = CastedLinear(d, self.head_dim) if use_value_embed else None
        for lin in (self.c_q, self.c_k, self.c_v, self.val_proj):
            if lin is not None:
                _uniform_(lin, d)
        self.lamb = nn.Parameter(torch.tensor(0.5))
        self.c_proj = CastedLinear(d, d)
        self.attn_gate = CastedLinear(12, cfg.n_head)

    def forward(self, x, ve, v1, attend, rope, carry: KVCarry | None):
        B, T = x.shape[:2]
        hd = self.head_dim
        # q, k and v in one GEMM; the weights stay separate parameters (Muon orthogonalizes each).
        qkv = F.linear(x, torch.cat((self.c_q.weight, self.c_k.weight, self.c_v.weight)))
        q, k, v = qkv.split((self.n_head * hd, hd, hd), dim=-1)
        q, k, v = q.view(B, T, self.n_head, hd), k.view(B, T, 1, hd), v.view(B, T, 1, hd)
        if v1 is None:
            v1 = v
        vi = self.val_proj(ve).view(B, T, 1, self.head_dim) if self.val_proj is not None and ve is not None else v1
        v = (1 - self.lamb) * v + self.lamb * vi
        q, k = norm(q), norm(k)
        if carry is not None:
            k = torch.cat((carry.k.unsqueeze(2).to(k.dtype), k), dim=1)
            v = torch.cat((carry.v.unsqueeze(2).to(v.dtype), v), dim=1)
        cos, sin = rope
        past = k.size(1) - T
        qr = apply_rope(q, cos[:, past:], sin[:, past:])
        kr = apply_rope(k, cos, sin)
        y = attend(qr.transpose(1, 2), kr.transpose(1, 2), v.transpose(1, 2)).transpose(1, 2)
        y = (y * torch.sigmoid(self.attn_gate(x[..., :12])).unsqueeze(-1)).reshape(B, T, -1)
        new = None
        if carry is not None:
            W = carry.k.size(1)
            new = KVCarry(k[:, -W:, 0], v[:, -W:, 0])
            if k.size(1) > 2 * W:  # a view would keep the whole chunk's keys alive
                new = KVCarry(new.k.clone(), new.v.clone())
        return self.c_proj(y), v1, new


class MLP(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.c_fc = CastedLinear(dim, 4 * dim)
        self.c_proj = CastedLinear(4 * dim, dim)
        _uniform_(self.c_fc, dim)

    def forward(self, x):
        return self.c_proj(F.relu(self.c_fc(x)).square())


class Block(nn.Module):
    def __init__(self, cfg, kind, has_ve, delta_slot, n_delta):
        super().__init__()
        self.attn = AttentionMixer(cfg, has_ve) if kind == "A" else None
        self.delta = DeltaMixer(cfg, delta_slot, n_delta, has_ve) if kind == "D" else None
        self.mlp = MLP(cfg.n_embd) if kind in "ADM" else None
        self.lambdas = nn.Parameter(torch.tensor([1.0, 0.0]))

    def forward(self, x, x0, ve, v1, attend, rope, carry, reset, c):
        """c: while nothing has been written to the stream it is c * x0, with c the product
        of the x0 lambdas so far (a scalar; None after the first write). The stream is kept
        at |c| * x0: norm(c * x0) = sign(c) * x0 would flip q, k, v and every bias-free gate
        at once when c crosses zero (in MQAR runs this broke the first delta layer's gates
        for good in 4 of 7 seeds). |c| is identical while c > 0 and continuous through 0.
        Positions the first mixer leaves at exactly zero (a delta layer's first reads in a
        document) stay |c| * x0, so the MLP's norm after it cannot flip either."""
        if c is not None:
            c = self.lambdas[0] * c + self.lambdas[1]
            x = c.abs() * x0
        else:
            x = self.lambdas[0] * x + self.lambdas[1] * x0
        if self.attn is not None:
            y, v1, carry = self.attn(norm(x), ve, v1, attend, rope, carry)
            x, c = x + y, None
        elif self.delta is not None:
            y, carry = self.delta(norm(x), ve, carry, reset)
            x, c = x + y, None
        if self.mlp is not None:
            x, c = x + self.mlp(norm(x)), None
        return x, v1, carry, c


# ----------------------------------------------------------------------------- loss

def _softcap_logits(raw: Tensor, bias: Tensor, cap: float):
    """tanh(raw / cap) and the logits cap * tanh(raw / cap) + bias, in bias' dtype."""
    t = torch.tanh(raw.to(bias.dtype) / cap)
    return t, t * cap + bias


def _ce_chunk_loss(raw: Tensor, bias: Tensor, target: Tensor, valid: Tensor, cap: float) -> Tensor:
    """Summed CE over the valid rows of one chunk of raw logits (no gradients)."""
    _, logits = _softcap_logits(raw, bias, cap)
    picked = logits.gather(1, target[:, None])[:, 0]
    return ((torch.logsumexp(logits, dim=-1) - picked) * valid).sum()


def _ce_chunk_grad(raw: Tensor, bias: Tensor, target: Tensor, valid: Tensor, scale: Tensor, cap: float):
    """Summed CE over the valid rows of one chunk, its gradient for the raw logits (rows
    scaled by scale, in raw's dtype) and every row's log-sum-exp. No in-place ops, so
    torch.compile can fuse it into a few passes over the chunk."""
    t, logits = _softcap_logits(raw, bias, cap)
    lse = torch.logsumexp(logits, dim=-1, keepdim=True)
    picked = logits.gather(1, target[:, None])
    loss = ((lse - picked)[:, 0] * valid).sum()
    vocab = torch.arange(logits.size(1), device=raw.device)
    g = (torch.exp(logits - lse) - (vocab == target[:, None]).to(logits.dtype)) * scale[:, None]
    return loss, (g * (1 - t * t)).to(raw.dtype), lse[:, 0]  # 1 - t^2: d(cap*tanh(z/cap))/dz


def _ce_chunk_bias_grad(raw: Tensor, bias: Tensor, lse: Tensor, scale: Tensor, cap: float) -> Tensor:
    """Column sums of softmax * scale over one chunk: the bias gradient without its one-hot
    part. Recomputed from the bf16 logits, so no fp32 [chunk, V] tensor is ever written:
    taking g.sum(0) above made torch.compile store g in fp32 and read it back."""
    _, logits = _softcap_logits(raw, bias, cap)
    return (torch.exp(logits - lse[:, None]) * scale[:, None]).sum(0)


def _accumulate_matmul(acc: Tensor, a: Tensor, b: Tensor):
    """acc += a @ b. With an fp32 acc and bf16/fp16 a, b on CUDA, one GEMM accumulates
    straight into acc (no product rounded to bf16, no fp32 temporary) where torch has it."""
    global _ADDMM_INTO_FP32
    if acc.dtype == a.dtype:
        acc.addmm_(a, b)
        return
    if a.is_cuda and _ADDMM_INTO_FP32 is not False:
        try:
            torch.addmm(acc, a, b, out_dtype=acc.dtype, out=acc)
            _ADDMM_INTO_FP32 = True
            return
        except (RuntimeError, TypeError, NotImplementedError):
            _ADDMM_INTO_FP32 = False
    acc += (a @ b).to(acc.dtype)


_ADDMM_INTO_FP32 = None  # unknown until the first CUDA call tries it

# Eagerly, every operation above is its own pass over a [chunk, V] fp32 tensor (memory
# bound: ~3/4 of the loss time on an RTX 4060); compiled, they fuse into a few kernels.
_ce_chunk_loss_fused = torch.compile(_ce_chunk_loss, dynamic=False, fullgraph=True)
_ce_chunk_grad_fused = torch.compile(_ce_chunk_grad, dynamic=False, fullgraph=True)
_ce_chunk_bias_fused = torch.compile(_ce_chunk_bias_grad, dynamic=False, fullgraph=True)


class _SoftcapCrossEntropy(torch.autograd.Function):
    """mean CE of cap*tanh(h W^T / cap) + b without materializing [N, V] logits.

    In chunks of tokens, the forward pass computes the loss and, when needed, the exact
    gradients for h, W and b (softmax - one-hot, through the softcap), so backward only
    rescales them: no recompute, and only [chunk, V] tensors are ever live. Softcap,
    log-sum-exp and the softmax gradient run in fp32, the gradient matmuls in h's dtype
    (the head gradient accumulates in fp32).
    With fused, the per-chunk math runs as torch.compile-fused kernels. Targets of -100
    are ignored.
    """

    @staticmethod
    def forward(ctx, h, weight, bias, target, chunk, cap, grad_enabled, fused):
        needs = tuple(n and grad_enabled for n in ctx.needs_input_grad[:3])
        valid = target != -100
        count = valid.sum().clamp_min(1)
        safe = target.clamp_min(0)
        f32 = torch.promote_types(h.dtype, torch.float32)
        bias_f = bias.to(f32)
        valid_f = valid.to(f32)
        scale = valid_f / count
        loss_fn, grad_fn, bias_fn = ((_ce_chunk_loss_fused, _ce_chunk_grad_fused, _ce_chunk_bias_fused) if fused
                                     else (_ce_chunk_loss, _ce_chunk_grad, _ce_chunk_bias_grad))
        total = torch.zeros((), device=h.device, dtype=f32)
        grad_h = torch.empty_like(h) if needs[0] else None
        grad_w = torch.zeros_like(weight, dtype=f32) if needs[1] else None
        grad_b = torch.zeros_like(bias, dtype=f32) if needs[2] else None
        for s in range(0, h.size(0), chunk):
            rows = slice(s, s + chunk)
            hc = h[rows]
            raw = F.linear(hc, weight)
            if not any(needs):
                total += loss_fn(raw, bias_f, safe[rows], valid_f[rows], cap)
                continue
            loss, gz, lse = grad_fn(raw, bias_f, safe[rows], valid_f[rows], scale[rows], cap)
            total += loss
            if grad_b is not None:  # softmax part, then -scale at every target (the one-hot part)
                grad_b += bias_fn(raw, bias_f, lse, scale[rows], cap)
                grad_b.index_add_(0, safe[rows], -scale[rows])
            if grad_h is not None:
                grad_h[rows] = gz @ weight
            if grad_w is not None:
                _accumulate_matmul(grad_w, gz.T, hc)
        ctx.save_for_backward(*(x if x is not None else torch.empty(0) for x in (grad_h, grad_w, grad_b)))
        ctx.dtypes = (weight.dtype, bias.dtype)
        return total / count

    @staticmethod
    def backward(ctx, grad_out):
        gh, gw, gb = ctx.saved_tensors
        needs = ctx.needs_input_grad
        return (gh * grad_out if needs[0] else None,
                (gw * grad_out).to(ctx.dtypes[0]) if needs[1] else None,
                (gb * grad_out).to(ctx.dtypes[1]) if needs[2] else None,
                None, None, None, None, None)


@torch.compiler.disable
def softcap_cross_entropy(h: Tensor, weight: Tensor, bias: Tensor, target: Tensor,
                          chunk: int = 8192, cap: float = 30.0, fused: bool | None = None) -> Tensor:
    """fused: compiled per-chunk kernels (default: on CUDA). They still compile when this
    function runs outside the caller's torch.compile."""
    # Autograd runs Function.forward in no-grad mode, so record the caller's mode here:
    # evaluation then skips the two gradient matmuls per chunk.
    fused = h.is_cuda if fused is None else fused
    return _SoftcapCrossEntropy.apply(h, weight, bias, target, chunk, cap, torch.is_grad_enabled(), fused)


# ----------------------------------------------------------------------------- kernel selection

ATTN_BACKENDS = ("auto", "flex", "flex_flash", "varlen", "dense")
# Kernels "auto" tries per compute-capability major, in order (HybridGPT.select_backends).
# Hopper, measured on an H100 at the training config (results/bench_h100_H100_20261129-165150.*;
# fwd+bwd per layer on a real row): attention FA3 varlen 6.4 ms < FlexAttention FLASH 7.4 <
# FlexAttention/Triton 8.5 < FA2 varlen 10.9 (so only FA3 counts: "varlen_fa3"); delta scan
# FlashQLA 6.2 ms < fla 15.6. Same errors against fp32 for all. Architectures not listed
# (Ampere, Ada, untested Blackwell) keep FlexAttention/Triton and fla.
ATTN_PREFERENCE: dict[int, tuple[str, ...]] = {9: ("varlen_fa3", "flex_flash", "flex")}
DELTA_PREFERENCE: dict[int, tuple[str, ...]] = {9: ("qla", "fla")}
_BACKEND_OF = {"varlen_fa3": "varlen"}  # candidate name -> attn_backend value
PROBE_TOLERANCE = 2e-2  # relative L2 error vs fp32 allowed in a probe (bf16 kernels: ~3e-3)
_PROBES: dict = {}


def _rel_l2(x: Tensor, ref: Tensor) -> float:
    return ((x.float() - ref.float()).norm() / ref.float().norm().clamp_min(1e-30)).item()


def _attention_probe_case(device, n_head: int, head_dim: int):
    """A small row with a cached prefix: unused slots, an older document, the document the
    memory ended in (continued by the first queries), and documents of 1, 2 and more tokens."""
    T, past, window = 1024, 256, 300
    g = torch.Generator().manual_seed(0)
    starts = torch.zeros(T, dtype=torch.bool)
    starts[[130, 400, 401, 403, 777]] = True
    qdocs = starts.long().cumsum(0)[None]
    cache = torch.full((past,), EMPTY_DOC)
    cache[50:180], cache[180:] = -1, 0
    kdocs = torch.cat((cache[None], qdocs), dim=1)
    q = torch.randn(1, n_head, T, head_dim, generator=g)
    k, v = (torch.randn(1, 1, past + T, head_dim, generator=g) for _ in range(2))
    do = torch.randn(1, n_head, T, head_dim, generator=g)
    distance = (torch.arange(T) + past)[:, None] - torch.arange(past + T)
    mask = (distance >= 0) & (distance < window) & (qdocs[0, :, None] == kdocs[0, None, :])
    ref = [t.to(device).requires_grad_() for t in (q, k, v)]
    out = F.scaled_dot_product_attention(ref[0], *(t.expand(-1, n_head, -1, -1) for t in ref[1:]),
                                         attn_mask=mask.to(device), scale=0.1)
    out.backward(do.to(device))
    case = dict(qdocs=qdocs.to(device), kdocs=kdocs.to(device), window=window, past=past, T=T,
                inputs=[t.to(device, torch.bfloat16) for t in (q, k, v)], do=do.to(device, torch.bfloat16))
    return case, [out.detach()] + [t.grad for t in ref]


def _attention_errors(case, expected, attend) -> list[float]:
    """Relative L2 errors of out, dq, dk, dv against the fp32 reference."""
    inputs = [t.clone().requires_grad_() for t in case["inputs"]]
    out = attend(*inputs)
    out.backward(case["do"])
    return [_rel_l2(x, y) for x, y in zip([out] + [t.grad for t in inputs], expected)]


def _check_attention(case, expected, attend) -> tuple[bool, str]:
    errors = _attention_errors(case, expected, attend)
    return max(errors) < PROBE_TOLERANCE, "rel. L2 vs fp32 out/dq/dk/dv " + "/".join(f"{e:.1e}" for e in errors)


def _varlen_case_attend(case):
    def attend(q, k, v):
        cu_q, cu_k, meta = _varlen_layout(case["qdocs"], case["kdocs"], case["window"], case["past"])
        out, _ = _varlen_attn_fwd(q[0].transpose(0, 1), k[0].transpose(0, 1), v[0].transpose(0, 1),
                                  cu_q, cu_k, meta, 0.1)
        return out.transpose(0, 1).unsqueeze(0)
    return attend


def _probe_varlen(device, n_head, head_dim):
    """FA3 on Hopper when the flash_attn_3 wheel is installed (activated in torch's dispatcher
    for aten._flash_attention_*), else torch's built-in FA2."""
    import importlib.util
    from torch.nn import attention as nn_attention
    case, expected = _attention_probe_case(device, n_head, head_dim)
    attend = _varlen_case_attend(case)
    notes = []
    if (torch.cuda.get_device_capability(device)[0] == 9 and importlib.util.find_spec("flash_attn_interface")
            and hasattr(nn_attention, "activate_flash_attention_impl")):
        try:
            nn_attention.activate_flash_attention_impl("FA3")
            ok, note = _check_attention(case, expected, attend)
            if ok:
                return True, f"FA3 varlen ({note})"
            notes.append(f"FA3 rejected: {note}")
        except Exception as error:
            notes.append(f"FA3 rejected: {type(error).__name__}: {str(error)[:200]}")
        try:
            nn_attention.restore_flash_attention_impl()
        except Exception:
            pass
    ok, note = _check_attention(case, expected, attend)
    return ok, "; ".join(notes + [f"FA2 varlen ({note})"])


def _probe_flex_flash(device, n_head, head_dim):
    """FlexAttention's FLASH backend (FlashAttention-4, CuTe DSL; needs flash-attn-4) on the
    same block-sparse mask training builds."""
    if flex_attention is None or BlockMask is None:
        return False, "no FlexAttention"
    case, expected = _attention_probe_case(device, n_head, head_dim)
    qd, kd, past, window = case["qdocs"][0], case["kdocs"][0], case["past"], case["window"]

    def mask_mod(b, h, q_idx, kv_idx):
        q_pos = q_idx + past
        return (kv_idx <= q_pos) & (q_pos - kv_idx < window) & (qd[q_idx] == kd[kv_idx])
    block_mask = _aligned_window_block_mask(case["qdocs"], case["kdocs"], window, past, mask_mod)
    ok, note = _check_attention(case, expected, lambda q, k, v: _flex_attention(
        q, k, v, block_mask=block_mask, scale=0.1, kernel_options={"BACKEND": "FLASH"}, enable_gqa=True))
    return ok, f"FlexAttention FLASH ({note})"


def _probe_qla(device, n_head, head_dim):
    """FlashQLA on a 8192-token row (split into sub-sequences) against the fp32 PyTorch scan."""
    if head_dim != 128:
        return False, f"FlashQLA needs head_dim 128, got {head_dim}"
    if _flash_qla() is None:
        return False, f"flash_qla unavailable ({_QLA['error']})"
    T, H, D = 8192, n_head, head_dim
    g = torch.Generator().manual_seed(0)
    q, k = (F.normalize(torch.randn(1, T, H, D, generator=g), dim=-1) for _ in range(2))
    v = torch.randn(1, T, H, D, generator=g).tanh()
    half_lives = 65536.0 ** (torch.arange(H, dtype=torch.float64) / max(H - 1, 1))
    log_decay = -F.softplus(torch.randn(1, T, H, generator=g) + _half_life_bias(half_lives).float())
    log_decay[:, [1000, 5000]] += RESET_LOG_DECAY  # document starts
    beta = torch.sigmoid(torch.randn(1, T, H, generator=g))
    h0 = 0.1 * torch.randn(1, H, D, D, generator=g)
    do = torch.randn(1, T, H, D, generator=g)
    q, k, v = (t.to(device, torch.bfloat16) for t in (q, k, v))
    log_decay, beta, h0, do = (t.to(device) for t in (log_decay, beta, h0, do))
    results = []
    for scan in (_delta_scan_torch, _delta_scan_qla):
        inputs = [t.clone().requires_grad_() for t in (q, k, v, log_decay, beta)]
        out, final = scan(*inputs, h0)
        (out.float() * do).sum().backward()
        results.append([out, final] + [t.grad for t in inputs])
    errors = [_rel_l2(x, y) for x, y in zip(results[1], results[0])]
    note = "rel. L2 vs fp32 out/state/dq/dk/dv/dlog_decay/dbeta " + "/".join(f"{e:.1e}" for e in errors)
    return max(errors) < PROBE_TOLERANCE, f"FlashQLA, exact split ({note})"


def _probe_varlen_fa3(device, n_head, head_dim):
    """varlen only with FA3 (FA2 varlen is slower than FlexAttention on an H100)."""
    ok, note = probe_backend("varlen", device, n_head=n_head, head_dim=head_dim)
    return ok and note.startswith("FA3"), note


_PROBE_FNS = {
    "flex": lambda device, n_head, head_dim: (flex_attention is not None, "FlexAttention (Triton)"),
    "fla": lambda device, n_head, head_dim: (_fla_delta_rule is not None,
                                             "fla custom op" if _FLA_OP is not None else "fla entry point"),
    "varlen": _probe_varlen,
    "varlen_fa3": _probe_varlen_fa3,
    "flex_flash": _probe_flex_flash,
    "qla": _probe_qla,
}


def probe_backend(name: str, device, *, n_head: int, head_dim: int) -> tuple[bool, str]:
    """(usable, note) for one candidate kernel, checked once per process and shape."""
    key = (name, str(device), n_head, head_dim)
    if key not in _PROBES:
        if name not in _PROBE_FNS:
            raise ValueError(f"unknown backend {name!r}; known: {sorted(_PROBE_FNS)}")
        try:
            _PROBES[key] = _PROBE_FNS[name](torch.device(device), n_head, head_dim)
        except Exception as error:
            _PROBES[key] = (False, f"{type(error).__name__}: {str(error)[:300]}")
    return _PROBES[key]


# ----------------------------------------------------------------------------- model

class HybridGPT(nn.Module):
    def __init__(self, cfg: HybridConfig):
        super().__init__()
        if len(cfg.layout) != cfg.n_layer or set(cfg.layout) - set("-MAD"):
            raise ValueError("layout needs one of '-MAD' per layer")
        if not cfg.n_layer // 2 <= cfg.backout_layer < cfg.n_layer:
            raise ValueError("backout_layer must sit in the decoder half")
        if cfg.delta_reset not in ("hard", "none"):
            raise ValueError("delta_reset must be 'hard' or 'none'")
        if cfg.attn_window < 1:
            raise ValueError("attn_window must be positive")
        self.cfg = cfg
        d = cfg.n_embd
        self.num_encoder_layers = cfg.n_layer // 2
        num_decoder = cfg.n_layer - self.num_encoder_layers
        self.skip_weights = nn.Parameter(torch.ones(num_decoder))
        # Routed skips: a token-dependent convex mix of all encoder outputs (softmax, so
        # its size is bounded by theirs), scaled by skip_mix. skip_mix starts at 0: exact U-Net.
        if cfg.routed_skips:
            self.skip_routers = nn.ModuleList(CastedLinear(d, self.num_encoder_layers) for _ in range(num_decoder))
            self.skip_mix = nn.Parameter(torch.zeros(num_decoder))
        else:
            self.skip_routers = self.skip_mix = None

        self.rotary = Rotary(d // cfg.n_head)
        self.ve_layout = value_embed_layout(cfg.n_layer)
        self.slots = []  # index into HybridMemory.delta / .attn for each layer
        counts = {"A": 0, "D": 0}
        for kind in cfg.layout:
            self.slots.append(counts[kind] if kind in counts else None)
            if kind in counts:
                counts[kind] += 1
        self.n_delta, self.n_attn = counts["D"], counts["A"]
        self.transformer = nn.ModuleDict(dict(
            wte=nn.Embedding(cfg.vocab_size, d),
            h=nn.ModuleList(
                Block(cfg, kind, self.ve_layout[i] is not None, self.slots[i], self.n_delta)
                for i, kind in enumerate(cfg.layout)
            ),
        ))
        self.lm_head = CastedLinear(d, cfg.vocab_size)
        self.lm_bias = nn.Parameter(torch.zeros(cfg.vocab_size))  # see init_output_prior
        self.smear_gate = CastedLinear(12, 1)
        self.value_embeds = nn.ModuleList(nn.Embedding(cfg.vocab_size, d) for _ in range(3))
        self.smear_lambda = nn.Parameter(torch.zeros(1))
        self.backout_lambda = nn.Parameter(0.5 * torch.ones(1))
        # "auto": auto_attn_backend on CUDA if T >= FLEX_MIN_QUERIES, else dense; or force one
        # of "flex" (Triton), "flex_flash" (FA4), "varlen" (FA2/FA3; one row), "dense"
        self.attn_backend = "auto"
        self.auto_attn_backend = "flex"  # select_backends may pick another
        # Tokens per chunk in the fused loss. Every chunk adds a [V, d] fp32 round trip for the
        # head gradient, so fewer, larger chunks are faster; 8192 holds ~0.8 GB of bf16 logits.
        self.loss_chunk = 8192

    # --- setup helpers

    def timescale_parameters(self):
        return [b.delta.decay_bias for b in self.transformer.h if b.delta is not None]

    def to_bf16_training(self):
        """Cast parameters to bf16 for training, except the timescale biases, which stay
        fp32: near -11 a bf16 ulp is 0.06, so small Adam steps on them would round away."""
        timescales = [(p, p.detach().float().clone()) for p in self.timescale_parameters()]
        self.bfloat16()
        for p, exact in timescales:  # restore the exact fp32 values, not a bf16 round trip
            p.data = exact.to(p.device)
        return self

    @torch.no_grad()
    def init_output_prior(self, counts: Tensor, smoothing: float = 0.5):
        """Start the (post-softcap) vocabulary bias at centered log unigram frequencies."""
        log_prior = (counts.double().cpu() + smoothing).log()
        self.lm_bias.copy_((log_prior - log_prior.mean()).to(self.lm_bias))

    def select_backends(self, device=None, *, attention=None, delta=None) -> dict:
        """Choose the kernels for "auto" on this GPU: the first candidate of the preference
        list for its architecture (or the given ones) that is installed and passes a small
        numerical check against an fp32 reference (probe_backend). Anything that fails falls
        back to the previous kernels (FlexAttention/Triton, fla), and other GPUs keep them.
        Parameters, checkpoints and the computed function are unchanged; only the kernels
        differ. Call it once, eagerly, before torch.compile. Returns what was chosen and why
        the rest was not."""
        device = torch.device(device) if device is not None else next(self.parameters()).device
        report = {"attention": "flex", "delta": "fla", "rejected": {}}
        if device.type != "cuda":
            self.auto_attn_backend = "flex"
            for b in self.transformer.h:
                if b.delta is not None:
                    b.delta.auto_backend = "fla"
            return {"attention": "dense (cpu)", "delta": "torch (cpu)", "rejected": {}}
        major = torch.cuda.get_device_capability(device)[0]
        attention = ATTN_PREFERENCE.get(major, ("flex",)) if attention is None else tuple(attention)
        delta = DELTA_PREFERENCE.get(major, ("fla",)) if delta is None else tuple(delta)
        heads, head_dim = self.cfg.delta_heads, self.cfg.delta_head_dim
        for name in attention:
            ok, note = probe_backend(name, device, n_head=self.cfg.n_head, head_dim=self.cfg.n_embd // self.cfg.n_head)
            if ok:
                report["attention"], report["attention_kernels"] = _BACKEND_OF.get(name, name), note
                break
            report["rejected"][name] = note
        for name in delta:
            ok, note = probe_backend(name, device, n_head=heads, head_dim=head_dim)
            if ok:
                report["delta"], report["delta_kernels"] = name, note
                break
            report["rejected"][name] = note
        self.auto_attn_backend = report["attention"]
        for b in self.transformer.h:
            if b.delta is not None:
                b.delta.auto_backend = report["delta"]
        return report

    def init_memory(self, batch: int, device) -> HybridMemory:
        cfg = self.cfg
        dtype = self.transformer.wte.weight.dtype
        state_dtype = torch.promote_types(dtype, torch.float32)
        H, D, d, W = cfg.delta_heads, cfg.delta_head_dim, cfg.n_embd, cfg.attn_window
        head_dim = d // cfg.n_head
        zeros = lambda *shape, dt=dtype: torch.zeros(*shape, device=device, dtype=dt)
        return HybridMemory(
            delta=tuple(DeltaCarry(zeros(batch, H, D, D, dt=state_dtype), zeros(batch, d)) for _ in range(self.n_delta)),
            attn=tuple(KVCarry(zeros(batch, W, head_dim), zeros(batch, W, head_dim)) for _ in range(self.n_attn)),
            docs=torch.full((batch, W), EMPTY_DOC, device=device, dtype=torch.long),
            prev_token=zeros(batch, dt=torch.long),
            has_prev=zeros(batch, dt=torch.bool),
        )

    # --- forward

    def _attention(self, qdocs: Tensor, kdocs: Tensor, window, T: int, past: int):
        """Causal, same-document, sliding-window attention over past + T keys. Every backend
        computes the same attention; they differ in kernels only (select_backends)."""
        scale, opts = 0.1, self.cfg.flex_kernel_options
        backend = self.attn_backend
        if backend not in ATTN_BACKENDS:
            raise ValueError(f"attn_backend must be one of {ATTN_BACKENDS}, got {backend!r}")
        flex_ok = flex_attention is not None
        if backend == "auto":
            backend = self.auto_attn_backend if qdocs.is_cuda and T >= FLEX_MIN_QUERIES else "dense"
            if backend == "varlen" and qdocs.size(0) > 1:
                backend = "flex"
            if backend in ("flex", "flex_flash") and not flex_ok:
                backend = "dense"
        elif backend == "varlen" and (qdocs.size(0) > 1 or not qdocs.is_cuda):
            backend = "flex" if qdocs.is_cuda and flex_ok else "dense"  # varlen: one CUDA row
        if backend in ("flex", "flex_flash") and not flex_ok:
            raise RuntimeError(f"attn_backend={backend!r} needs FlexAttention (torch.nn.attention.flex_attention)")
        if backend == "varlen":
            cu_q, cu_k, meta = _varlen_layout(qdocs, kdocs, window, past)

            def varlen(q, k, v):  # [1, H, L, D] views in and out
                out, _ = _varlen_attn_fwd(q[0].transpose(0, 1), k[0].transpose(0, 1), v[0].transpose(0, 1),
                                          cu_q, cu_k, meta, scale)
                return out.transpose(0, 1).unsqueeze(0)
            return varlen
        if backend == "flex_flash":  # FlexAttention lowered to FlashAttention-4 (CuTe DSL)
            opts = {**(opts or {}), "BACKEND": "FLASH"}
        if backend in ("flex", "flex_flash"):
            if qdocs.size(0) == 1:
                qd, kd = qdocs[0], kdocs[0]

                def mask_mod(b, h, q_idx, kv_idx):
                    q_pos = q_idx + past
                    return (kv_idx <= q_pos) & (q_pos - kv_idx < window) & (qd[q_idx] == kd[kv_idx])
            else:
                def mask_mod(b, h, q_idx, kv_idx):
                    q_pos = q_idx + past
                    return (kv_idx <= q_pos) & (q_pos - kv_idx < window) & (qdocs[b, q_idx] == kdocs[b, kv_idx])
            if T >= 65536 and T % FLEX_BLOCK_SIZE == 0 and past % FLEX_BLOCK_SIZE == 0:
                block_mask = _aligned_window_block_mask(qdocs, kdocs, window, past, mask_mod)
            else:
                block_mask = _create_block_mask(mask_mod, qdocs.size(0), None, T, past + T,
                                                device=qdocs.device, _compile=True)
            return lambda q, k, v: _flex_attention(q, k, v, block_mask=block_mask, scale=scale,
                                                   kernel_options=opts, enable_gqa=True)
        diff = (torch.arange(T, device=qdocs.device) + past)[:, None] - torch.arange(past + T, device=qdocs.device)
        mask = (diff >= 0) & (diff < window) & (qdocs[:, :, None] == kdocs[:, None, :])

        def dense(q, k, v):
            k, v = (t.expand(-1, q.size(1), -1, -1) for t in (k, v))
            return F.scaled_dot_product_attention(q, k, v, attn_mask=mask[:, None], scale=scale)
        return dense

    def _skip(self, i: int, x: Tensor, skips: list[Tensor]) -> Tensor:
        out = self.skip_weights[i] * skips[-1 - i]  # U-Net mirror
        if self.skip_routers is not None:
            weights = self.skip_routers[i](norm(x)).float().softmax(-1).to(x.dtype)
            mix = sum(weights[..., e:e + 1] * s for e, s in enumerate(skips))
            out = out + self.skip_mix[i] * mix
        return out

    def forward(self, idx: Tensor, target: Tensor | None = None, attn_blocksize=None,
                memory: HybridMemory | None = None, return_memory: bool = False,
                last_only: bool = False):
        """idx [T] (one packed row) or [B, T]. Returns the loss when target is
        given, else logits; with return_memory also the HybridMemory for the next chunk.
        attn_blocksize: attention window (int or 0-d tensor) in [1, cfg.attn_window], default
        cfg.attn_window.
        last_only: logits for the last position only ([B, 1, V], or [1, V] packed), so a
        long prompt never holds [T, vocab] logits (generate's prefill). Ignored with target."""
        packed = idx.ndim == 1
        if packed:
            idx = idx[None]
            target = None if target is None else target[None]
        B, T = idx.shape
        if return_memory and memory is None:
            memory = self.init_memory(B, idx.device)
        doc_start = idx == self.cfg.eos_token
        # Doc ids for the attention mask; 0 = the document the carried memory ended in.
        qdocs = doc_start.cumsum(-1) if self.cfg.attn_doc_mask else torch.zeros_like(idx)
        if memory is None:
            kdocs, past = qdocs, 0
        else:
            kdocs, past = torch.cat((memory.docs, qdocs), dim=1), memory.docs.size(1)
        window = self.cfg.attn_window if attn_blocksize is None else attn_blocksize
        # A window beyond the cache would read keys that streaming (memory, generate) has
        # already dropped, so chunked and whole-stream logits would silently differ.
        limit = self.cfg.attn_window
        if isinstance(window, Tensor):  # checked on device: no host sync
            torch._assert_async((window >= 1) & (window <= limit),
                                f"attention window must be in [1, attn_window={limit}]")
        elif not 1 <= window <= limit:
            raise ValueError(f"attention window {window} must be in [1, attn_window={limit}]")
        attend = self._attention(qdocs, kdocs, window, T, past)
        x = self.transformer.wte(idx)
        rope = self.rotary.tables(past + T, idx.device, x.dtype)

        # Smear in the previous token (the carried one at t = 0); with attn_doc_mask,
        # never into a doc start.
        if memory is None:
            first, has_first = torch.zeros_like(x[:, 0]), torch.zeros_like(doc_start[:, 0])
        else:
            first, has_first = self.transformer.wte(memory.prev_token), memory.has_prev
        previous = torch.cat((first.unsqueeze(1), x[:, :-1]), dim=1)
        allowed = torch.cat((has_first.unsqueeze(1), torch.ones_like(doc_start[:, 1:])), dim=1)
        if self.cfg.attn_doc_mask:
            allowed = allowed & ~doc_start
        gate = self.smear_lambda * torch.sigmoid(self.smear_gate(x[..., :12])) * allowed.unsqueeze(-1)
        x = norm(x + gate * previous)
        x0, v1 = x, None
        ve = [emb(idx) for emb in self.value_embeds]
        reset = doc_start if self.cfg.delta_reset == "hard" else None

        carries = {"D": [None] * self.n_delta, "A": [None] * self.n_attn}
        if memory is not None:
            carries = {"D": list(memory.delta), "A": list(memory.attn)}
        skips, x_backout, c = [], None, torch.ones((), device=x.device, dtype=x.dtype)
        for i, block in enumerate(self.transformer.h):
            if i >= self.num_encoder_layers:
                x = x + self._skip(i - self.num_encoder_layers, x, skips)
            kind, slot, j = self.cfg.layout[i], self.slots[i], self.ve_layout[i]
            carry = carries[kind][slot] if slot is not None else None
            x, v1, carry, c = block(x, x0, None if j is None else ve[j], v1, attend, rope, carry, reset, c)
            if slot is not None:
                carries[kind][slot] = carry
            if i < self.num_encoder_layers:
                skips.append(x)
            if i == self.cfg.backout_layer:
                x_backout = x
        x = x - self.backout_lambda * x_backout

        x = norm(x)
        if target is not None:  # training/eval loss: no [T, vocab] logits tensor
            out = softcap_cross_entropy(x.flatten(0, 1), self.lm_head.weight, self.lm_bias,
                                        target.reshape(-1), self.loss_chunk)
        else:
            h = x[:, -1:] if last_only else x
            logits = 30 * torch.tanh(self.lm_head(h) / 30) + self.lm_bias.to(x.dtype)
            out = logits[0] if packed else logits
        if not return_memory:
            return out
        W = memory.docs.size(1)
        docs = kdocs[:, -W:]
        docs = torch.where(docs > EMPTY_DOC // 2, docs - qdocs[:, -1:], docs)
        new_memory = HybridMemory(
            tuple(carries["D"]), tuple(carries["A"]), docs,
            idx[:, -1].clone(), torch.ones_like(memory.has_prev),
        )
        return out, new_memory

    @torch.no_grad()
    def generate(self, prompt: Tensor, max_new_tokens: int, *, temperature: float = 1.0,
                 top_k: int | None = None, memory: HybridMemory | None = None,
                 attn_blocksize=None, generator: torch.Generator | None = None):
        """Sample after prompt [B, T] (or [T]) with constant memory per sequence.
        temperature 0 is greedy. Pass the returned memory back in to continue."""
        squeeze = prompt.ndim == 1
        prompt = prompt[None] if squeeze else prompt
        logits, memory = self(prompt, attn_blocksize=attn_blocksize, memory=memory,
                              return_memory=True, last_only=True)
        tokens = []
        for _ in range(max_new_tokens):
            last = logits[:, -1].float()
            if temperature == 0:
                token = last.argmax(-1)
            else:
                last = last / temperature
                if top_k is not None:
                    cutoff = last.topk(min(top_k, last.size(-1)), dim=-1).values[:, -1:]
                    last = last.masked_fill(last < cutoff, -torch.inf)
                token = torch.multinomial(last.softmax(-1), 1, generator=generator)[:, 0]
            tokens.append(token)
            logits, memory = self(token[:, None], attn_blocksize=attn_blocksize, memory=memory,
                                  return_memory=True, last_only=True)
        out = torch.stack(tokens, 1) if tokens else prompt.new_zeros(prompt.size(0), 0)
        return (out[0] if squeeze else out), memory


# ----------------------------------------------------------------------------- optimizers

def zeropower_via_newtonschulz5(G, steps=5, eps=1e-7, dtype=torch.bfloat16):
    """Approximately orthogonalize G [m, n], or each matrix of a batch [..., m, n] (each
    normalized by its own norm), with a quintic Newton-Schulz iteration in dtype."""
    X = G.to(dtype)
    X = X / (X.norm(dim=(-2, -1), keepdim=True) + eps)
    transposed = G.size(-2) > G.size(-1)
    if transposed:
        X = X.mT
    a, b, c = (3.4445, -4.7750, 2.0315)
    for _ in range(steps):
        A = X @ X.mT
        B = b * A + c * A @ A
        X = a * X + B @ X
    return X.mT if transposed else X


def _orthogonalize(updates: list[Tensor], ns, steps: int) -> list[Tensor]:
    """ns on every matrix, one call per shape: matrices of the same shape (tall ones
    transposed to wide) are stacked, instead of one call per matrix. Per-matrix overhead
    (Python, kernel launches, tiny gate matrices) was most of the Muon step."""
    groups = {}
    for i, u in enumerate(updates):
        groups.setdefault((min(u.shape), max(u.shape)), []).append(i)
    out = [None] * len(updates)
    for idxs in groups.values():
        tall = [updates[i].size(0) > updates[i].size(1) for i in idxs]
        orth = ns(torch.stack([updates[i].T if t else updates[i] for i, t in zip(idxs, tall)]), steps=steps)
        for i, t, o in zip(idxs, tall, orth):
            out[i] = (o.T if t else o).to(updates[i].dtype)
    return out


class Muon(torch.optim.Optimizer):
    """Muon: Nesterov momentum with Newton-Schulz orthogonalized updates, for 2D matrices."""

    def __init__(self, params, lr=0.02, momentum=0.95, nesterov=True, backend_steps=5, ns=zeropower_via_newtonschulz5):
        super().__init__(params, dict(lr=lr, momentum=momentum, nesterov=nesterov, backend_steps=backend_steps))
        self.ns = ns

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            params = [p for p in group["params"] if p.grad is not None]
            if not params:
                continue
            grads, bufs, scales = [], [], []
            for p in params:
                state = self.state[p]
                if "momentum_buffer" not in state:
                    state["momentum_buffer"] = torch.zeros_like(p.grad)
                    state["scale"] = max(1.0, p.size(0) / p.size(1)) ** 0.5
                grads.append(p.grad)
                bufs.append(state["momentum_buffer"])
                scales.append(state["scale"])
            torch._foreach_mul_(bufs, group["momentum"])
            torch._foreach_add_(bufs, grads)
            updates = torch._foreach_add(grads, bufs, alpha=group["momentum"]) if group["nesterov"] else bufs
            updates = _orthogonalize(updates, self.ns, group["backend_steps"])
            torch._foreach_mul_(updates, scales)
            torch._foreach_add_(params, updates, alpha=-group["lr"])


def build_optimizers(model: HybridGPT, *, timescale_lr: float = 0.005, compile_ns: bool = True):
    """Adam for embeddings, head and scalars, Muon for 2D matrices, and a slow Adam group
    for the delta timescale biases (decay_bias). The token-dependent part of the decay
    gate (DeltaMixer.c_gate) is a 2D matrix and trains with Muon.
    Order: [embeddings, head, matrices (Muon), scalars(, timescales)]."""
    fused = next(model.parameters()).is_cuda
    embed = [model.transformer.wte.weight] + [e.weight for e in model.value_embeds]
    head = [model.lm_head.weight, model.lm_bias]
    timescale = model.timescale_parameters()
    special = {id(p) for p in embed + head + timescale}
    rest = [p for p in model.parameters() if id(p) not in special]
    matrix = [p for p in rest if p.ndim == 2]
    scalar = [p for p in rest if p.ndim < 2]
    # dynamic=False: one specialized kernel per (batch, m, n) group (a handful of shapes).
    ns = torch.compile(zeropower_via_newtonschulz5, dynamic=False) if compile_ns else zeropower_via_newtonschulz5
    adam = lambda params, lr: torch.optim.Adam(params, lr=lr, betas=(0.8, 0.95), fused=fused)
    optimizers = [
        adam(embed, 0.6),
        adam(head, 0.008),
        Muon(matrix, lr=0.05, momentum=0.95, ns=ns),
        adam(scalar, 0.04),
    ]
    if timescale:  # no delta layers: no timescale group
        optimizers.append(adam(timescale, timescale_lr))
    return optimizers