File size: 79,820 Bytes
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
49be061
e4bde99
49be061
 
 
 
e4bde99
49be061
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
49be061
e4bde99
49be061
e4bde99
49be061
 
e4bde99
 
 
49be061
 
e4bde99
 
 
 
 
49be061
 
e4bde99
 
 
49be061
e4bde99
49be061
e4bde99
 
 
 
49be061
 
 
e4bde99
 
 
49be061
 
e4bde99
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
49be061
e4bde99
 
 
49be061
 
e4bde99
49be061
e4bde99
49be061
e4bde99
 
 
 
 
49be061
 
e4bde99
49be061
 
e4bde99
49be061
e4bde99
 
 
49be061
 
 
e4bde99
49be061
 
e4bde99
 
49be061
 
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ace89be
 
 
 
e4bde99
49be061
 
e4bde99
 
49be061
e4bde99
 
 
49be061
 
 
e4bde99
 
49be061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4bde99
49be061
 
 
e4bde99
 
 
 
 
 
 
49be061
5f3021d
 
 
 
49be061
 
5f3021d
 
 
 
 
 
 
e4bde99
49be061
 
e4bde99
 
49be061
 
e4bde99
49be061
 
e4bde99
49be061
 
 
e4bde99
49be061
 
e4bde99
5f3021d
 
 
49be061
5f3021d
 
e4bde99
49be061
 
 
 
5f3021d
e4bde99
5f3021d
49be061
 
 
 
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
 
 
 
 
 
e4bde99
49be061
 
e4bde99
 
 
49be061
 
 
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
49be061
 
e4bde99
 
 
 
49be061
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
49be061
 
e4bde99
 
 
 
49be061
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
49be061
 
e4bde99
49be061
 
e4bde99
 
 
 
 
49be061
 
e4bde99
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
49be061
 
 
e4bde99
 
 
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
 
 
 
 
49be061
 
 
 
 
 
e4bde99
 
49be061
e4bde99
49be061
 
 
 
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
 
 
 
e4bde99
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
49be061
 
 
 
e4bde99
49be061
e4bde99
 
 
 
49be061
e4bde99
 
 
 
49be061
 
 
 
 
e4bde99
 
 
 
 
49be061
 
 
e4bde99
49be061
e4bde99
49be061
 
 
 
 
 
e4bde99
49be061
 
 
 
 
e4bde99
 
49be061
e4bde99
 
 
49be061
 
e4bde99
49be061
e4bde99
 
 
 
 
49be061
e4bde99
 
 
 
49be061
 
e4bde99
 
49be061
e4bde99
49be061
 
 
 
 
 
 
 
 
 
 
e4bde99
 
49be061
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
49be061
e4bde99
49be061
 
 
 
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
49be061
 
 
 
e4bde99
 
49be061
e4bde99
 
49be061
 
 
e4bde99
49be061
 
 
e4bde99
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
 
 
 
 
e4bde99
 
 
 
 
 
49be061
 
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
49be061
e4bde99
49be061
e4bde99
49be061
 
e4bde99
 
 
 
49be061
e4bde99
49be061
 
 
 
 
 
e4bde99
 
 
 
 
 
49be061
 
 
 
e4bde99
49be061
 
 
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
49be061
e4bde99
 
 
 
49be061
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
49be061
e4bde99
49be061
 
 
e4bde99
 
49be061
 
e4bde99
 
 
49be061
 
e4bde99
49be061
e4bde99
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
49be061
e4bde99
49be061
 
 
e4bde99
 
 
 
49be061
 
e4bde99
 
 
 
49be061
 
 
e4bde99
 
 
 
 
 
 
 
49be061
 
e4bde99
 
 
 
49be061
 
 
 
e4bde99
 
 
49be061
e4bde99
49be061
e4bde99
 
49be061
 
 
 
 
 
 
e4bde99
 
 
 
49be061
e4bde99
 
 
49be061
e4bde99
49be061
e4bde99
49be061
e4bde99
49be061
e4bde99
 
 
49be061
e4bde99
 
49be061
e4bde99
49be061
 
 
 
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
49be061
 
 
e4bde99
 
 
49be061
 
 
e4bde99
 
 
49be061
 
 
e4bde99
49be061
 
 
 
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
49be061
 
 
 
e4bde99
49be061
e4bde99
 
 
 
 
 
49be061
 
 
e4bde99
 
49be061
 
e4bde99
49be061
 
 
e4bde99
 
49be061
e4bde99
49be061
 
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
 
 
 
 
 
 
 
49be061
e4bde99
 
49be061
e4bde99
 
49be061
e4bde99
49be061
 
 
 
e4bde99
 
49be061
 
 
 
e4bde99
49be061
 
 
 
e4bde99
49be061
 
 
 
e4bde99
 
49be061
 
 
e4bde99
 
 
 
 
 
 
 
 
 
49be061
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
 
49be061
 
 
e4bde99
 
 
49be061
e4bde99
49be061
e4bde99
 
 
 
49be061
 
 
e4bde99
 
 
 
 
 
 
 
49be061
 
 
 
 
 
 
e4bde99
49be061
e4bde99
 
49be061
 
 
 
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
49be061
e4bde99
49be061
 
 
 
e4bde99
49be061
e4bde99
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
49be061
 
 
e4bde99
49be061
e4bde99
 
49be061
e4bde99
 
 
49be061
 
e4bde99
 
49be061
e4bde99
 
 
49be061
e4bde99
 
49be061
 
 
 
 
 
e4bde99
49be061
e4bde99
 
 
 
49be061
e4bde99
49be061
 
e4bde99
 
 
 
49be061
 
 
e4bde99
49be061
e4bde99
49be061
e4bde99
49be061
e4bde99
 
 
49be061
 
e4bde99
 
 
 
 
49be061
e4bde99
 
49be061
 
e4bde99
49be061
e4bde99
49be061
 
e4bde99
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
49be061
e4bde99
 
 
 
 
 
 
 
 
 
 
49be061
 
e4bde99
 
 
 
 
 
 
 
 
 
 
 
 
49be061
e4bde99
49be061
e4bde99
 
 
 
 
 
49be061
e4bde99
49be061
 
e4bde99
 
 
 
 
 
 
 
49be061
 
 
e4bde99
49be061
 
 
 
 
 
 
 
 
 
 
 
 
e4bde99
49be061
 
e4bde99
 
 
 
 
 
49be061
 
 
e4bde99
49be061
e4bde99
49be061
e4bde99
49be061
 
 
 
 
 
 
 
 
 
e4bde99
49be061
 
e4bde99
 
 
 
 
49be061
 
 
 
e4bde99
49be061
e4bde99
49be061
 
 
 
 
 
 
 
e4bde99
 
49be061
 
e4bde99
 
 
 
 
 
49be061
e4bde99
49be061
 
e4bde99
 
 
 
 
49be061
e4bde99
 
 
49be061
e4bde99
 
 
49be061
e4bde99
 
49be061
 
 
e4bde99
 
 
49be061
 
 
 
 
 
 
 
 
e4bde99
 
 
 
 
49be061
 
e4bde99
49be061
e4bde99
 
49be061
 
e4bde99
 
 
49be061
e4bde99
 
49be061
 
e4bde99
 
49be061
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
49be061
e4bde99
49be061
 
 
 
e4bde99
49be061
e4bde99
 
 
49be061
e4bde99
 
49be061
 
e4bde99
 
 
 
 
49be061
e4bde99
 
49be061
 
 
 
 
e4bde99
 
 
 
 
 
 
49be061
 
 
e4bde99
 
49be061
e4bde99
49be061
e4bde99
 
 
 
49be061
 
e4bde99
 
 
49be061
 
eb7c19d
 
 
 
 
 
 
 
 
e4bde99
 
 
 
49be061
e4bde99
 
db19a5f
49be061
 
db19a5f
49be061
 
e4bde99
49be061
 
e4bde99
49be061
 
 
 
 
 
 
 
 
 
e4bde99
 
49be061
 
 
 
 
 
 
 
 
e4bde99
 
 
 
 
 
49be061
 
e4bde99
 
 
49be061
e4bde99
 
 
 
49be061
e4bde99
 
 
 
 
49be061
e4bde99
49be061
 
 
e4bde99
 
49be061
 
 
e4bde99
 
 
 
 
 
 
 
 
 
49be061
 
e4bde99
49be061
e4bde99
 
 
 
 
49be061
 
 
 
 
e4bde99
 
 
 
 
 
49be061
 
e4bde99
 
 
49be061
e4bde99
49be061
e4bde99
49be061
 
 
 
 
 
 
 
e4bde99
49be061
e4bde99
 
49be061
 
 
e4bde99
 
49be061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
49be061
e4bde99
49be061
 
 
 
 
 
e4bde99
49be061
 
e4bde99
49be061
e4bde99
49be061
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4bde99
 
 
 
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
"""
CascadeFormer  Β·  SmilyAI 3rd Gen Assistant
Heterogeneous Mixture-of-Experts Transformer β€” TRITON KERNEL EDITION (v3, speed patch)

Same architecture as before, but:
  - RMSNorm -> fused triton kernel (fwd+bwd)
  - RoPE -> fused triton kernel (fwd+bwd)
  - Attention -> fused triton flash-attn w/ window support (fwd triton, bwd via flex_attention block mask)
    * v2: fixed -inf/-inf NaN edge case in softmax online-max init (NEG_INF sentinel)
    * v3: bwd swapped from dense SDPA mask -> flex_attention block_mask (skips masked blocks)
  - MoE expert dispatch -> grouped-GEMM triton kernel (no more per-expert python loop)
    * v3: dW (weight-grad) path also moved off the per-expert python loop onto a
          fused atomic-accumulate triton kernel (_moe_dw_kernel)
    * v3: forward/dW GEMMs autotuned over BLOCK_N/BLOCK_K/warps/stages β€” BLOCK_M is
          NOT autotuned since it's tied to the block-aligned token layout from
          moe_align_block_size; changing it there without changing block_m would
          silently misalign expert boundaries and corrupt gradients.
  - Muon -> extended to handle 3D fused expert weight tensors

HOW TO RUN (for hugging-science):
  Set these environment variables before launching:

    export HF_TOKEN=your_hf_token_here
    export HF_USERNAME=hugging-science
    export CASCADEFORMER_SESSION_ID=3
    export HF_MODEL_REPO_BASE=hugging-science/cascadeformer
    export HF_DATASET_REPO=Bc-AI/CodVa-1-Pretrain-20B

  Then: python train.py

METRICS:
  A metrics_session{N}.jsonl file is written locally and uploaded to the HF
  checkpoint repo every 15 min. Pull it any time to check training progress.
  Each line is a JSON object with kind="train"|"val"|"ckpt"|"final".

TIME BUDGET:
  MAX_TRAINING_HOURS = 53.0 (~54h32m total, leaving ~1.5h buffer for cleanup)

SESSION NOTES:
  Session 3 = fresh pretrain on Bc-AI/CodVa-1-Pretrain-20B corpus.
  To resume within session 3, uncomment the checkpoint resume block in train().
  Old session repos (1, 2) are auto-deleted after session 3 starts.

ARCHITECTURE NOTE:
  If resuming from a checkpoint saved with the OLD (non-fused) architecture,
  MoE expert weights will NOT match key names and will silently stay randomly
  initialized (load_state_dict uses strict=False). Session 3 starts clean.
"""

import os
import gc
import json
import time
import math
import random
import logging
from dataclasses import dataclass, asdict
from typing import Optional, List

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader

try:
    import triton
    import triton.language as tl
    HAS_TRITON = True
except ImportError:
    HAS_TRITON = False
    raise RuntimeError(
        "triton is required. pip install triton or use a torch build that ships it."
    )

try:
    from torch.nn.attention.flex_attention import flex_attention, create_block_mask
    HAS_FLEX_ATTN = True
except ImportError:
    HAS_FLEX_ATTN = False

from huggingface_hub import HfApi, hf_hub_download, upload_file
from huggingface_hub import login as hf_login

try:
    import bitsandbytes as bnb
    HAS_BNB = True
    print("bitsandbytes: ON")
except ImportError:
    HAS_BNB = False

try:
    from safetensors.torch import save_file as st_save
    HAS_ST = True
    print("safetensors: ON")
except ImportError:
    HAS_ST = False

try:
    from torchao.float8 import convert_to_float8_training, Float8LinearConfig
    HAS_TORCHAO = True
    print("torchao fp8: ON")
except ImportError:
    HAS_TORCHAO = False

os.environ["CUDA_DEVICE_ORDER"]      = "PCI_BUS_ID"
os.environ["TOKENIZERS_PARALLELISM"] = "false"
torch.set_float32_matmul_precision("high")
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32       = True
torch.backends.cudnn.benchmark        = True

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger("cascadeformer")

if not HAS_FLEX_ATTN:
    log.warning(
        "[attn] flex_attention not available (needs torch>=2.5) β€” "
        "attention backward will fail. Upgrade torch."
    )

# ══════════════════════════════════════════════════════════════════════════════
#  HUGGINGFACE HUB SETUP
# ══════════════════════════════════════════════════════════════════════════════
HF_TOKEN    = os.environ.get("HF_TOKEN", "")
HF_USERNAME = os.environ.get("HF_USERNAME", "hugging-science")

HF_DATASET_REPO = os.environ.get("HF_DATASET_REPO", "Bc-AI/CodVa-1-Pretrain-20B")

SESSION_ID          = int(os.environ.get("CASCADEFORMER_SESSION_ID", "3"))
HF_MODEL_REPO_BASE  = os.environ.get("HF_MODEL_REPO_BASE", "hugging-science/cascadeformer")
HF_MODEL_REPO       = f"{HF_MODEL_REPO_BASE}-session-{SESSION_ID:03d}"

if not HF_TOKEN:
    log.warning(
        "[hf] HF_TOKEN env var not set β€” uploads/downloads will fail. "
        "Set it with:  export HF_TOKEN=your_token"
    )
else:
    try:
        hf_login(token=HF_TOKEN)
        log.info(f"[hf] logged in | user={HF_USERNAME}")
    except Exception as e:
        log.warning(f"[hf] login failed: {e}")

hf_api = HfApi()

LOCAL_CACHE   = "/tmp/cascadeformer_cache"
TEMP_CKPT_DIR = "/tmp/cascadeformer_ckpts"
os.makedirs(LOCAL_CACHE,   exist_ok=True)
os.makedirs(TEMP_CKPT_DIR, exist_ok=True)

log.info(f"[session] ID={SESSION_ID}  ckpt_repo={HF_MODEL_REPO}  data={HF_DATASET_REPO}")


def ensure_session_repo_exists():
    try:
        hf_api.repo_info(repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN)
        log.info(f"[hf] repo {HF_MODEL_REPO} already exists")
    except Exception:
        try:
            hf_api.create_repo(
                repo_id=HF_MODEL_REPO, repo_type="model",
                private=False, token=HF_TOKEN,
            )
            log.info(f"[hf] created repo {HF_MODEL_REPO}")
        except Exception as e:
            log.error(f"[hf] could not create repo: {e}")


def delete_old_session_repos(keep_last_n: int = 2):
    if SESSION_ID <= keep_last_n:
        return
    for old in range(1, SESSION_ID - keep_last_n + 1):
        repo = f"{HF_MODEL_REPO_BASE}-session-{old:03d}"
        try:
            hf_api.delete_repo(repo_id=repo, repo_type="model", token=HF_TOKEN)
            log.info(f"[hf] deleted old session repo: {repo}")
        except Exception as e:
            log.debug(f"[hf] could not delete {repo}: {e}")


def download_dataset_file(filename: str, cache_dir: str = LOCAL_CACHE) -> str:
    path = hf_hub_download(
        repo_id=HF_DATASET_REPO, filename=filename,
        repo_type="dataset", cache_dir=cache_dir, token=HF_TOKEN,
    )
    log.info(f"[hf] downloaded dataset file: {filename}")
    return path


def upload_to_hf(local_path: str, remote_filename: str) -> bool:
    """Upload any local file to the session checkpoint repo."""
    try:
        upload_file(
            path_or_fileobj=local_path,
            path_in_repo=remote_filename,
            repo_id=HF_MODEL_REPO,
            repo_type="model",
            token=HF_TOKEN,
        )
        log.info(f"[hf] uploaded {remote_filename}")
        return True
    except Exception as e:
        log.error(f"[hf] upload failed ({remote_filename}): {e}")
        return False


def list_hf_checkpoints() -> List[str]:
    try:
        files = hf_api.list_repo_files(
            repo_id=HF_MODEL_REPO, repo_type="model", token=HF_TOKEN
        )
        ckpts = [f for f in files if f.endswith(".model.pt")]
        return sorted(
            ckpts,
            key=lambda x: int(x.split("_s")[-1].split(".")[0]) if "_s" in x else 0,
        )
    except Exception as e:
        log.warning(f"[hf] list_repo_files failed: {e}")
        return []


def find_latest_checkpoint() -> Optional[str]:
    ckpts = list_hf_checkpoints()
    if not ckpts:
        return None
    latest = ckpts[-1]
    log.info(f"[hf] latest checkpoint: {latest}")
    return latest.replace(".model.pt", "")


# ══════════════════════════════════════════════════════════════════════════════
#  TIME BUDGET
# ══════════════════════════════════════════════════════════════════════════════
#  TIME BUDGET
# ══════════════════════════════════════════════════════════════════════════════
MAX_TRAINING_HOURS = 53.0
TRAINING_START = time.time()

def elapsed_h()   -> float: return (time.time() - TRAINING_START) / 3600
def remaining_h() -> float: return MAX_TRAINING_HOURS - elapsed_h()
def should_stop() -> bool:
    if elapsed_h() >= MAX_TRAINING_HOURS:
        log.info(f"[time] {MAX_TRAINING_HOURS}h budget reached β€” stopping")
        return True
    return False

def vram_used_gb()  -> float: return torch.cuda.memory_allocated() / 1024**3
def vram_total_gb() -> float: return torch.cuda.get_device_properties(0).total_memory / 1024**3
def vram_str()      -> str:   return f"{vram_used_gb():.1f}/{vram_total_gb():.0f}GB"


# ══════════════════════════════════════════════════════════════════════════════
#  METRICS LOGGER
# ══════════════════════════════════════════════════════════════════════════════
class MetricsLogger:
    """
    Streams one JSON object per line to a local .jsonl file, then uploads
    to the HF checkpoint repo every 15 min (and always on checkpoint saves).

    Each line fields:
      t, elapsed_h, session, step, epoch, kind
      kind=train  : loss, avg50, ppl, aux_loss, muon_lr, adamw_lr,
                    tok_per_sec, sec_per_step, vram_used_gb, vram_tot_gb,
                    moe_dead, moe_slots
      kind=val    : val_loss, val_ppl, is_best
      kind=ckpt   : ok (bool)
      kind=final  : train_loss, val_loss, val_ppl, best_val
    """

    def __init__(self):
        self.local_path  = os.path.join(TEMP_CKPT_DIR, f"metrics_session{SESSION_ID:03d}.jsonl")
        self.remote_name = f"metrics_session{SESSION_ID:03d}.jsonl"
        self._f          = open(self.local_path, "a", buffering=1)  # line-buffered
        log.info(f"[metrics] writing to {self.local_path}")

    def _write(self, record: dict):
        record.setdefault("t",         time.time())
        record.setdefault("elapsed_h", round(elapsed_h(), 4))
        record.setdefault("session",   SESSION_ID)
        self._f.write(json.dumps(record) + "\n")

    def log_train(self, *, step, epoch, loss, avg50, ppl, aux_loss,
                  muon_lr, adamw_lr, tok_per_sec, sec_per_step,
                  moe_dead, moe_slots):
        self._write(dict(
            kind         = "train",
            step         = step,
            epoch        = epoch,
            loss         = round(loss,         6),
            avg50        = round(avg50,        6),
            ppl          = round(ppl,          4),
            aux_loss     = round(aux_loss,     6),
            muon_lr      = muon_lr,
            adamw_lr     = adamw_lr,
            tok_per_sec  = round(tok_per_sec,  1),
            sec_per_step = round(sec_per_step, 3),
            vram_used_gb = round(vram_used_gb(),  2),
            vram_tot_gb  = round(vram_total_gb(), 1),
            moe_dead     = moe_dead,
            moe_slots    = moe_slots,
        ))

    def log_val(self, *, step, epoch, val_loss, val_ppl, is_best):
        self._write(dict(
            kind     = "val",
            step     = step,
            epoch    = epoch,
            val_loss = round(val_loss, 6),
            val_ppl  = round(val_ppl,  4),
            is_best  = is_best,
        ))

    def log_ckpt(self, *, step, epoch, ok):
        self._write(dict(kind="ckpt", step=step, epoch=epoch, ok=ok))

    def log_final(self, *, step, epoch, train_loss, val_loss, val_ppl, best_val):
        self._write(dict(
            kind       = "final",
            step       = step,
            epoch      = epoch,
            train_loss = round(train_loss, 6),
            val_loss   = round(val_loss,   6),
            val_ppl    = round(val_ppl,    4),
            best_val   = round(best_val,   6),
        ))

    def flush_to_hf(self) -> bool:
        self._f.flush()
        try:
            ok = upload_to_hf(self.local_path, self.remote_name)
            return ok
        except Exception as e:
            log.warning(f"[metrics] HF flush failed: {e}")
            return False

    def close(self):
        self.flush_to_hf()
        self._f.close()


# ══════════════════════════════════════════════════════════════════════════════
#  CONFIG
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class CascadeConfig:
    vocab_size: int   = 50304
    d_model:    int   = 896        # down from 1024, divisible by heads
    n_heads:    int   = 14         # 896/14 = 64 head_dim
    n_kv_heads: int   = 2          # aggressive GQA to save params
    n_layers:   int   = 20         # down from 24
    max_len:    int   = 2048

    # ── MoE tiers β€” biggest reduction lever ──────────────────────────────
    n_nano_experts:  int = 16      # down from 32
    n_midi_experts:  int = 24      # down from 48
    n_macro_experts: int = 8       # down from 16
    nano_hidden:     int = 224     # down from 256
    midi_hidden:     int = 448     # down from 512
    macro_hidden:    int = 1280    # down from 1536

    nano_top_k:  int = 2
    midi_top_k:  int = 2
    macro_top_k: int = 1

    nano_cost_weight:  float = 0.25
    midi_cost_weight:  float = 1.00
    macro_cost_weight: float = 3.00
    balance_coeff:     float = 0.01
    zloss_coeff:       float = 0.001

    router_noise_steps: int   = 5000
    router_noise_std:   float = 0.1
    macro_warmup_steps: int   = 5000

    local_window_size: int   = 512
    rope_theta:        float = 500000.0

    # ── optimizer β€” slightly more aggressive given smaller model ──────────
    muon_lr:      float = 0.014    # slightly higher for smaller model
    muon_min_lr:  float = 0.0014
    muon_momentum:float = 0.95
    adamw_lr:     float = 0.0005
    adamw_min_lr: float = 0.00005
    weight_decay: float = 0.1
    beta1:        float = 0.9
    beta2:        float = 0.95
    grad_clip:    float = 1.0
    warmup_steps: int   = 2000
    total_steps:  int   = 850000   # more steps since model is smaller/faster

    micro_batch: int = 4           # overridden by batch search anyway
    grad_accum:  int = 8
    log_every:   int = 10
    eval_every:  int = 500
    ckpt_every:  int = 2000
    seed:        int = 42

    use_fp8: str = "off"

    @property
    def dtype(self):
        return torch.bfloat16

    @property
    def head_dim(self):
        return self.d_model // self.n_heads

    @property
    def total_experts_per_layer(self):
        return self.n_nano_experts + self.n_midi_experts + self.n_macro_experts

    def effective_batch_tokens(self, micro: int) -> int:
        return micro * self.grad_accum * self.max_len


# ══════════════════════════════════════════════════════════════════════════════
#  DATA
# ══════════════════════════════════════════════════════════════════════════════
class TokenDataset(Dataset):
    """
    Expects a .npy file with shape (n_chunks, seq_len) and dtype int32/int64.
    Rows are shuffled per-epoch with a fixed seed so resuming is deterministic.
    """

    def __init__(self, hf_filename: str, epoch: int = 0):
        local_path = download_dataset_file(hf_filename)
        self.data    = np.load(local_path, mmap_mode="r")
        self.n       = len(self.data)
        self.seq_len = self.data.shape[1]
        self.indices = np.random.default_rng(42 + epoch).permutation(self.n)
        log.info(
            f"[data] {hf_filename} | epoch={epoch} | "
            f"{self.n:,} chunks | {self.n * self.seq_len / 1e9:.3f}B tokens | "
            f"seq_len={self.seq_len}"
        )

    def __len__(self):
        return self.n

    def __getitem__(self, i):
        return torch.from_numpy(self.data[self.indices[i]].astype(np.int64).copy())


class FixedLoader:
    """Infinite iterator over epochs; rebuilds DataLoader on each epoch boundary."""

    def __init__(self, hf_filename: str, batch_size: int, num_workers: int = 4):
        self.hf_filename = hf_filename
        self.batch_size  = batch_size
        self.num_workers = num_workers
        self.epoch       = 0
        self.loader      = None
        self._build()

    def _build(self):
        if self.loader is not None:
            try:
                del self.loader
            except Exception:
                pass
            gc.collect()
        ds = TokenDataset(self.hf_filename, self.epoch)
        self.loader = DataLoader(
            ds,
            batch_size=self.batch_size,
            shuffle=False,
            num_workers=self.num_workers,
            pin_memory=True,
            drop_last=True,
            prefetch_factor=4 if self.num_workers > 0 else None,
            persistent_workers=self.num_workers > 0,
        )
        self.it = iter(self.loader)
        log.info(
            f"[data] loader rebuilt | epoch={self.epoch + 1} "
            f"bs={self.batch_size} steps/epochβ‰ˆ{len(self.loader)}"
        )

    def __next__(self):
        try:
            return next(self.it), self.epoch
        except StopIteration:
            self.epoch += 1
            self._build()
            return next(self.it), self.epoch


# ══════════════════════════════════════════════════════════════════════════════
#  TRITON KERNELS
# ══════════════════════════════════════════════════════════════════════════════

# ── 1. Fused RMSNorm ─────────────────────────────────────────────────────────
@triton.jit
def _rmsnorm_fwd_kernel(X, W, Y, Rstd, N, eps, BLOCK_N: tl.constexpr):
    row  = tl.program_id(0)
    cols = tl.arange(0, BLOCK_N)
    mask = cols < N
    x    = tl.load(X + row * N + cols, mask=mask, other=0.0).to(tl.float32)
    var  = tl.sum(x * x, axis=0) / N
    rstd = 1.0 / tl.sqrt(var + eps)
    tl.store(Rstd + row, rstd)
    w = tl.load(W + cols, mask=mask, other=0.0).to(tl.float32)
    tl.store(Y + row * N + cols, (x * rstd * w).to(tl.bfloat16), mask=mask)


@triton.jit
def _rmsnorm_bwd_kernel(DY, X, W, Rstd, DX, DW, N, BLOCK_N: tl.constexpr):
    row  = tl.program_id(0)
    cols = tl.arange(0, BLOCK_N)
    mask = cols < N
    dy   = tl.load(DY + row * N + cols, mask=mask, other=0.0).to(tl.float32)
    x    = tl.load(X  + row * N + cols, mask=mask, other=0.0).to(tl.float32)
    w    = tl.load(W  + cols,           mask=mask, other=0.0).to(tl.float32)
    rstd = tl.load(Rstd + row)
    xhat = x * rstd
    wdy  = w * dy
    dx   = (wdy - xhat * (tl.sum(xhat * wdy, axis=0) / N)) * rstd
    tl.store(DX + row * N + cols, dx.to(tl.bfloat16), mask=mask)
    tl.atomic_add(DW + cols, dy * xhat, mask=mask)


class _RMSNormFn(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, weight, eps):
        orig_shape = x.shape
        N  = orig_shape[-1]
        x2 = x.reshape(-1, N).contiguous()
        M  = x2.shape[0]
        y    = torch.empty_like(x2, dtype=torch.bfloat16)
        rstd = torch.empty(M, dtype=torch.float32, device=x.device)
        BN   = triton.next_power_of_2(N)
        _rmsnorm_fwd_kernel[(M,)](x2, weight, y, rstd, N, eps, BLOCK_N=BN)
        ctx.save_for_backward(x2, weight, rstd)
        ctx.BN         = BN
        ctx.orig_shape = orig_shape
        return y.reshape(orig_shape)

    @staticmethod
    def backward(ctx, dy):
        x2, weight, rstd = ctx.saved_tensors
        N   = x2.shape[1]
        M   = x2.shape[0]
        dy2 = dy.reshape(-1, N).contiguous()
        dx  = torch.empty_like(x2, dtype=torch.bfloat16)
        dw  = torch.zeros(N, dtype=torch.float32, device=x2.device)
        _rmsnorm_bwd_kernel[(M,)](dy2, x2, weight, rstd, dx, dw, N, BLOCK_N=ctx.BN)
        return dx.reshape(ctx.orig_shape), dw.to(weight.dtype), None


class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps   = eps
        self.scale = nn.Parameter(torch.ones(dim))

    def forward(self, x):
        return _RMSNormFn.apply(x, self.scale, self.eps)


# ── 2. Fused RoPE ────────────────────────────────────────────────────────────
def precompute_freqs_cis(head_dim: int, max_len: int,
                         theta: float = 500000.0, device=None):
    freqs = 1.0 / (
        theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32, device=device) / head_dim)
    )
    t     = torch.arange(max_len, dtype=torch.float32, device=device)
    freqs = torch.outer(t, freqs)
    return torch.cos(freqs), torch.sin(freqs)   # (max_len, head_dim//2) each


@triton.jit
def _rope_kernel(X, COS, SIN, OUT, L, H, HD, BLOCK_HALF: tl.constexpr):
    pid  = tl.program_id(0)   # flat index over B*L*H
    l    = (pid // H) % L
    half = HD // 2
    offs = tl.arange(0, BLOCK_HALF)
    mask = offs < half
    base = pid * HD
    x1   = tl.load(X + base + offs,        mask=mask, other=0.0).to(tl.float32)
    x2   = tl.load(X + base + half + offs, mask=mask, other=0.0).to(tl.float32)
    cos  = tl.load(COS + l * half + offs,  mask=mask, other=0.0).to(tl.float32)
    sin  = tl.load(SIN + l * half + offs,  mask=mask, other=0.0).to(tl.float32)
    tl.store(OUT + base + offs,        (x1 * cos - x2 * sin).to(tl.bfloat16), mask=mask)
    tl.store(OUT + base + half + offs, (x2 * cos + x1 * sin).to(tl.bfloat16), mask=mask)


def _rope_raw(x: torch.Tensor, cos_half: torch.Tensor, sin_half: torch.Tensor):
    B, L, H, HD = x.shape
    out        = torch.empty_like(x, dtype=torch.bfloat16)
    BLOCK_HALF = triton.next_power_of_2(HD // 2)
    _rope_kernel[(B * L * H,)](
        x.contiguous(), cos_half, sin_half, out, L, H, HD, BLOCK_HALF=BLOCK_HALF
    )
    return out


class _RopeFn(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, cos_half, sin_half):
        ctx.save_for_backward(cos_half, sin_half)
        return _rope_raw(x, cos_half, sin_half)

    @staticmethod
    def backward(ctx, dy):
        cos_half, sin_half = ctx.saved_tensors
        return _rope_raw(dy, cos_half, -sin_half), None, None


def apply_rope(xq, xk, cos, sin):
    L        = xq.shape[1]
    cos_half = cos[:L].contiguous()
    sin_half = sin[:L].contiguous()
    return (
        _RopeFn.apply(xq, cos_half, sin_half).to(xq.dtype),
        _RopeFn.apply(xk, cos_half, sin_half).to(xk.dtype),
    )


# ── 3. Fused windowed/causal attention ───────────────────────────────────────
@triton.jit
def _fwd_attn_kernel(
    Q, K, V, O, sm_scale,
    stride_qz, stride_qh, stride_qm, stride_qk,
    stride_kz, stride_kh, stride_kn, stride_kk,
    stride_vz, stride_vh, stride_vn, stride_vk,
    stride_oz, stride_oh, stride_om, stride_ok,
    H, N_CTX,
    WINDOW: tl.constexpr,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_D: tl.constexpr,
):
    start_m = tl.program_id(0)
    off_hz  = tl.program_id(1)
    off_z   = off_hz // H
    off_h   = off_hz  % H

    q_off = off_z * stride_qz + off_h * stride_qh
    k_off = off_z * stride_kz + off_h * stride_kh
    v_off = off_z * stride_vz + off_h * stride_vh
    o_off = off_z * stride_oz + off_h * stride_oh

    offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_d = tl.arange(0, BLOCK_D)

    q = tl.load(
        Q + q_off + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk,
        mask=offs_m[:, None] < N_CTX, other=0.0,
    )

    NEG_INF: tl.constexpr = -1e9     # v2 fix: finite sentinel avoids NaN in rescale
    m_i  = tl.zeros([BLOCK_M], dtype=tl.float32) + NEG_INF
    l_i  = tl.zeros([BLOCK_M], dtype=tl.float32)
    acc  = tl.zeros([BLOCK_M, BLOCK_D], dtype=tl.float32)

    lo = tl.maximum(0, ((start_m * BLOCK_M - WINDOW) // BLOCK_N) * BLOCK_N) if WINDOW > 0 else 0
    hi = (start_m + 1) * BLOCK_M

    for start_n in range(lo, hi, BLOCK_N):
        offs_n = start_n + tl.arange(0, BLOCK_N)
        k = tl.load(
            K + k_off + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk,
            mask=offs_n[:, None] < N_CTX, other=0.0,
        )
        qk     = tl.dot(q, tl.trans(k)) * sm_scale
        m_idx  = offs_m[:, None]
        n_idx  = offs_n[None, :]
        causal = n_idx <= m_idx
        if WINDOW > 0:
            causal = causal & (n_idx > m_idx - WINDOW)
        qk    = tl.where(causal, qk, NEG_INF)
        m_ij  = tl.maximum(m_i, tl.max(qk, axis=1))
        p     = tl.exp(qk - m_ij[:, None])
        alpha = tl.exp(m_i - m_ij)
        l_i   = l_i * alpha + tl.sum(p, axis=1)
        acc   = acc * alpha[:, None]
        v = tl.load(
            V + v_off + offs_n[:, None] * stride_vn + offs_d[None, :] * stride_vk,
            mask=offs_n[:, None] < N_CTX, other=0.0,
        )
        acc  += tl.dot(p.to(v.dtype), v)
        m_i   = m_ij

    acc = acc / tl.maximum(l_i[:, None], 1e-9)
    tl.store(
        O + o_off + offs_m[:, None] * stride_om + offs_d[None, :] * stride_ok,
        acc.to(tl.bfloat16), mask=offs_m[:, None] < N_CTX,
    )


def _triton_attn_fwd(q, k, v, window_size):
    B, H, L, D = q.shape
    o        = torch.empty_like(q, dtype=torch.bfloat16)
    sm_scale = 1.0 / math.sqrt(D)
    BM, BN   = 64, 64
    BD       = triton.next_power_of_2(D)
    WIN      = window_size if (window_size and window_size > 0) else 0
    _fwd_attn_kernel[(triton.cdiv(L, BM), B * H)](
        q, k, v, o, sm_scale,
        q.stride(0), q.stride(1), q.stride(2), q.stride(3),
        k.stride(0), k.stride(1), k.stride(2), k.stride(3),
        v.stride(0), v.stride(1), v.stride(2), v.stride(3),
        o.stride(0), o.stride(1), o.stride(2), o.stride(3),
        H, L, WIN, BLOCK_M=BM, BLOCK_N=BN, BLOCK_D=BD,
    )
    return o


# block-mask cache for flex_attention backward (v3)
_block_mask_cache: dict = {}


def _get_block_mask(L: int, window_size: int, device):
    key = (L, window_size, device)
    if key not in _block_mask_cache:
        if window_size and window_size > 0:
            def mask_mod(b, h, q_idx, kv_idx):
                return (kv_idx <= q_idx) & (kv_idx > q_idx - window_size)
        else:
            def mask_mod(b, h, q_idx, kv_idx):
                return kv_idx <= q_idx
        _block_mask_cache[key] = create_block_mask(
            mask_mod, B=None, H=None, Q_LEN=L, KV_LEN=L, device=device
        )
    return _block_mask_cache[key]


# dense-mask fallback (only used when flex_attention is unavailable)
_window_mask_cache: dict = {}


def _get_window_mask(L: int, window_size: int, device):
    key = (L, window_size, device)
    if key not in _window_mask_cache:
        idx  = torch.arange(L, device=device)
        diff = idx.view(-1, 1) - idx.view(1, -1)
        mask = (diff >= 0) & (diff < window_size) if (window_size and window_size > 0) else diff >= 0
        _window_mask_cache[key] = mask
    return _window_mask_cache[key]


class TritonWindowAttentionFn(torch.autograd.Function):
    """fwd = fused triton kernel, bwd = flex_attention block_mask recompute."""

    @staticmethod
    def forward(ctx, q, k, v, window_size):
        q, k, v = q.contiguous(), k.contiguous(), v.contiguous()
        out = _triton_attn_fwd(q, k, v, window_size)
        ctx.save_for_backward(q, k, v)
        ctx.window_size = window_size
        return out

    @staticmethod
    def backward(ctx, dout):
        q, k, v     = ctx.saved_tensors
        window_size = ctx.window_size
        L           = q.shape[2]
        with torch.enable_grad():
            qd = q.detach().requires_grad_(True)
            kd = k.detach().requires_grad_(True)
            vd = v.detach().requires_grad_(True)
            if HAS_FLEX_ATTN:
                bm  = _get_block_mask(L, window_size, q.device)
                out = flex_attention(qd, kd, vd, block_mask=bm)
            else:
                mask = _get_window_mask(L, window_size, q.device)
                out  = F.scaled_dot_product_attention(qd, kd, vd, attn_mask=mask)
            dq, dk, dv = torch.autograd.grad(out, (qd, kd, vd), dout)
        return dq, dk, dv, None


def triton_attention(q, k, v, window_size: int = 0):
    return TritonWindowAttentionFn.apply(q, k, v, window_size)


# ── 4. Fused grouped-GEMM MoE dispatch ───────────────────────────────────────
_moe_autotune_configs = [
    triton.Config({"BLOCK_N": 64,  "BLOCK_K": 32}, num_warps=4, num_stages=3),
    triton.Config({"BLOCK_N": 128, "BLOCK_K": 32}, num_warps=8, num_stages=3),
    triton.Config({"BLOCK_N": 128, "BLOCK_K": 64}, num_warps=8, num_stages=4),
    triton.Config({"BLOCK_N": 64,  "BLOCK_K": 64}, num_warps=4, num_stages=4),
]


@triton.autotune(configs=_moe_autotune_configs, key=["K", "N"])
@triton.jit
def _moe_gemm_kernel(
    A_ptr, B_ptr, C_ptr, block_expert_ptr,
    M_padded, K, N,
    stride_am, stride_ak,
    stride_be, stride_bk, stride_bn,
    stride_cm, stride_cn,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    e     = tl.load(block_expert_ptr + pid_m).to(tl.int64)

    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_k = tl.arange(0, BLOCK_K)
    m_mask = offs_m < M_padded
    n_mask = offs_n < N

    a_ptrs = A_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
    b_ptrs = B_ptr + e * stride_be + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn

    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
    for k0 in range(0, K, BLOCK_K):
        k_mask = (k0 + offs_k) < K
        a = tl.load(a_ptrs, mask=m_mask[:, None] & k_mask[None, :], other=0.0)
        b = tl.load(b_ptrs, mask=k_mask[:, None] & n_mask[None, :], other=0.0)
        acc    = tl.dot(a, b, acc)
        a_ptrs += BLOCK_K * stride_ak
        b_ptrs += BLOCK_K * stride_bk

    tl.store(
        C_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn,
        acc.to(tl.bfloat16), mask=m_mask[:, None] & n_mask[None, :],
    )


def _grouped_linear_raw(A, W, block_expert, M_padded, transpose, BM):
    E, OUT, IN = W.shape
    if not transpose:
        K, N       = IN, OUT
        stride_bk  = W.stride(2)
        stride_bn  = W.stride(1)
    else:
        K, N       = OUT, IN
        stride_bk  = W.stride(1)
        stride_bn  = W.stride(2)

    C    = torch.empty((M_padded, N), device=A.device, dtype=torch.bfloat16)
    grid = lambda META: (triton.cdiv(M_padded, BM), triton.cdiv(N, META["BLOCK_N"]))
    _moe_gemm_kernel[grid](
        A, W, C, block_expert, M_padded, K, N,
        A.stride(0), A.stride(1),
        W.stride(0), stride_bk, stride_bn,
        C.stride(0), C.stride(1),
        BLOCK_M=BM,
    )
    return C


@triton.autotune(configs=_moe_autotune_configs, key=["K", "N"])
@triton.jit
def _moe_dw_kernel(
    A_ptr, DC_ptr, DW_ptr, block_expert_ptr,
    M_padded, K, N,
    stride_am, stride_ak,
    stride_dcm, stride_dcn,
    stride_dwe, stride_dwn, stride_dwk,
    BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    pid_k = tl.program_id(2)
    e     = tl.load(block_expert_ptr + pid_m).to(tl.int64)

    offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    offs_k = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
    m_mask = offs_m < M_padded
    n_mask = offs_n < N
    k_mask = offs_k < K

    a  = tl.load(A_ptr  + offs_m[:, None] * stride_am  + offs_k[None, :] * stride_ak,
                 mask=m_mask[:, None] & k_mask[None, :], other=0.0)
    dc = tl.load(DC_ptr + offs_m[:, None] * stride_dcm + offs_n[None, :] * stride_dcn,
                 mask=m_mask[:, None] & n_mask[None, :], other=0.0)

    tl.atomic_add(
        DW_ptr + e * stride_dwe + offs_n[:, None] * stride_dwn + offs_k[None, :] * stride_dwk,
        tl.dot(tl.trans(dc), a),
        mask=n_mask[:, None] & k_mask[None, :],
    )


def _grouped_dw_raw(A, dC, block_expert, E, OUT, IN, M_padded, BM):
    DW   = torch.zeros((E, OUT, IN), device=A.device, dtype=torch.float32)
    grid = lambda META: (
        triton.cdiv(M_padded, BM),
        triton.cdiv(OUT, META["BLOCK_N"]),
        triton.cdiv(IN,  META["BLOCK_K"]),
    )
    _moe_dw_kernel[grid](
        A, dC, DW, block_expert, M_padded, IN, OUT,
        A.stride(0), A.stride(1),
        dC.stride(0), dC.stride(1),
        DW.stride(0), DW.stride(1), DW.stride(2),
        BLOCK_M=BM,
    )
    return DW


class GroupedLinearFn(torch.autograd.Function):
    @staticmethod
    def forward(ctx, A, W, block_expert, padded_offsets, M_padded, BM):
        A = A.contiguous().to(torch.bfloat16)
        C = _grouped_linear_raw(A, W, block_expert, M_padded, False, BM)
        ctx.save_for_backward(A, W, block_expert, padded_offsets)
        ctx.M_padded = M_padded
        ctx.BM       = BM
        return C

    @staticmethod
    def backward(ctx, dC):
        A, W, block_expert, _ = ctx.saved_tensors
        dC = dC.contiguous().to(torch.bfloat16)
        dA = _grouped_linear_raw(dC, W, block_expert, ctx.M_padded, True, ctx.BM) \
             if ctx.needs_input_grad[0] else None
        dW = _grouped_dw_raw(A, dC, block_expert, W.shape[0], W.shape[1], W.shape[2],
                             ctx.M_padded, ctx.BM).to(W.dtype) \
             if ctx.needs_input_grad[1] else None
        return dA, dW, None, None, None, None


def moe_align_block_size(expert_ids, num_experts, block_size, device):
    counts        = torch.bincount(expert_ids, minlength=num_experts)
    padded_counts = ((counts + block_size - 1) // block_size) * block_size

    padded_offsets      = torch.zeros(num_experts + 1, dtype=torch.long, device=device)
    padded_offsets[1:]  = torch.cumsum(padded_counts, dim=0)
    orig_offsets        = torch.zeros(num_experts + 1, dtype=torch.long, device=device)
    orig_offsets[1:]    = torch.cumsum(counts, dim=0)

    total_padded         = int(padded_offsets[-1].item())
    sort_idx             = torch.argsort(expert_ids, stable=True)
    num_blocks_per_expert= padded_counts // block_size
    block_expert         = torch.repeat_interleave(
        torch.arange(num_experts, device=device), num_blocks_per_expert
    )

    n_rows               = expert_ids.numel()
    arange_total         = torch.arange(n_rows, device=device)
    sorted_expert_of_row = expert_ids[sort_idx]
    row_within_expert    = arange_total - orig_offsets[sorted_expert_of_row]
    dest                 = padded_offsets[sorted_expert_of_row] + row_within_expert

    perm       = torch.full((total_padded,), -1, dtype=torch.long, device=device)
    perm[dest] = sort_idx
    return perm, block_expert, total_padded, padded_offsets


class FusedExpertTier(nn.Module):
    """Single-tier fused grouped-GEMM expert compute."""

    def __init__(self, n_experts: int, d_model: int, hidden_dim: int, block_m: int = 64):
        super().__init__()
        self.n_experts  = n_experts
        self.hidden_dim = hidden_dim
        self.block_m    = block_m
        self.W_gate_up  = nn.Parameter(torch.empty(n_experts, 2 * hidden_dim, d_model))
        self.W_down     = nn.Parameter(torch.empty(n_experts, d_model, hidden_dim))
        nn.init.normal_(self.W_gate_up, std=0.02)
        nn.init.normal_(self.W_down,    std=0.02)

    def forward(self, x_flat, top_idx, top_gate, tier_weight):
        N, D   = x_flat.shape
        k      = top_idx.shape[1]
        E      = self.n_experts
        device = x_flat.device
        BM     = self.block_m

        expert_ids_flat = top_idx.reshape(-1)
        gate_flat       = (top_gate * tier_weight).reshape(-1)
        token_idx_flat  = torch.arange(N, device=device).unsqueeze(1).expand(N, k).reshape(-1)

        perm, block_expert, total_padded, padded_offsets = moe_align_block_size(
            expert_ids_flat, E, BM, device
        )

        valid      = perm >= 0
        gather_idx = perm.clamp_min(0)
        src_token  = token_idx_flat[gather_idx]
        A_padded   = x_flat[src_token] * valid.unsqueeze(1).to(x_flat.dtype)

        gate_up = GroupedLinearFn.apply(A_padded, self.W_gate_up, block_expert, padded_offsets, total_padded, BM)
        H       = self.hidden_dim
        down    = GroupedLinearFn.apply(F.silu(gate_up[:, :H]) * gate_up[:, H:], self.W_down, block_expert, padded_offsets, total_padded, BM)

        gate_vals = (gate_flat[gather_idx] * valid.to(gate_flat.dtype)).unsqueeze(1)
        out       = torch.zeros(N, D, dtype=x_flat.dtype, device=device)
        out.index_add_(0, src_token, (down * gate_vals.to(down.dtype)))
        return out


# ── 5. Muon with 3-D expert tensor support ───────────────────────────────────
def zeropower_via_newtonschulz5(G: torch.Tensor, steps: int = 5) -> torch.Tensor:
    assert G.ndim == 2
    a, b, c = 3.4445, -4.7750, 2.0315
    X = G.bfloat16()
    if X.size(0) > X.size(1):
        X = X.T
    X = X / (X.norm() + 1e-7)
    for _ in range(steps):
        A = X @ X.T
        X = a * X + (b * A + c * A @ A) @ X
    if G.size(0) > G.size(1):
        X = X.T
    return X


class Muon(torch.optim.Optimizer):
    def __init__(self, params, lr=0.02, momentum=0.95, weight_decay=0.0, ns_steps=5):
        params = list(params)
        for p in params:
            assert p.ndim in (2, 3), f"Muon: expected 2D/3D param, got {tuple(p.shape)}"
        super().__init__(params, dict(lr=lr, momentum=momentum,
                                     weight_decay=weight_decay, ns_steps=ns_steps))

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            lr, mom, wd, ns = group["lr"], group["momentum"], group["weight_decay"], group["ns_steps"]
            for p in group["params"]:
                if p.grad is None:
                    continue
                g     = p.grad
                state = self.state[p]
                if "buf" not in state:
                    state["buf"] = torch.zeros_like(g)
                buf = state["buf"]
                buf.mul_(mom).add_(g)
                g = g.add(buf, alpha=mom)
                if wd > 0:
                    p.mul_(1 - lr * wd)
                if p.ndim == 2:
                    u     = zeropower_via_newtonschulz5(g, steps=ns)
                    scale = 0.2 * math.sqrt(max(p.size(0), p.size(1)))
                else:
                    u = torch.stack([zeropower_via_newtonschulz5(g[e], steps=ns)
                                     for e in range(p.size(0))])
                    scale = 0.2 * math.sqrt(max(p.size(1), p.size(2)))
                p.add_(u.to(p.dtype), alpha=-lr * scale)


log.info(
    "[triton] RMSNorm / RoPE / windowed-attn (flex_attention bwd) / "
    "grouped-GEMM MoE (fwd+dW autotuned) / Muon(2D+3D) β€” all ready"
)


# ══════════════════════════════════════════════════════════════════════════════
#  NaN HUNTER  (debug utility β€” not called in normal training)
# ══════════════════════════════════════════════════════════════════════════════
def install_nan_hooks(model: nn.Module):
    handles = []
    for name, module in model.named_modules():
        if not list(module.children()):
            def _hook(m, inp, out, _name=name):
                for i, o in enumerate((out if isinstance(out, (tuple, list)) else (out,))):
                    if isinstance(o, torch.Tensor) and o.dtype.is_floating_point:
                        if torch.isnan(o).any() or torch.isinf(o).any():
                            raise RuntimeError(f"NaN/Inf in {_name} output[{i}]")
            handles.append(module.register_forward_hook(_hook))
    return handles


def debug_one_batch(model, cfg, device, B=2, L=512):
    model.train(); model.set_step(0)
    handles = install_nan_hooks(model)
    dummy   = torch.randint(0, cfg.vocab_size, (B, L), device=device)
    try:
        with torch.amp.autocast("cuda", dtype=torch.bfloat16):
            out = model(dummy, targets=dummy)
        print(f"βœ… forward clean β€” loss={out[1].item():.4f}")
    except RuntimeError as e:
        print(f"πŸ”΄ {e}")
    finally:
        for h in handles: h.remove()


# ══════════════════════════════════════════════════════════════════════════════
#  MODEL BUILDING BLOCKS
# ══════════════════════════════════════════════════════════════════════════════
class GroupedQueryAttention(nn.Module):
    def __init__(self, cfg: CascadeConfig, layer_idx: int):
        super().__init__()
        self.nh          = cfg.n_heads
        self.nkv         = cfg.n_kv_heads
        self.hd          = cfg.head_dim
        self.ng          = cfg.n_heads // cfg.n_kv_heads
        self.is_local    = (layer_idx % 2 == 0)
        self.window_size = cfg.local_window_size if self.is_local else 0

        D   = cfg.n_heads    * cfg.head_dim
        Dkv = cfg.n_kv_heads * cfg.head_dim

        self.q = nn.Linear(cfg.d_model, D,   bias=False)
        self.k = nn.Linear(cfg.d_model, Dkv, bias=False)
        self.v = nn.Linear(cfg.d_model, Dkv, bias=False)
        self.o = nn.Linear(D, cfg.d_model,   bias=False)

        self.q_norm = RMSNorm(self.hd)
        self.k_norm = RMSNorm(self.hd)

        for lin in (self.q, self.k, self.v):
            nn.init.normal_(lin.weight, std=0.02)
        nn.init.normal_(self.o.weight, std=0.02 / math.sqrt(2 * cfg.n_layers))

    def forward(self, x, cos, sin):
        B, L, _ = x.shape
        q = self.q_norm(self.q(x).view(B, L, self.nh,  self.hd))
        k = self.k_norm(self.k(x).view(B, L, self.nkv, self.hd))
        v =             self.v(x).view(B, L, self.nkv, self.hd)

        q, k = apply_rope(q, k, cos, sin)

        q = q.transpose(1, 2).contiguous()
        k = k.transpose(1, 2).repeat_interleave(self.ng, 1).contiguous()
        v = v.transpose(1, 2).repeat_interleave(self.ng, 1).contiguous()

        return self.o(
            triton_attention(q, k, v, window_size=self.window_size)
            .transpose(1, 2).contiguous().view(B, L, -1)
        )


class HierarchicalMoE(nn.Module):
    def __init__(self, cfg: CascadeConfig):
        super().__init__()
        self.cfg     = cfg
        self.n_nano  = cfg.n_nano_experts
        self.n_midi  = cfg.n_midi_experts
        self.n_macro = cfg.n_macro_experts

        self.tier_router  = nn.Linear(cfg.d_model, 3,             bias=False)
        self.nano_router  = nn.Linear(cfg.d_model, self.n_nano,   bias=False)
        self.midi_router  = nn.Linear(cfg.d_model, self.n_midi,   bias=False)
        self.macro_router = nn.Linear(cfg.d_model, self.n_macro,  bias=False)
        nn.init.normal_(self.tier_router.weight, std=0.01)
        for r in (self.nano_router, self.midi_router, self.macro_router):
            nn.init.normal_(r.weight, std=0.02)

        self.nano_tier  = FusedExpertTier(self.n_nano,  cfg.d_model, cfg.nano_hidden)
        self.midi_tier  = FusedExpertTier(self.n_midi,  cfg.d_model, cfg.midi_hidden)
        self.macro_tier = FusedExpertTier(self.n_macro, cfg.d_model, cfg.macro_hidden)

        for name, n in [("nano_load", self.n_nano), ("midi_load", self.n_midi),
                        ("macro_load", self.n_macro), ("token_count", 1)]:
            self.register_buffer(name, torch.zeros(n, dtype=torch.float32), persistent=False)

    def _apply(self, fn, recurse=True):
        saved = {k: getattr(self, k).clone()
                 for k in ("nano_load", "midi_load", "macro_load", "token_count")}
        super()._apply(fn, recurse=recurse)
        dev = self.nano_load.device
        for k, v in saved.items():
            setattr(self, k, v.float().to(dev))
        return self

    def forward(self, x, step: int):
        B, L, D = x.shape
        N, cfg  = B * L, self.cfg
        xf      = x.reshape(N, D)

        # ── routers ──────────────────────────────────────────────────────────
        def _maybe_noise(t):
            if self.training and step < cfg.router_noise_steps:
                return t + cfg.router_noise_std * torch.randn_like(t)
            return t

        tier_probs  = F.softmax(_maybe_noise(self.tier_router(xf)).float(),  dim=-1)
        nano_soft   = F.softmax(_maybe_noise(self.nano_router(xf)).float(),  dim=-1)
        midi_soft   = F.softmax(_maybe_noise(self.midi_router(xf)).float(),  dim=-1)
        macro_soft  = F.softmax(_maybe_noise(self.macro_router(xf)).float(), dim=-1)

        nano_g,  nano_idx  = torch.topk(nano_soft,  cfg.nano_top_k,  dim=-1)
        midi_g,  midi_idx  = torch.topk(midi_soft,  cfg.midi_top_k,  dim=-1)
        macro_g, macro_idx = torch.topk(macro_soft, cfg.macro_top_k, dim=-1)

        nano_g  = nano_g  / nano_g.sum( -1, keepdim=True).clamp_min(1e-9)
        midi_g  = midi_g  / midi_g.sum( -1, keepdim=True).clamp_min(1e-9)
        macro_g = macro_g / macro_g.sum(-1, keepdim=True).clamp_min(1e-9)

        nano_w, midi_w, macro_w = tier_probs[:, 0:1], tier_probs[:, 1:2], tier_probs[:, 2:3]
        if self.training and step < cfg.macro_warmup_steps:
            macro_w = torch.clamp(macro_w + 0.3, 0.0, 1.0)
            s       = (nano_w + midi_w + macro_w).clamp_min(1e-9)
            nano_w, midi_w, macro_w = nano_w / s, midi_w / s, macro_w / s

        # ── load tracking ────────────────────────────────────────────────────
        with torch.no_grad():
            ones = lambda n: torch.ones(n, device=x.device, dtype=torch.float32)
            self.nano_load.scatter_add_ (0, nano_idx.reshape(-1),  ones(nano_idx.numel()))
            self.midi_load.scatter_add_ (0, midi_idx.reshape(-1),  ones(midi_idx.numel()))
            self.macro_load.scatter_add_(0, macro_idx.reshape(-1), ones(macro_idx.numel()))
            self.token_count += float(N)

        # ── expert compute ───────────────────────────────────────────────────
        out = (  self.nano_tier( xf, nano_idx,  nano_g,  nano_w)
               + self.midi_tier( xf, midi_idx,  midi_g,  midi_w)
               + self.macro_tier(xf, macro_idx, macro_g, macro_w))

        # ── aux losses ───────────────────────────────────────────────────────
        zloss = ((torch.logsumexp(nano_soft.log(),  -1) ** 2).mean()
               + (torch.logsumexp(midi_soft.log(),  -1) ** 2).mean()
               + (torch.logsumexp(macro_soft.log(), -1) ** 2).mean()) / 3.0

        def _bal(soft, idx, top_g, tier_w, cost):
            full = torch.zeros(N, soft.shape[1], device=x.device, dtype=torch.float32)
            full.scatter_(1, idx, (top_g * tier_w).float())
            return cost * ((full > 0).float().mean(0) * soft.mean(0)).sum()

        balance = (
            _bal(nano_soft,  nano_idx,  nano_g,  nano_w,  cfg.nano_cost_weight)
          + _bal(midi_soft,  midi_idx,  midi_g,  midi_w,  cfg.midi_cost_weight)
          + _bal(macro_soft, macro_idx, macro_g, macro_w, cfg.macro_cost_weight)
        ) * cfg.total_experts_per_layer / 3.0

        aux_loss = cfg.zloss_coeff * zloss + cfg.balance_coeff * balance
        return out.reshape(B, L, D), aux_loss

    @torch.no_grad()
    def read_reset_stats(self):
        total = self.token_count.item()
        if total <= 0:
            return [], [], [], 0, 0
        nano_f  = (self.nano_load  / total).tolist()
        midi_f  = (self.midi_load  / total).tolist()
        macro_f = (self.macro_load / total).tolist()
        dead    = int((self.nano_load  == 0).sum()
                    + (self.midi_load  == 0).sum()
                    + (self.macro_load == 0).sum())
        slots   = self.n_nano + self.n_midi + self.n_macro
        self.nano_load.zero_()
        self.midi_load.zero_()
        self.macro_load.zero_()
        self.token_count.zero_()
        return nano_f, midi_f, macro_f, dead, slots


class CascadeBlock(nn.Module):
    def __init__(self, cfg: CascadeConfig, layer_idx: int):
        super().__init__()
        self.attn_norm = RMSNorm(cfg.d_model)
        self.ffn_norm  = RMSNorm(cfg.d_model)
        self.attn      = GroupedQueryAttention(cfg, layer_idx)
        self.ffn       = HierarchicalMoE(cfg)

    def forward(self, x, cos, sin, step):
        x = x + self.attn(self.attn_norm(x), cos, sin)
        ffn_out, aux = self.ffn(self.ffn_norm(x), step)
        return x + ffn_out, aux


class CascadeFormer(nn.Module):
    def __init__(self, cfg: CascadeConfig):
        super().__init__()
        self.cfg     = cfg
        self.embed   = nn.Embedding(cfg.vocab_size, cfg.d_model)
        self.layers  = nn.ModuleList([CascadeBlock(cfg, i) for i in range(cfg.n_layers)])
        self.norm    = RMSNorm(cfg.d_model)
        self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)
        self.lm_head.weight = self.embed.weight          # weight tying

        nn.init.normal_(self.embed.weight, std=0.02)

        cos, sin = precompute_freqs_cis(cfg.head_dim, cfg.max_len, theta=cfg.rope_theta)
        self.register_buffer("rope_cos", cos, persistent=False)
        self.register_buffer("rope_sin", sin, persistent=False)

        self._step = 0

        n_local = sum(1 for l in self.layers if l.attn.is_local)
        log.info(f"[model] {cfg.n_layers} layers | "
                 f"{n_local} local-attn (w={cfg.local_window_size}) + "
                 f"{cfg.n_layers - n_local} global-attn")
        log.info(f"[model] {cfg.total_experts_per_layer} experts/layer | "
                 f"{cfg.n_nano_experts}Γ—NANO({cfg.nano_hidden}d) + "
                 f"{cfg.n_midi_experts}Γ—MIDI({cfg.midi_hidden}d) + "
                 f"{cfg.n_macro_experts}Γ—MACRO({cfg.macro_hidden}d)")

    def set_step(self, s: int): self._step = s

    def forward(self, input_ids, targets=None):
        B, L  = input_ids.shape
        x     = self.embed(input_ids)
        cos   = self.rope_cos[:L]
        sin   = self.rope_sin[:L]

        aux_total = x.new_zeros(())
        for layer in self.layers:
            x, aux    = layer(x, cos, sin, self._step)
            aux_total = aux_total + aux

        logits = self.lm_head(self.norm(x))

        if targets is None:
            return logits, None

        lm_loss = F.cross_entropy(
            logits[:, :-1].contiguous().view(-1, self.cfg.vocab_size),
            targets[:, 1:].contiguous().view(-1),
            ignore_index=-1,
        )
        total_loss = lm_loss + aux_total / self.cfg.n_layers
        return logits, total_loss, lm_loss.detach(), (aux_total / self.cfg.n_layers).detach()

    def moe_modules(self):
        for layer in self.layers:
            yield layer.ffn

    @torch.no_grad()
    def moe_read_stats(self):
        all_n, all_m, all_mc, dead, slots = [], [], [], 0, 0
        for moe in self.moe_modules():
            n, m, mc, d, s = moe.read_reset_stats()
            all_n.extend(n); all_m.extend(m); all_mc.extend(mc)
            dead += d; slots += s
        return all_n, all_m, all_mc, dead, slots

    def count_params(self) -> int:
        seen, total = set(), 0
        for p in self.parameters():
            if id(p) not in seen:
                seen.add(id(p)); total += p.numel()
        return total


# ══════════════════════════════════════════════════════════════════════════════
#  FP8
# ══════════════════════════════════════════════════════════════════════════════
_FP8_SKIP = ("tier_router", "nano_router", "midi_router", "macro_router", "lm_head", "embed")


def fp8_capable_gpu() -> bool:
    return torch.cuda.is_available() and torch.cuda.get_device_capability(0)[0] >= 9


def resolve_use_fp8(cfg: CascadeConfig) -> bool:
    if cfg.use_fp8 == "off":
        return False
    if cfg.use_fp8 == "on":
        if not HAS_TORCHAO: log.warning("[fp8] torchao missing β€” bf16"); return False
        if not fp8_capable_gpu(): log.warning("[fp8] pre-Hopper GPU β€” bf16"); return False
        return True
    ok = HAS_TORCHAO and fp8_capable_gpu()
    log.info(f"[fp8] auto β†’ {'FP8' if ok else 'BF16'}")
    return ok


def apply_fp8(model: nn.Module, cfg: CascadeConfig) -> nn.Module:
    if not resolve_use_fp8(cfg):
        return model
    convert_to_float8_training(
        model,
        config=Float8LinearConfig.from_recipe_name("rowwise"),
        module_filter_fn=lambda m, fqn: (
            isinstance(m, nn.Linear) and not any(s in fqn for s in _FP8_SKIP)
        ),
    )
    log.info("[fp8] model converted")
    return model


# ══════════════════════════════════════════════════════════════════════════════
#  OPTIMIZERS
# ══════════════════════════════════════════════════════════════════════════════
def build_optimizers(model: nn.Module, cfg: CascadeConfig):
    muon_p, wd_p, no_wd_p, seen = [], [], [], set()
    for name, p in model.named_parameters():
        if id(p) in seen or not p.requires_grad:
            continue
        seen.add(id(p))
        is_head = ("embed" in name) or ("lm_head" in name)
        if p.ndim in (2, 3) and not is_head:
            muon_p.append(p)
        elif p.ndim >= 2:
            wd_p.append(p)
        else:
            no_wd_p.append(p)

    muon_opt = Muon(muon_p, lr=cfg.muon_lr, momentum=cfg.muon_momentum,
                    weight_decay=cfg.weight_decay)

    adamw_groups = [
        {"params": wd_p,    "weight_decay": cfg.weight_decay},
        {"params": no_wd_p, "weight_decay": 0.0},
    ]
    if HAS_BNB:
        adamw_opt = bnb.optim.AdamW8bit(
            adamw_groups, lr=cfg.adamw_lr, betas=(cfg.beta1, cfg.beta2), eps=1e-8
        )
        log.info("[optim] Muon + 8-bit AdamW (bitsandbytes)")
    else:
        adamw_opt = torch.optim.AdamW(
            adamw_groups, lr=cfg.adamw_lr, betas=(cfg.beta1, cfg.beta2),
            eps=1e-8, fused=True,
        )
        log.info("[optim] Muon + fused AdamW")

    log.info(f"[optim] Muon={sum(p.numel() for p in muon_p)/1e6:.1f}M  "
             f"AdamW={sum(p.numel() for p in wd_p + no_wd_p)/1e6:.1f}M")
    return muon_opt, adamw_opt


def get_lr(step: int, warmup: int, max_steps: int, peak: float, minimum: float) -> float:
    if step < warmup:
        return peak * (step + 1) / warmup
    if step >= max_steps:
        return minimum
    t = (step - warmup) / (max_steps - warmup)
    return minimum + 0.5 * (peak - minimum) * (1 + math.cos(math.pi * t))


# ══════════════════════════════════════════════════════════════════════════════
#  BATCH SIZE SEARCH
# ══════════════════════════════════════════════════════════════════════════════
MIN_MICRO        = 2
MAX_MICRO        = 128
VRAM_SAFETY_FRAC = 0.70


def _try_bs(model, cfg, device, bs, muon_opt, adamw_opt) -> bool:
    try:
        torch.cuda.empty_cache()
        torch.cuda.reset_peak_memory_stats()
        dummy = torch.randint(0, cfg.vocab_size, (bs, cfg.max_len), device=device)
        with torch.amp.autocast("cuda", dtype=torch.bfloat16):
            loss = model(dummy, targets=dummy)[1]
        loss.backward()
        muon_opt.step(); adamw_opt.step()
        muon_opt.zero_grad(set_to_none=True); adamw_opt.zero_grad(set_to_none=True)
        frac = torch.cuda.max_memory_allocated() / (vram_total_gb() * 1024**3)
        torch.cuda.reset_peak_memory_stats(); torch.cuda.empty_cache()
        return frac <= VRAM_SAFETY_FRAC
    except torch.cuda.OutOfMemoryError:
        torch.cuda.empty_cache()
        muon_opt.zero_grad(set_to_none=True); adamw_opt.zero_grad(set_to_none=True)
        return False


def find_optimal_batch(model, cfg, device, muon_opt, adamw_opt) -> int:
    log.info(f"[batch] searching best micro-batch (≀{VRAM_SAFETY_FRAC:.0%} VRAM) ...")
    if not _try_bs(model, cfg, device, MIN_MICRO, muon_opt, adamw_opt):
        log.warning(f"[batch] bs={MIN_MICRO} already tight β€” using it anyway")
        muon_opt.state.clear(); adamw_opt.state.clear(); torch.cuda.empty_cache()
        return MIN_MICRO
    lo, hi, best = MIN_MICRO, MAX_MICRO, MIN_MICRO
    while lo <= hi:
        mid = (lo + hi) // 2
        if _try_bs(model, cfg, device, mid, muon_opt, adamw_opt):
            best = mid; log.info(f"[batch]   {mid:4d} βœ“"); lo = mid + 1
        else:
            log.info(f"[batch]   {mid:4d} βœ—"); hi = mid - 1
    log.info(f"[batch] β†’ micro_batch = {best}")
    muon_opt.state.clear(); adamw_opt.state.clear(); torch.cuda.empty_cache()
    return best


# ══════════════════════════════════════════════════════════════════════════════
#  CHECKPOINT I/O
# ══════════════════════════════════════════════════════════════════════════════
def save_ckpt(model, muon_opt, adamw_opt, step, epoch, cfg, val_loss) -> bool:
    base      = f"session{SESSION_ID:03d}_s{step:07d}"
    f_model   = os.path.join(TEMP_CKPT_DIR, f"{base}.model.pt")
    f_meta    = os.path.join(TEMP_CKPT_DIR, f"{base}.meta.pt")
    try:
        torch.save({k: v.contiguous() for k, v in model.state_dict().items()}, f_model)
        torch.save(dict(
            step=step, epoch=epoch, val_loss=val_loss,
            config=asdict(cfg),
            muon_optimizer=muon_opt.state_dict(),
            adamw_optimizer=adamw_opt.state_dict(),
            session_id=SESSION_ID,
        ), f_meta)
        ok = upload_to_hf(f_model, f"{base}.model.pt") and upload_to_hf(f_meta, f"{base}.meta.pt")
        os.remove(f_model); os.remove(f_meta)
        if ok: log.info(f"[ckpt] βœ“ {base}")
        else:  log.error(f"[ckpt] upload incomplete for {base}")
        return ok
    except Exception as e:
        log.error(f"[ckpt] save error: {e}")
        for f in (f_model, f_meta):
            try: os.remove(f)
            except FileNotFoundError: pass
        return False


def save_final(model, step, epoch, cfg, val_loss) -> None:
    base    = f"cascadeformer_session{SESSION_ID:03d}_final_s{step:07d}"
    f_model = os.path.join(TEMP_CKPT_DIR, f"{base}.safetensors")
    f_cfg   = os.path.join(TEMP_CKPT_DIR, f"{base}_config.json")
    try:
        sd = {k: v.detach().clone().contiguous() for k, v in model.state_dict().items()}
        if HAS_ST:
            st_save(sd, f_model)
        else:
            f_model = f_model.replace(".safetensors", ".model.pt")
            torch.save(sd, f_model)
        with open(f_cfg, "w") as fh:
            json.dump({**asdict(cfg), "final_step": step,
                       "final_epoch": epoch, "final_val_loss": val_loss,
                       "session_id": SESSION_ID}, fh, indent=2)
        upload_to_hf(f_model, os.path.basename(f_model))
        upload_to_hf(f_cfg,   os.path.basename(f_cfg))
        os.remove(f_model); os.remove(f_cfg)
        log.info(f"[final] βœ“ {base}")
    except Exception as e:
        log.error(f"[final] save error: {e}")
        for f in (f_model, f_cfg):
            try: os.remove(f)
            except FileNotFoundError: pass


def load_ckpt(base_name, model, muon_opt, adamw_opt, device, cfg):
    f_model = hf_hub_download(repo_id=HF_MODEL_REPO, filename=f"{base_name}.model.pt",
                               repo_type="model", cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)
    f_meta  = hf_hub_download(repo_id=HF_MODEL_REPO, filename=f"{base_name}.meta.pt",
                               repo_type="model", cache_dir=TEMP_CKPT_DIR, token=HF_TOKEN)

    sd = torch.load(f_model, map_location=device, weights_only=True)
    missing, unexpected = model.load_state_dict(sd, strict=False)
    if missing:     log.warning(f"[ckpt] {len(missing)} missing keys")
    if unexpected:  log.warning(f"[ckpt] {len(unexpected)} unexpected keys")

    meta = torch.load(f_meta, map_location="cpu", weights_only=False)
    for opt, key in ((muon_opt, "muon_optimizer"), (adamw_opt, "adamw_optimizer")):
        if opt and key in meta:
            try: opt.load_state_dict(meta[key])
            except Exception as e: log.warning(f"[ckpt] {key} not restored: {e}")

    log.info(f"[ckpt] resumed s={meta['step']} e={meta['epoch']} "
             f"val={meta['val_loss']:.4f} session={meta.get('session_id','?')}")
    return meta["step"], meta["epoch"], meta["val_loss"]


# ══════════════════════════════════════════════════════════════════════════════
#  VALIDATION
# ══════════════════════════════════════════════════════════════════════════════
@torch.no_grad()
def run_val(model, val_loader, device, n: int = 100) -> float:
    model.eval()
    losses = []
    it     = iter(val_loader)
    for _ in range(n):
        try:
            b = next(it).to(device, non_blocking=True)
        except StopIteration:
            break
        with torch.amp.autocast("cuda", dtype=torch.bfloat16):
            out = model(b, targets=b)
        losses.append(out[2].item() if len(out) > 2 else out[1].item())
    model.train()
    # reset MoE load buffers that accumulated during eval
    for moe in model.moe_modules():
        moe.nano_load.zero_(); moe.midi_load.zero_()
        moe.macro_load.zero_(); moe.token_count.zero_()
    return float(np.mean(losses)) if losses else float("nan")


# ══════════════════════════════════════════════════════════════════════════════
#  DISPLAY HELPERS
# ══════════════════════════════════════════════════════════════════════════════
_BARS = "β–β–‚β–ƒβ–„β–…β–†β–‡β–ˆ"


def load_bar(fracs, n_experts: int) -> str:
    return "".join(_BARS[min(7, int(f * n_experts * 4))] for f in fracs)


def _fmt_time(seconds: float) -> str:
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = int(seconds % 60)
    return f"{h:02d}h{m:02d}m{s:02d}s"


# ══════════════════════════════════════════════════════════════════════════════
#  GRACEFUL SHUTDOWN
# ══════════════════════════════════════════════════════════════════════════════
def graceful_shutdown(model, muon_opt, adamw_opt, step, epoch, cfg,
                      best_val, device, val_loader, losses, metrics: MetricsLogger):
    log.info("=" * 64)
    log.info("GRACEFUL SHUTDOWN β€” final save")
    log.info("=" * 64)

    save_ckpt(model, muon_opt, adamw_opt, step, epoch, cfg,
              losses[-1] if losses else 0.0)

    fval  = run_val(model, val_loader, device, n=200)
    fppl  = math.exp(min(fval, 20))
    avg_t = float(np.mean(losses[-200:])) if losses else float("nan")

    save_final(model, step, epoch, cfg, fval)
    metrics.log_final(step=step, epoch=epoch, train_loss=avg_t,
                      val_loss=fval, val_ppl=fppl, best_val=best_val)

    report = dict(
        session_id     = SESSION_ID,
        step           = step,
        epoch          = epoch,
        train_loss     = avg_t,
        val_loss       = fval,
        val_ppl        = fppl,
        best_val       = best_val,
        elapsed_h      = elapsed_h(),
        wall_time      = _fmt_time(time.time() - TRAINING_START),
        architecture   = "CascadeFormer",
        total_params_b = model.count_params() / 1e9,
        optimizer      = "Muon+AdamW",
    )

    f_report = os.path.join(TEMP_CKPT_DIR, f"report_session{SESSION_ID:03d}_s{step}.json")
    try:
        with open(f_report, "w") as fh:
            json.dump(report, fh, indent=2)
        upload_to_hf(f_report, os.path.basename(f_report))
        os.remove(f_report)
    except Exception as e:
        log.warning(f"[shutdown] report upload failed: {e}")

    log.info("-" * 64)
    for k, v in report.items():
        log.info(f"  {k:<22}: " + (f"{v:.4f}" if isinstance(v, float) else str(v)))
    log.info("=" * 64)

    metrics.close()   # final flush to HF


# ══════════════════════════════════════════════════════════════════════════════
#  TRAIN
# ══════════════════════════════════════════════════════════════════════════════
def train():
    torch.manual_seed(42); np.random.seed(42); random.seed(42)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    log.info(f"[env] device={device} | "
             f"GPU={torch.cuda.get_device_name(0)} | "
             f"VRAM={vram_total_gb():.0f}GB")
    log.info(f"[env] bnb={HAS_BNB} torchao={HAS_TORCHAO} "
             f"triton={HAS_TRITON} flex_attn={HAS_FLEX_ATTN} safetensors={HAS_ST}")

    ensure_session_repo_exists()
    delete_old_session_repos(keep_last_n=2)

    cfg = CascadeConfig()

    try:
        meta_path = download_dataset_file("metadata.json")
        with open(meta_path) as fh:
            meta = json.load(fh)
        actual_vocab   = meta.get("vocab_size", 32000)
        cfg.vocab_size = (actual_vocab + 63) // 64 * 64
        log.info(f"[data] vocab {actual_vocab} β†’ padded to {cfg.vocab_size}")
    except Exception as e:
        log.info(f"[data] no metadata.json ({e}) β€” using default vocab={cfg.vocab_size}")

    log.info("[model] building CascadeFormer ...")
    model = CascadeFormer(cfg).to(device).to(cfg.dtype)
    model = apply_fp8(model, cfg)
    tot   = model.count_params()
    log.info(f"[model] {tot/1e9:.3f}B params | {vram_str()}")

    muon_opt, adamw_opt = build_optimizers(model, cfg)

    # ── checkpoint resume (uncomment to resume within session 3) ─────────────
    start_step, start_epoch, best_val = 0, 0, float("inf")
    latest = find_latest_checkpoint()
    if latest:
        try:
            start_step, start_epoch, best_val = load_ckpt(
                latest, model, muon_opt, adamw_opt, device, cfg
            )
        except Exception as e:
            log.error(f"[ckpt] resume failed ({e}) β€” fresh start")
            start_step = start_epoch = 0

    model.train()
    model.set_step(start_step)

    chosen_bs       = find_optimal_batch(model, cfg, device, muon_opt, adamw_opt)
    cfg.micro_batch = chosen_bs

    train_inf  = FixedLoader("train_tokens.npy", batch_size=chosen_bs, num_workers=16)
    val_ds     = TokenDataset("val_tokens.npy", epoch=0)
    val_loader = DataLoader(val_ds, batch_size=min(chosen_bs, 32), shuffle=False,
                            num_workers=16, pin_memory=True, drop_last=True)

    metrics = MetricsLogger()

    # ── banner ───────────────────────────────────────────────────────────────
    fp8_tag = "FP8(rowwise)" if resolve_use_fp8(cfg) else "BF16"
    log.info("=" * 64)
    log.info(f"  CascadeFormer Β· Session {SESSION_ID} Β· {tot/1e9:.2f}B params Β· {fp8_tag}")
    log.info(f"  d={cfg.d_model} L={cfg.n_layers} H={cfg.n_heads}/{cfg.n_kv_heads} "
             f"ctx={cfg.max_len}")
    log.info(f"  experts/layer: {cfg.n_nano_experts}Γ—NANO({cfg.nano_hidden}) + "
             f"{cfg.n_midi_experts}Γ—MIDI({cfg.midi_hidden}) + "
             f"{cfg.n_macro_experts}Γ—MACRO({cfg.macro_hidden})")
    log.info(f"  effective batch: {cfg.effective_batch_tokens(chosen_bs):,} tok/step "
             f"(bs={chosen_bs} Γ— accum={cfg.grad_accum} Γ— ctx={cfg.max_len})")
    log.info(f"  budget: {MAX_TRAINING_HOURS}h | fresh start session {SESSION_ID}")
    log.info(f"  metrics: {metrics.local_path} (HF upload every 15 min)")
    log.info("=" * 64)

    step           = start_step
    epoch          = start_epoch
    losses: list   = []
    last_aux       = 0.0
    accum_lm       = 0.0
    accum_n        = 0
    last_ckpt_t    = time.time()
    last_metrics_t = time.time()
    t0             = time.time()

    muon_opt.zero_grad(set_to_none=True)
    adamw_opt.zero_grad(set_to_none=True)
    model.set_step(step)

    while not should_stop():

        # ── fetch batch ──────────────────────────────────────────────────────
        try:
            batch, cur_epoch = next(train_inf)
        except Exception as e:
            log.error(f"[data] fetch error: {e}")
            continue

        if cur_epoch != epoch:
            epoch = cur_epoch
            log.info(f"[data] ── epoch {epoch + 1} start @ step {step} ──")

        batch = batch.to(device, non_blocking=True)
        if batch.shape[1] > cfg.max_len:
            batch = batch[:, :cfg.max_len]

        # ── forward + backward ───────────────────────────────────────────────
        try:
            with torch.amp.autocast("cuda", dtype=torch.bfloat16):
                _, total_loss, lm_loss, aux_loss = model(batch, targets=batch)
                (total_loss / cfg.grad_accum).backward()

            if torch.isnan(lm_loss) or torch.isinf(lm_loss):
                log.error(f"[nan] lm_loss={lm_loss.item():.4f} at step {step} β€” skipping micro-step")
                muon_opt.zero_grad(set_to_none=True)
                adamw_opt.zero_grad(set_to_none=True)
                accum_lm = accum_n = 0
                continue

            accum_lm += lm_loss.item()
            accum_n  += 1
            if accum_n == 1:
                last_aux = aux_loss.item()

        except torch.cuda.OutOfMemoryError:
            torch.cuda.empty_cache()
            muon_opt.zero_grad(set_to_none=True)
            adamw_opt.zero_grad(set_to_none=True)
            accum_lm = accum_n = 0
            log.error("[oom] OOM on forward/backward β€” micro-step skipped")
            continue

        if accum_n < cfg.grad_accum:
            continue

        # ── optimizer step ───────────────────────────────────────────────────
        muon_lr  = get_lr(step, cfg.warmup_steps, cfg.total_steps, cfg.muon_lr,  cfg.muon_min_lr)
        adamw_lr = get_lr(step, cfg.warmup_steps, cfg.total_steps, cfg.adamw_lr, cfg.adamw_min_lr)
        for pg in muon_opt.param_groups:  pg["lr"] = muon_lr
        for pg in adamw_opt.param_groups: pg["lr"] = adamw_lr

        torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.grad_clip)
        muon_opt.step(); adamw_opt.step()
        muon_opt.zero_grad(set_to_none=True); adamw_opt.zero_grad(set_to_none=True)

        avg_lm = accum_lm / cfg.grad_accum
        losses.append(avg_lm)
        if len(losses) > 500: losses.pop(0)

        step += 1
        model.set_step(step)
        accum_lm = accum_n = 0

        # ── logging ──────────────────────────────────────────────────────────
        if step % cfg.log_every == 0:
            elapsed      = time.time() - t0
            sps          = (step - start_step) / max(elapsed, 1e-6)
            tps          = sps * cfg.micro_batch * cfg.grad_accum * cfg.max_len
            sec_per_step = 1.0 / max(sps, 1e-9)
            avg50        = float(np.mean(losses[-50:])) if losses else 0.0
            ppl          = math.exp(min(avg_lm, 20))
            eta_steps    = cfg.total_steps - step
            eta_s        = eta_steps * sec_per_step

            nano_f, midi_f, macro_f, dead, slots = model.moe_read_stats()

            log.info(
                f"step {step:>7,} | ep {epoch + 1} | "
                f"loss {avg_lm:.4f} | avg50 {avg50:.4f} | ppl {ppl:.1f} | "
                f"aux {last_aux:.4f}"
            )
            log.info(
                f"  lr  muon={muon_lr:.2e}  adamw={adamw_lr:.2e} | "
                f"speed {tps/1e3:.0f}K tok/s  {sec_per_step:.2f}s/step | "
                f"vram {vram_str()} | "
                f"elapsed {_fmt_time(elapsed)} | "
                f"eta {_fmt_time(eta_s)} | "
                f"{remaining_h():.2f}h left"
            )
            if nano_f:
                log.info(f"  MoE NANO  [{load_bar(nano_f,  cfg.n_nano_experts)}]")
                log.info(f"  MoE MIDI  [{load_bar(midi_f,  cfg.n_midi_experts)}]")
                log.info(f"  MoE MACRO [{load_bar(macro_f, cfg.n_macro_experts)}]")
                log.info(f"  dead experts {dead}/{slots}")

            metrics.log_train(
                step=step, epoch=epoch, loss=avg_lm, avg50=avg50, ppl=ppl,
                aux_loss=last_aux, muon_lr=muon_lr, adamw_lr=adamw_lr,
                tok_per_sec=tps, sec_per_step=sec_per_step,
                moe_dead=dead, moe_slots=slots,
            )

        # ── validation ───────────────────────────────────────────────────────
        if step % cfg.eval_every == 0:
            vl      = run_val(model, val_loader, device, n=100)
            vpp     = math.exp(min(vl, 20))
            is_best = vl < best_val
            star    = " β˜… new best!" if is_best else ""
            log.info(f"  [val] loss={vl:.4f} ppl={vpp:.2f}{star}")
            if is_best:
                best_val = vl
            metrics.log_val(step=step, epoch=epoch, val_loss=vl,
                            val_ppl=vpp, is_best=is_best)

        # ── step-based checkpoint ─────────────────────────────────────────────
        if step % cfg.ckpt_every == 0:
            ok = save_ckpt(model, muon_opt, adamw_opt, step, epoch, cfg,
                           losses[-1] if losses else 0.0)
            metrics.log_ckpt(step=step, epoch=epoch, ok=ok)
            metrics.flush_to_hf()
            last_ckpt_t = last_metrics_t = time.time()

        # ── time-based checkpoint (every 30 min) ─────────────────────────────
        elif time.time() - last_ckpt_t > 1800:
            ok = save_ckpt(model, muon_opt, adamw_opt, step, epoch, cfg,
                           losses[-1] if losses else 0.0)
            metrics.log_ckpt(step=step, epoch=epoch, ok=ok)
            metrics.flush_to_hf()
            last_ckpt_t = last_metrics_t = time.time()

        # ── metrics-only HF flush (every 15 min between checkpoints) ─────────
        elif time.time() - last_metrics_t > 900:
            metrics.flush_to_hf()
            last_metrics_t = time.time()

    # ── end of training ───────────────────────────────────────────────────────
    graceful_shutdown(
        model, muon_opt, adamw_opt, step, epoch, cfg,
        best_val, device, val_loader, losses, metrics,
    )


if __name__ == "__main__":
    train()