File size: 115,746 Bytes
c39225b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
"""
src/mps_kernels.py

Custom Apple Silicon Metal Compute Shaders (via torch.mps.compile_shader) for Step 3 Training:
1. 2D-Coalesced Conformer ConvModule Kernels (GLU + DepthwiseConv1d(k=15) + Shifted-Mean FP32 BN + SiLU)
2. Fused Conformer Sublayer Epilogues & Activations:
   - Fused LayerNorm (BF16 I/O, FP32 mean/rstd)
   - Fused Bias + Stateless Philox Dropout + Residual Scale + Residual Add + FP32 LayerNorm
   - Fused Bias + GELU + Stateless Philox Dropout
   - Coalesced Multi-Head Attention Split/Merge + Fused Scale/Mask/Online-FP32-Softmax/Philox-Dropout
   - Zero-Allocation Flat-Buffer Linear Projection (in-place addmm_ into flat grad buffers)
3. Fused Reader Tail Kernel (Residual Scale + Mask + FP32-Accumulated L2 Normalization)
4. 100% GPU Fused CosineCTCHead + Online LogSumExp + Active-Target Gather + Custom Metal FP32 Log-CTC
   + Exact Active-Scatter Softmax Backward (0 CPU Roundtrip, 0 Per-Step Sync, Cached Spherical Bank)
5. Zero-Sync Contiguous Flat-Buffer Fused Metal GradNorm + In-Kernel Clipped AdamW (FP32 Master Weights)
"""

from __future__ import annotations

from collections import OrderedDict
import math
import random
from typing import Dict, Tuple, List, Optional, Any

import torch
import torch.nn as nn
import torch.nn.functional as F

_METAL_SHADER_SOURCE = r"""
#include <metal_stdlib>
using namespace metal;

// ============================================================================
// 0. Stateless Philox-2x32 RNG, Fast Math & Reduction Epilogues
// ============================================================================

inline float philox_keep_scale(uint seed_lo, uint seed_hi, uint idx, float drop_p, float inv_keep) {
    if (drop_p <= 0.0f) return 1.0f;
    uint ctr0 = idx;
    uint ctr1 = seed_hi ^ 0x9E3779B9u;
    uint key = seed_lo;
    for (int r = 0; r < 4; ++r) {
        uint hi = mulhi(0xD256D193u, ctr0);
        uint lo = 0xD256D193u * ctr0;
        ctr0 = hi ^ key ^ ctr1;
        ctr1 = lo;
        key += 0x9E3779B9u;
    }
    float u = float(ctr0 >> 8) * (1.0f / 16777216.0f);
    return (u >= drop_p) ? inv_keep : 0.0f;
}

inline float erf_approx_fp32(float x) {
    float sign = (x < 0.0f) ? -1.0f : 1.0f;
    float ax = metal::min(metal::abs(x), 10.0f);
    float t = 1.0f / (1.0f + 0.3275911f * ax);
    float poly = (((((1.061405429f * t - 1.453152027f) * t) + 1.421413741f) * t - 0.284496736f) * t + 0.254829592f) * t;
    return sign * (1.0f - poly * metal::exp(-ax * ax));
}

inline float log_add(float a, float b) {
    if (a == -INFINITY) return b;
    if (b == -INFINITY) return a;
    float m = metal::max(a, b);
    return m + metal::log(1.0f + metal::exp(-metal::abs(a - b)));
}

inline float log_add3(float a, float b, float c) {
    float m = metal::max(a, metal::max(b, c));
    if (m == -INFINITY) return -INFINITY;
    return m + metal::log(
        ((a == -INFINITY) ? 0.0f : metal::exp(a - m)) +
        ((b == -INFINITY) ? 0.0f : metal::exp(b - m)) +
        ((c == -INFINITY) ? 0.0f : metal::exp(c - m))
    );
}

kernel void accum_reset_fp32_to_bf16(
    device float* src_fp32 [[buffer(0)]],
    device bfloat* dst_bf16 [[buffer(1)]],
    constant int& n [[buffer(2)]],
    uint gid [[thread_position_in_grid]]
) {
    if (int(gid) >= n) return;
    float v = src_fp32[gid];
    src_fp32[gid] = 0.0f;
    dst_bf16[gid] = bfloat(float(dst_bf16[gid]) + v);
}

kernel void copy_reset_fp32_to_bf16(
    device float* src_fp32 [[buffer(0)]],
    device bfloat* dst_bf16 [[buffer(1)]],
    constant int& n [[buffer(2)]],
    uint gid [[thread_position_in_grid]]
) {
    if (int(gid) >= n) return;
    float v = src_fp32[gid];
    src_fp32[gid] = 0.0f;
    dst_bf16[gid] = bfloat(v);
}

kernel void accum_reset_two_bf16(
    device float* src_fp32 [[buffer(0)]],
    device bfloat* dst1_bf16 [[buffer(1)]],
    device bfloat* dst2_bf16 [[buffer(2)]],
    constant int& n1 [[buffer(3)]],
    constant int& n2 [[buffer(4)]],
    uint gid [[thread_position_in_grid]]
) {
    int i = int(gid);
    if (i >= n1 + n2) return;
    float v = src_fp32[i];
    src_fp32[i] = 0.0f;
    if (i < n1) {
        dst1_bf16[i] = bfloat(float(dst1_bf16[i]) + v);
    } else {
        int j = i - n1;
        dst2_bf16[j] = bfloat(float(dst2_bf16[j]) + v);
    }
}

kernel void accum_reset_two_fp32(
    device float* src_fp32 [[buffer(0)]],
    device float* dst1_fp32 [[buffer(1)]],
    device float* dst2_fp32 [[buffer(2)]],
    constant int& D [[buffer(3)]],
    uint gid [[thread_position_in_grid]]
) {
    int i = int(gid);
    if (i >= 2 * D) return;
    float v = src_fp32[i];
    src_fp32[i] = 0.0f;
    if (i < D) dst1_fp32[i] += v;
    else dst2_fp32[i - D] += v;
}

kernel void copy_reset_two_fp32(
    device float* src_fp32 [[buffer(0)]],
    device float* dst1_fp32 [[buffer(1)]],
    device float* dst2_fp32 [[buffer(2)]],
    constant int& D [[buffer(3)]],
    uint gid [[thread_position_in_grid]]
) {
    int i = int(gid);
    if (i >= 2 * D) return;
    float v = src_fp32[i];
    src_fp32[i] = 0.0f;
    if (i < D) dst1_fp32[i] = v;
    else dst2_fp32[i - D] = v;
}

// ============================================================================
// 1. 2D-Coalesced Conformer ConvModule Kernels (GLU + DWConv15 + BN + SiLU)
// ============================================================================

kernel void glu_fwd_bf16(
    device const bfloat* u [[buffer(0)]],
    device bfloat* glu_out [[buffer(1)]],
    constant int& BT [[buffer(2)]],
    constant int& D [[buffer(3)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    if (d >= D || bt >= BT) return;
    int base = bt * (2 * D) + d;
    float a = float(u[base]);
    float b = float(u[base + D]);
    float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-b, -80.0f, 80.0f)));
    glu_out[bt * D + d] = bfloat(a * sig);
}

kernel void dwconv15_stats_coalesced_fwd_bf16(
    device const bfloat* glu_in [[buffer(0)]],
    device const bfloat* weight [[buffer(1)]],
    device const float* running_mean [[buffer(2)]],
    device bfloat* dw_out [[buffer(3)]],
    device atomic_float* stats_buf [[buffer(4)]], // [2 * D]: sum_delta, sum_delta2
    constant int& B [[buffer(5)]],
    constant int& T [[buffer(6)]],
    constant int& D [[buffer(7)]],
    uint2 gid [[thread_position_in_grid]],
    uint2 lid [[thread_position_in_threadgroup]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    int BT = B * T;
    int dx = int(lid.x);
    int ty = int(lid.y);

    threadgroup float sh_d[8][33];
    threadgroup float sh_d2[8][33];

    float delta = 0.0f;
    float delta2 = 0.0f;

    if (d < D && bt < BT) {
        int b = bt / T;
        int t = bt % T;
        device const bfloat* x_b = glu_in + b * T * D + d;
        device const bfloat* w_d = weight + d * 15;
        float acc = 0.0f;
        int k_start = max(0, 7 - t);
        int k_end = min(15, T + 7 - t);
        for (int k = k_start; k < k_end; ++k) {
            acc += float(x_b[(t + k - 7) * D]) * float(w_d[k]);
        }
        bfloat acc_bf = bfloat(acc);
        dw_out[bt * D + d] = acc_bf;
        delta = float(acc_bf) - running_mean[d];
        delta2 = delta * delta;
    }

    sh_d[ty][dx] = delta;
    sh_d2[ty][dx] = delta2;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (ty == 0 && d < D) {
        float sd = 0.0f, sd2 = 0.0f;
        for (int i = 0; i < 8; ++i) {
            sd += sh_d[i][dx];
            sd2 += sh_d2[i][dx];
        }
        atomic_fetch_add_explicit(&stats_buf[d], sd, memory_order_relaxed);
        atomic_fetch_add_explicit(&stats_buf[D + d], sd2, memory_order_relaxed);
    }
}

kernel void bn_finalize_stats_fp32(
    device float* stats_buf [[buffer(0)]],
    device float* running_mean [[buffer(1)]],
    device float* running_var [[buffer(2)]],
    device float* saved_mean [[buffer(3)]],
    device float* saved_rstd [[buffer(4)]],
    constant int& BT [[buffer(5)]],
    constant int& D [[buffer(6)]],
    uint gid [[thread_position_in_grid]]
) {
    int d = int(gid);
    if (d >= D) return;
    float sum_d = stats_buf[d];
    float sum_d2 = stats_buf[D + d];
    stats_buf[d] = 0.0f;
    stats_buf[D + d] = 0.0f;

    float fBT = float(BT);
    float c = running_mean[d];
    float d_mean = sum_d / fBT;
    float mean = c + d_mean;
    float s2 = metal::max(0.0f, sum_d2 - fBT * d_mean * d_mean);
    float var = s2 / fBT;
    float rstd = metal::rsqrt(var + 1e-5f);

    saved_mean[d] = mean;
    saved_rstd[d] = rstd;
    float uvar = (BT > 1) ? (s2 / float(BT - 1)) : var;
    running_mean[d] = 0.9f * c + 0.1f * mean;
    running_var[d] = 0.9f * running_var[d] + 0.1f * uvar;
}

kernel void bn_silu_coalesced_fwd_bf16(
    device const bfloat* dw_out [[buffer(0)]],
    device const float* gamma [[buffer(1)]],
    device const float* beta [[buffer(2)]],
    device const float* saved_mean [[buffer(3)]],
    device const float* saved_rstd [[buffer(4)]],
    device bfloat* out [[buffer(5)]],
    constant int& BT [[buffer(6)]],
    constant int& D [[buffer(7)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    if (d >= D || bt >= BT) return;
    int idx = bt * D + d;
    float v = float(dw_out[idx]);
    float y = (v - saved_mean[d]) * saved_rstd[d] * gamma[d] + beta[d];
    float silu_y = y / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
    out[idx] = bfloat(silu_y);
}

kernel void dwconv15_bn_silu_eval_coalesced_fwd_bf16(
    device const bfloat* glu_in [[buffer(0)]],
    device const bfloat* weight [[buffer(1)]],
    device const float* gamma [[buffer(2)]],
    device const float* beta [[buffer(3)]],
    device const float* running_mean [[buffer(4)]],
    device const float* running_var [[buffer(5)]],
    device bfloat* out [[buffer(6)]],
    constant int& B [[buffer(7)]],
    constant int& T [[buffer(8)]],
    constant int& D [[buffer(9)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    if (d >= D || bt >= B * T) return;

    int b = bt / T;
    int t = bt % T;
    device const bfloat* x_b = glu_in + b * T * D + d;
    device const bfloat* w_d = weight + d * 15;

    float acc = 0.0f;
    int k_start = max(0, 7 - t);
    int k_end = min(15, T + 7 - t);
    for (int k = k_start; k < k_end; ++k) {
        acc += float(x_b[(t + k - 7) * D]) * float(w_d[k]);
    }
    float v = float(bfloat(acc));
    float inv_std = metal::rsqrt(running_var[d] + 1e-5f);
    float y = (v - running_mean[d]) * inv_std * gamma[d] + beta[d];
    float silu_y = y / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
    out[bt * D + d] = bfloat(silu_y);
}

kernel void bn_silu_bwd_stats_coalesced_bf16(
    device const bfloat* grad_out [[buffer(0)]],
    device const bfloat* dw_out [[buffer(1)]],
    device const float* gamma [[buffer(2)]],
    device const float* beta [[buffer(3)]],
    device const float* saved_mean [[buffer(4)]],
    device const float* saved_rstd [[buffer(5)]],
    device atomic_float* bwd_stats [[buffer(6)]], // [2 * D]: [0..D-1] dgamma, [D..2D-1] dbeta
    constant int& BT [[buffer(7)]],
    constant int& D [[buffer(8)]],
    uint2 gid [[thread_position_in_grid]],
    uint2 lid [[thread_position_in_threadgroup]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    int dx = int(lid.x);
    int ty = int(lid.y);

    threadgroup float sh_dy_xh[8][33];
    threadgroup float sh_dy[8][33];

    float dy = 0.0f;
    float dy_xh = 0.0f;
    if (d < D && bt < BT) {
        int idx = bt * D + d;
        float xv = float(dw_out[idx]);
        float go = float(grad_out[idx]);
        float xhat = (xv - saved_mean[d]) * saved_rstd[d];
        float y = xhat * gamma[d] + beta[d];
        float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
        dy = go * sig * (1.0f + y * (1.0f - sig));
        dy_xh = dy * xhat;
    }
    sh_dy_xh[ty][dx] = dy_xh;
    sh_dy[ty][dx] = dy;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (ty == 0 && d < D) {
        float s_xh = 0.0f, s_dy = 0.0f;
        for (int i = 0; i < 8; ++i) {
            s_xh += sh_dy_xh[i][dx];
            s_dy += sh_dy[i][dx];
        }
        atomic_fetch_add_explicit(&bwd_stats[d], s_xh, memory_order_relaxed);
        atomic_fetch_add_explicit(&bwd_stats[D + d], s_dy, memory_order_relaxed);
    }
}

kernel void bn_bwd_dx_coalesced_bf16(
    device const bfloat* grad_out [[buffer(0)]],
    device const bfloat* dw_out [[buffer(1)]],
    device const float* gamma [[buffer(2)]],
    device const float* beta [[buffer(3)]],
    device const float* saved_mean [[buffer(4)]],
    device const float* saved_rstd [[buffer(5)]],
    device const float* bwd_stats [[buffer(6)]],
    device bfloat* grad_dw [[buffer(7)]],
    constant int& BT [[buffer(8)]],
    constant int& D [[buffer(9)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    if (d >= D || bt >= BT) return;

    int idx = bt * D + d;
    float m = saved_mean[d];
    float rstd = saved_rstd[d];
    float g = gamma[d];
    float xhat = (float(dw_out[idx]) - m) * rstd;
    float y = xhat * g + beta[d];
    float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-y, -80.0f, 80.0f)));
    float dy = float(grad_out[idx]) * sig * (1.0f + y * (1.0f - sig));

    float tot_dy_xh = bwd_stats[d];
    float tot_dy = bwd_stats[D + d];
    float scale = g * rstd / float(BT);
    grad_dw[idx] = bfloat(scale * (float(BT) * dy - tot_dy - xhat * tot_dy_xh));
}

kernel void dwconv15_bwd_w_simd_bf16(
    device const bfloat* grad_dw [[buffer(0)]],
    device const bfloat* glu_in [[buffer(1)]],
    device bfloat* dst_w_bf16 [[buffer(2)]],
    constant int& B [[buffer(3)]],
    constant int& T [[buffer(4)]],
    constant int& D [[buffer(5)]],
    constant int& accum_mode [[buffer(6)]],
    uint d [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    if (int(d) >= D) return;
    int BT = B * T;
    float acc[15];
    for (int k = 0; k < 15; ++k) acc[k] = 0.0f;

    for (int bt = int(tid); bt < BT; bt += 256) {
        int b = bt / T;
        int t = bt % T;
        float gdw = float(grad_dw[bt * D + int(d)]);
        device const bfloat* x_b = glu_in + b * T * D + int(d);
        int k_start = max(0, 7 - t);
        int k_end = min(15, T + 7 - t);
        for (int k = k_start; k < k_end; ++k) {
            acc[k] += gdw * float(x_b[(t + k - 7) * D]);
        }
    }

    threadgroup float sh[8][16];
    for (int k = 0; k < 15; ++k) {
        float s = simd_sum(acc[k]);
        if (lane == 0) sh[sgid][k] = s;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (tid < 15u) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh[i][tid];
        uint out_idx = d * 15u + tid;
        if (accum_mode != 0) {
            dst_w_bf16[out_idx] = bfloat(float(dst_w_bf16[out_idx]) + tot);
        } else {
            dst_w_bf16[out_idx] = bfloat(tot);
        }
    }
}

kernel void dwconv15_glu_bwd_x_bf16(
    device const bfloat* grad_dw [[buffer(0)]],
    device const bfloat* weight [[buffer(1)]],
    device const bfloat* u [[buffer(2)]],
    device bfloat* grad_u [[buffer(3)]],
    constant int& B [[buffer(4)]],
    constant int& T [[buffer(5)]],
    constant int& D [[buffer(6)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    if (d >= D || bt >= B * T) return;

    int b = bt / T;
    int t = bt % T;
    device const bfloat* go_b = grad_dw + b * T * D + d;
    device const bfloat* w_d = weight + d * 15;

    float grad_glu = 0.0f;
    int k_start = max(0, t + 7 - (T - 1));
    int k_end = min(15, t + 8);
    for (int k = k_start; k < k_end; ++k) {
        grad_glu += float(go_b[(t - k + 7) * D]) * float(w_d[k]);
    }

    uint u_base = uint(bt) * uint(2 * D) + uint(d);
    float a = float(u[u_base]);
    float b_val = float(u[u_base + D]);
    float sig = 1.0f / (1.0f + metal::exp(metal::clamp(-b_val, -80.0f, 80.0f)));
    grad_u[u_base] = bfloat(grad_glu * sig);
    grad_u[u_base + D] = bfloat(grad_glu * a * sig * (1.0f - sig));
}

// ============================================================================
// 2. Fused LayerNorm, Bias+Drop+Res+LN, Bias+GELU+Drop, and Self-Attention
// ============================================================================

kernel void layernorm_fwd_bf16(
    device const bfloat* x [[buffer(0)]],
    device const bfloat* gamma [[buffer(1)]],
    device const bfloat* beta [[buffer(2)]],
    device bfloat* y [[buffer(3)]],
    device float* mean_out [[buffer(4)]],
    device float* rstd_out [[buffer(5)]],
    constant int& D [[buffer(6)]],
    uint bt [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    uint base = bt * uint(D);
    float v0 = (int(tid) < D) ? float(x[base + tid]) : 0.0f;
    float v1 = (int(tid) + 256 < D) ? float(x[base + tid + 256u]) : 0.0f;
    float s = simd_sum(v0 + v1);

    threadgroup float sh[8];
    if (lane == 0) sh[sgid] = s;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_mean;
    if (tid == 0) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh[i];
        s_mean = tot / float(D);
        mean_out[bt] = s_mean;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float m = s_mean;
    float d0 = (int(tid) < D) ? (v0 - m) : 0.0f;
    float d1 = (int(tid) + 256 < D) ? (v1 - m) : 0.0f;
    float sq = simd_sum(d0 * d0 + d1 * d1);
    if (lane == 0) sh[sgid] = sq;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_rstd;
    if (tid == 0) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh[i];
        float r = metal::rsqrt(tot / float(D) + 1e-5f);
        s_rstd = r;
        rstd_out[bt] = r;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float r = s_rstd;
    if (int(tid) < D) {
        y[base + tid] = bfloat(d0 * r * float(gamma[tid]) + float(beta[tid]));
    }
    if (int(tid) + 256 < D) {
        uint c = tid + 256u;
        y[base + c] = bfloat(d1 * r * float(gamma[c]) + float(beta[c]));
    }
}

kernel void layernorm_bwd_bf16(
    device const bfloat* grad_y [[buffer(0)]],
    device const bfloat* x [[buffer(1)]],
    device const bfloat* gamma [[buffer(2)]],
    device const float* mean_in [[buffer(3)]],
    device const float* rstd_in [[buffer(4)]],
    device bfloat* grad_x [[buffer(5)]],
    device atomic_float* scratch_grads [[buffer(6)]], // [2 * D]: dgamma, dbeta
    constant int& D [[buffer(7)]],
    uint bt [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    uint base = bt * uint(D);
    float m = mean_in[bt];
    float r = rstd_in[bt];

    float gy0 = 0.0f, gy1 = 0.0f;
    float xh0 = 0.0f, xh1 = 0.0f;
    float dy0 = 0.0f, dy1 = 0.0f;

    if (int(tid) < D) {
        uint idx = base + tid;
        gy0 = float(grad_y[idx]);
        xh0 = (float(x[idx]) - m) * r;
        dy0 = gy0 * float(gamma[tid]);
        atomic_fetch_add_explicit(&scratch_grads[tid], gy0 * xh0, memory_order_relaxed);
        atomic_fetch_add_explicit(&scratch_grads[uint(D) + tid], gy0, memory_order_relaxed);
    }
    if (int(tid) + 256 < D) {
        uint c = tid + 256u;
        uint idx = base + c;
        gy1 = float(grad_y[idx]);
        xh1 = (float(x[idx]) - m) * r;
        dy1 = gy1 * float(gamma[c]);
        atomic_fetch_add_explicit(&scratch_grads[c], gy1 * xh1, memory_order_relaxed);
        atomic_fetch_add_explicit(&scratch_grads[uint(D) + c], gy1, memory_order_relaxed);
    }

    float s_dy = simd_sum(dy0 + dy1);
    float s_dy_xh = simd_sum(dy0 * xh0 + dy1 * xh1);

    threadgroup float sh1[8];
    threadgroup float sh2[8];
    if (lane == 0) {
        sh1[sgid] = s_dy;
        sh2[sgid] = s_dy_xh;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float tot_dy;
    threadgroup float tot_dy_xh;
    if (tid == 0) {
        float a = 0.0f, b = 0.0f;
        for (int i = 0; i < 8; ++i) { a += sh1[i]; b += sh2[i]; }
        tot_dy = a;
        tot_dy_xh = b;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float invD = 1.0f / float(D);
    float m_dy = tot_dy * invD;
    float m_dy_xh = tot_dy_xh * invD;

    if (int(tid) < D) {
        grad_x[base + tid] = bfloat(r * (dy0 - m_dy - xh0 * m_dy_xh));
    }
    if (int(tid) + 256 < D) {
        uint c = tid + 256u;
        grad_x[base + c] = bfloat(r * (dy1 - m_dy - xh1 * m_dy_xh));
    }
}

kernel void fused_bias_drop_res_ln_fwd_bf16(
    device const bfloat* x_res [[buffer(0)]],
    device const bfloat* sub_nobias [[buffer(1)]],
    device const bfloat* sub_bias [[buffer(2)]],
    device const bfloat* gamma [[buffer(3)]],
    device const bfloat* beta [[buffer(4)]],
    device bfloat* x_out [[buffer(5)]],
    device bfloat* normed_out [[buffer(6)]],
    device float* mean_out [[buffer(7)]],
    device float* rstd_out [[buffer(8)]],
    constant int& D [[buffer(9)]],
    constant float& res_scale [[buffer(10)]],
    constant float& drop_p [[buffer(11)]],
    constant float& inv_keep [[buffer(12)]],
    constant uint& seed_lo [[buffer(13)]],
    constant uint& seed_hi [[buffer(14)]],
    uint bt [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    uint base = bt * uint(D);
    float v0 = 0.0f, v1 = 0.0f;
    if (int(tid) < D) {
        uint idx = base + tid;
        float u = float(sub_nobias[idx]) + float(sub_bias[tid]);
        float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
        bfloat x_bf = bfloat(float(x_res[idx]) + res_scale * (u * kp));
        x_out[idx] = x_bf;
        v0 = float(x_bf);
    }
    if (int(tid) + 256 < D) {
        uint c = tid + 256u;
        uint idx = base + c;
        float u = float(sub_nobias[idx]) + float(sub_bias[c]);
        float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
        bfloat x_bf = bfloat(float(x_res[idx]) + res_scale * (u * kp));
        x_out[idx] = x_bf;
        v1 = float(x_bf);
    }

    float s = simd_sum(v0 + v1);
    threadgroup float sh[8];
    if (lane == 0) sh[sgid] = s;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_mean;
    if (tid == 0) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh[i];
        s_mean = tot / float(D);
        mean_out[bt] = s_mean;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float m = s_mean;
    float d0 = (int(tid) < D) ? (v0 - m) : 0.0f;
    float d1 = (int(tid) + 256 < D) ? (v1 - m) : 0.0f;
    float sq = simd_sum(d0 * d0 + d1 * d1);
    if (lane == 0) sh[sgid] = sq;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_rstd;
    if (tid == 0) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh[i];
        float r = metal::rsqrt(tot / float(D) + 1e-5f);
        s_rstd = r;
        rstd_out[bt] = r;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float r = s_rstd;
    if (int(tid) < D) {
        normed_out[base + tid] = bfloat(d0 * r * float(gamma[tid]) + float(beta[tid]));
    }
    if (int(tid) + 256 < D) {
        uint c = tid + 256u;
        normed_out[base + c] = bfloat(d1 * r * float(gamma[c]) + float(beta[c]));
    }
}

kernel void fused_bias_drop_res_ln_bwd_bf16(
    device const bfloat* grad_normed [[buffer(0)]],
    device const bfloat* grad_x_out [[buffer(1)]],
    device const bfloat* x_out [[buffer(2)]],
    device const bfloat* gamma [[buffer(3)]],
    device const float* mean_in [[buffer(4)]],
    device const float* rstd_in [[buffer(5)]],
    device bfloat* grad_x_res [[buffer(6)]],
    device bfloat* grad_sub_nobias [[buffer(7)]],
    device atomic_float* scratch_grads [[buffer(8)]], // [3 * D]: dgamma, dbeta, dsub_bias
    constant int& D [[buffer(9)]],
    constant int& has_grad_normed [[buffer(10)]],
    constant int& has_grad_x_out [[buffer(11)]],
    constant float& res_scale [[buffer(12)]],
    constant float& drop_p [[buffer(13)]],
    constant float& inv_keep [[buffer(14)]],
    constant uint& seed_lo [[buffer(15)]],
    constant uint& seed_hi [[buffer(16)]],
    uint bt [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    uint base = bt * uint(D);
    float m = mean_in[bt];
    float r = rstd_in[bt];

    float gn0 = 0.0f, gn1 = 0.0f;
    float xh0 = 0.0f, xh1 = 0.0f;
    float dy0 = 0.0f, dy1 = 0.0f;

    if (has_grad_normed != 0) {
        if (int(tid) < D) {
            uint idx = base + tid;
            gn0 = float(grad_normed[idx]);
            xh0 = (float(x_out[idx]) - m) * r;
            dy0 = gn0 * float(gamma[tid]);
            atomic_fetch_add_explicit(&scratch_grads[tid], gn0 * xh0, memory_order_relaxed);
            atomic_fetch_add_explicit(&scratch_grads[uint(D) + tid], gn0, memory_order_relaxed);
        }
        if (int(tid) + 256 < D) {
            uint c = tid + 256u;
            uint idx = base + c;
            gn1 = float(grad_normed[idx]);
            xh1 = (float(x_out[idx]) - m) * r;
            dy1 = gn1 * float(gamma[c]);
            atomic_fetch_add_explicit(&scratch_grads[c], gn1 * xh1, memory_order_relaxed);
            atomic_fetch_add_explicit(&scratch_grads[uint(D) + c], gn1, memory_order_relaxed);
        }
    }

    float s_dy = simd_sum(dy0 + dy1);
    float s_dy_xh = simd_sum(dy0 * xh0 + dy1 * xh1);

    threadgroup float sh1[8];
    threadgroup float sh2[8];
    if (lane == 0) {
        sh1[sgid] = s_dy;
        sh2[sgid] = s_dy_xh;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float tot_dy;
    threadgroup float tot_dy_xh;
    if (tid == 0) {
        float a = 0.0f, b = 0.0f;
        for (int i = 0; i < 8; ++i) { a += sh1[i]; b += sh2[i]; }
        tot_dy = a;
        tot_dy_xh = b;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float invD = 1.0f / float(D);
    float m_dy = tot_dy * invD;
    float m_dy_xh = tot_dy_xh * invD;

    if (int(tid) < D) {
        uint idx = base + tid;
        float dx_ln = (has_grad_normed != 0) ? (r * (dy0 - m_dy - xh0 * m_dy_xh)) : 0.0f;
        float gx = dx_ln + ((has_grad_x_out != 0) ? float(grad_x_out[idx]) : 0.0f);
        grad_x_res[idx] = bfloat(gx);
        float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
        bfloat gsub_bf = bfloat(gx * res_scale * kp);
        grad_sub_nobias[idx] = gsub_bf;
        atomic_fetch_add_explicit(&scratch_grads[2u * uint(D) + tid], float(gsub_bf), memory_order_relaxed);
    }
    if (int(tid) + 256 < D) {
        uint c = tid + 256u;
        uint idx = base + c;
        float dx_ln = (has_grad_normed != 0) ? (r * (dy1 - m_dy - xh1 * m_dy_xh)) : 0.0f;
        float gx = dx_ln + ((has_grad_x_out != 0) ? float(grad_x_out[idx]) : 0.0f);
        grad_x_res[idx] = bfloat(gx);
        float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
        bfloat gsub_bf = bfloat(gx * res_scale * kp);
        grad_sub_nobias[idx] = gsub_bf;
        atomic_fetch_add_explicit(&scratch_grads[2u * uint(D) + c], float(gsub_bf), memory_order_relaxed);
    }
}

kernel void fused_bias_gelu_drop_fwd_bf16(
    device const bfloat* z_nobias [[buffer(0)]],
    device const bfloat* bias [[buffer(1)]],
    device bfloat* out [[buffer(2)]],
    constant int& BT [[buffer(3)]],
    constant int& D [[buffer(4)]],
    constant float& drop_p [[buffer(5)]],
    constant float& inv_keep [[buffer(6)]],
    constant uint& seed_lo [[buffer(7)]],
    constant uint& seed_hi [[buffer(8)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    if (d >= D || bt >= BT) return;
    uint idx = uint(bt) * uint(D) + uint(d);
    float x = float(z_nobias[idx]) + float(bias[d]);
    float cdf = 0.5f * (1.0f + erf_approx_fp32(x * 0.7071067811865475f));
    float g = x * cdf;
    float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
    out[idx] = bfloat(g * kp);
}

kernel void fused_bias_gelu_drop_bwd_bf16(
    device const bfloat* grad_out [[buffer(0)]],
    device const bfloat* z_nobias [[buffer(1)]],
    device const bfloat* bias [[buffer(2)]],
    device bfloat* grad_z [[buffer(3)]],
    device atomic_float* grad_bias_fp32 [[buffer(4)]],
    constant int& BT [[buffer(5)]],
    constant int& D [[buffer(6)]],
    constant float& drop_p [[buffer(7)]],
    constant float& inv_keep [[buffer(8)]],
    constant uint& seed_lo [[buffer(9)]],
    constant uint& seed_hi [[buffer(10)]],
    uint2 gid [[thread_position_in_grid]],
    uint2 lid [[thread_position_in_threadgroup]]
) {
    int d = int(gid.x);
    int bt = int(gid.y);
    int dx = int(lid.x);
    int ty = int(lid.y);

    threadgroup float sh_gb[8][33];
    float gb = 0.0f;

    if (d < D && bt < BT) {
        uint idx = uint(bt) * uint(D) + uint(d);
        float x = float(z_nobias[idx]) + float(bias[d]);
        float cdf = 0.5f * (1.0f + erf_approx_fp32(x * 0.7071067811865475f));
        float xc = metal::clamp(x, -14.0f, 14.0f);
        float pdf = 0.3989422804014327f * metal::exp(-0.5f * xc * xc);
        float dgelu = cdf + x * pdf;
        float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
        bfloat gz_bf = bfloat(float(grad_out[idx]) * kp * dgelu);
        grad_z[idx] = gz_bf;
        gb = float(gz_bf);
    }
    sh_gb[ty][dx] = gb;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (ty == 0 && d < D) {
        float s = 0.0f;
        for (int i = 0; i < 8; ++i) s += sh_gb[i][dx];
        atomic_fetch_add_explicit(&grad_bias_fp32[d], s, memory_order_relaxed);
    }
}

kernel void qkv_split_heads_bf16(
    device const bfloat* qkv [[buffer(0)]], // [B, T, 3, H, Dh]
    device bfloat* q_out [[buffer(1)]],     // [B*H, T, Dh]
    device bfloat* k_out [[buffer(2)]],     // [B*H, T, Dh]
    device bfloat* v_out [[buffer(3)]],     // [B*H, T, Dh]
    constant int& B [[buffer(4)]],
    constant int& T [[buffer(5)]],
    constant int& H [[buffer(6)]],
    constant int& Dh [[buffer(7)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int hd = int(gid.x);
    int bt = int(gid.y);
    int HD = H * Dh;
    if (hd >= HD || bt >= B * T) return;

    int b = bt / T;
    int t = bt % T;
    int h = hd / Dh;
    int d = hd % Dh;

    int in_base = bt * (3 * HD);
    int out_idx = ((b * H + h) * T + t) * Dh + d;
    q_out[out_idx] = qkv[in_base + hd];
    k_out[out_idx] = qkv[in_base + HD + hd];
    v_out[out_idx] = qkv[in_base + 2 * HD + hd];
}

kernel void qkv_merge_heads_bf16(
    device const bfloat* gq [[buffer(0)]],
    device const bfloat* gk [[buffer(1)]],
    device const bfloat* gv [[buffer(2)]],
    device bfloat* gqkv [[buffer(3)]],
    constant int& B [[buffer(4)]],
    constant int& T [[buffer(5)]],
    constant int& H [[buffer(6)]],
    constant int& Dh [[buffer(7)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int hd = int(gid.x);
    int bt = int(gid.y);
    int HD = H * Dh;
    if (hd >= HD || bt >= B * T) return;

    int b = bt / T;
    int t = bt % T;
    int h = hd / Dh;
    int d = hd % Dh;

    int in_idx = ((b * H + h) * T + t) * Dh + d;
    int out_base = bt * (3 * HD);
    gqkv[out_base + hd] = gq[in_idx];
    gqkv[out_base + HD + hd] = gk[in_idx];
    gqkv[out_base + 2 * HD + hd] = gv[in_idx];
}

kernel void attn_merge_ctx_bf16(
    device const bfloat* ctx_bh [[buffer(0)]], // [B*H, T, Dh]
    device bfloat* ctx_out [[buffer(1)]],      // [B, T, H*Dh]
    constant int& B [[buffer(2)]],
    constant int& T [[buffer(3)]],
    constant int& H [[buffer(4)]],
    constant int& Dh [[buffer(5)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int hd = int(gid.x);
    int bt = int(gid.y);
    int HD = H * Dh;
    if (hd >= HD || bt >= B * T) return;
    int b = bt / T;
    int t = bt % T;
    int h = hd / Dh;
    int d = hd % Dh;
    ctx_out[bt * HD + hd] = ctx_bh[((b * H + h) * T + t) * Dh + d];
}

kernel void attn_split_ctx_bf16(
    device const bfloat* gctx [[buffer(0)]],   // [B, T, H*Dh]
    device bfloat* gctx_bh [[buffer(1)]],      // [B*H, T, Dh]
    constant int& B [[buffer(2)]],
    constant int& T [[buffer(3)]],
    constant int& H [[buffer(4)]],
    constant int& Dh [[buffer(5)]],
    uint2 gid [[thread_position_in_grid]]
) {
    int hd = int(gid.x);
    int bt = int(gid.y);
    int HD = H * Dh;
    if (hd >= HD || bt >= B * T) return;
    int b = bt / T;
    int t = bt % T;
    int h = hd / Dh;
    int d = hd % Dh;
    gctx_bh[((b * H + h) * T + t) * Dh + d] = gctx[bt * HD + hd];
}

kernel void attn_scale_mask_softmax_drop_fwd_bf16(
    device const bfloat* scores [[buffer(0)]], // [B*H, T, T]
    device const bool* key_mask [[buffer(1)]], // [B, T] (true = pad)
    device bfloat* probs_drop [[buffer(2)]],   // [B*H, T, T]
    device float* lse_out [[buffer(3)]],       // [B*H, T]
    constant int& B [[buffer(4)]],
    constant int& H [[buffer(5)]],
    constant int& T [[buffer(6)]],
    constant int& has_mask [[buffer(7)]],
    constant float& scale [[buffer(8)]],
    constant float& drop_p [[buffer(9)]],
    constant float& inv_keep [[buffer(10)]],
    constant uint& seed_lo [[buffer(11)]],
    constant uint& seed_hi [[buffer(12)]],
    uint row [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    int total_rows = B * H * T;
    if (int(row) >= total_rows) return;
    int bh = int(row) / T;
    int b = bh / H;

    uint row_base = row * uint(T);
    device const bool* mask_b = key_mask + b * T;

    float local_max = -1e30f;
    float local_sum = 0.0f;
    for (int col = int(tid); col < T; col += 256) {
        float v = float(scores[row_base + uint(col)]) * scale;
        if (has_mask != 0 && mask_b[col]) v += -10000.0f;
        if (v > local_max) {
            local_sum = local_sum * metal::exp(local_max - v) + 1.0f;
            local_max = v;
        } else {
            local_sum += metal::exp(v - local_max);
        }
    }

    for (ushort offset = 16; offset > 0; offset >>= 1) {
        float om = simd_shuffle_down(local_max, offset);
        float os = simd_shuffle_down(local_sum, offset);
        if (om > local_max) {
            local_sum = local_sum * metal::exp(local_max - om) + os;
            local_max = om;
        } else {
            local_sum += os * metal::exp(om - local_max);
        }
    }

    threadgroup float sh_m[8];
    threadgroup float sh_s[8];
    if (lane == 0) {
        sh_m[sgid] = local_max;
        sh_s[sgid] = local_sum;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_lse;
    if (tid == 0) {
        float m = sh_m[0], s = sh_s[0];
        for (int i = 1; i < 8; ++i) {
            float om = sh_m[i], os = sh_s[i];
            if (om > m) { s = s * metal::exp(m - om) + os; m = om; }
            else { s += os * metal::exp(om - m); }
        }
        s_lse = m + metal::log(metal::max(s, 1e-30f));
        lse_out[row] = s_lse;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float lse = s_lse;
    for (int col = int(tid); col < T; col += 256) {
        uint idx = row_base + uint(col);
        float v = float(scores[idx]) * scale;
        if (has_mask != 0 && mask_b[col]) v += -10000.0f;
        float p = metal::exp(v - lse);
        float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
        probs_drop[idx] = bfloat(p * kp);
    }
}

kernel void attn_scale_mask_softmax_drop_bwd_bf16(
    device bfloat* scores_in_dscores_out [[buffer(0)]],     // [B*H, T, T] in-place
    device bfloat* grad_pdrop_in_pdrop_out [[buffer(1)]],   // [B*H, T, T] in-place
    device const bool* key_mask [[buffer(2)]],              // [B, T]
    device const float* lse_in [[buffer(3)]],               // [B*H, T]
    constant int& B [[buffer(4)]],
    constant int& H [[buffer(5)]],
    constant int& T [[buffer(6)]],
    constant int& has_mask [[buffer(7)]],
    constant float& scale [[buffer(8)]],
    constant float& drop_p [[buffer(9)]],
    constant float& inv_keep [[buffer(10)]],
    constant uint& seed_lo [[buffer(11)]],
    constant uint& seed_hi [[buffer(12)]],
    uint row [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    int total_rows = B * H * T;
    if (int(row) >= total_rows) return;
    int bh = int(row) / T;
    int b = bh / H;

    uint row_base = row * uint(T);
    device const bool* mask_b = key_mask + b * T;
    float lse = lse_in[row];

    if (T <= 1024) {
        float reg_p[4];
        float reg_dp[4];
        float reg_pdrop[4];
        float local_dot = 0.0f;

        for (int k = 0; k < 4; ++k) {
            int col = int(tid) + k * 256;
            if (col < T) {
                uint idx = row_base + uint(col);
                float v = float(scores_in_dscores_out[idx]) * scale;
                if (has_mask != 0 && mask_b[col]) v += -10000.0f;
                float p_raw = metal::exp(v - lse);
                float p = float(bfloat(p_raw));
                float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
                float gp = float(grad_pdrop_in_pdrop_out[idx]);
                float dp = gp * kp;
                reg_p[k] = p;
                reg_dp[k] = dp;
                reg_pdrop[k] = p_raw * kp;
                local_dot += p * dp;
            }
        }

        local_dot = simd_sum(local_dot);
        threadgroup float sh_dot[8];
        if (lane == 0) sh_dot[sgid] = local_dot;
        threadgroup_barrier(mem_flags::mem_threadgroup);

        threadgroup float s_dot;
        if (tid == 0) {
            float tot = 0.0f;
            for (int i = 0; i < 8; ++i) tot += sh_dot[i];
            s_dot = tot;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);

        float dot = s_dot;
        for (int k = 0; k < 4; ++k) {
            int col = int(tid) + k * 256;
            if (col < T) {
                uint idx = row_base + uint(col);
                scores_in_dscores_out[idx] = bfloat(scale * reg_p[k] * (reg_dp[k] - dot));
                grad_pdrop_in_pdrop_out[idx] = bfloat(reg_pdrop[k]);
            }
        }
    } else {
        float local_dot = 0.0f;
        for (int col = int(tid); col < T; col += 256) {
            uint idx = row_base + uint(col);
            float v = float(scores_in_dscores_out[idx]) * scale;
            if (has_mask != 0 && mask_b[col]) v += -10000.0f;
            float p = float(bfloat(metal::exp(v - lse)));
            float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
            local_dot += p * (float(grad_pdrop_in_pdrop_out[idx]) * kp);
        }
        local_dot = simd_sum(local_dot);
        threadgroup float sh_dot2[8];
        if (lane == 0) sh_dot2[sgid] = local_dot;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        threadgroup float s_dot2;
        if (tid == 0) {
            float tot = 0.0f;
            for (int i = 0; i < 8; ++i) tot += sh_dot2[i];
            s_dot2 = tot;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        float dot = s_dot2;
        for (int col = int(tid); col < T; col += 256) {
            uint idx = row_base + uint(col);
            float v = float(scores_in_dscores_out[idx]) * scale;
            if (has_mask != 0 && mask_b[col]) v += -10000.0f;
            float p_raw = metal::exp(v - lse);
            float p = float(bfloat(p_raw));
            float kp = philox_keep_scale(seed_lo, seed_hi, idx, drop_p, inv_keep);
            float dp = float(grad_pdrop_in_pdrop_out[idx]) * kp;
            scores_in_dscores_out[idx] = bfloat(scale * p * (dp - dot));
            grad_pdrop_in_pdrop_out[idx] = bfloat(p_raw * kp);
        }
    }
}

// ============================================================================
// 3. Fused Reader Tail: Residual Scale + Mask + L2 Normalize (D = 256)
// ============================================================================

kernel void fused_res_l2norm_fwd_bf16(
    device const bfloat* out_in [[buffer(0)]],
    device const bfloat* res_in [[buffer(1)]],
    device const float* res_scale [[buffer(2)]],
    device const bool* mask [[buffer(3)]],
    device bfloat* normed_out [[buffer(4)]],
    device float* inv_norm_out [[buffer(5)]],
    uint bt [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    if (mask[bt]) {
        normed_out[bt * 256 + tid] = bfloat(0.0f);
        if (tid == 0) inv_norm_out[bt] = 0.0f;
        return;
    }
    float rs = res_scale[0];
    uint idx = bt * 256 + tid;
    float c = rs * float(res_in[idx]) + float(out_in[idx]);
    float sq = simd_sum(c * c);

    threadgroup float sh_sq[8];
    if (lane == 0) sh_sq[sgid] = sq;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_inv_norm;
    if (tid == 0) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh_sq[i];
        float inv_n = 1.0f / max(metal::sqrt(tot), 1e-5f);
        s_inv_norm = inv_n;
        inv_norm_out[bt] = inv_n;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    normed_out[idx] = bfloat(c * s_inv_norm);
}

kernel void fused_res_l2norm_bwd_bf16(
    device const bfloat* grad_normed [[buffer(0)]],
    device const bfloat* normed [[buffer(1)]],
    device const bfloat* res_in [[buffer(2)]],
    device const float* inv_norm [[buffer(3)]],
    device bfloat* grad_out [[buffer(4)]],
    device atomic_float* grad_res_scale [[buffer(5)]],
    uint bt [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    float inv_n = inv_norm[bt];
    uint idx = bt * 256 + tid;
    if (inv_n == 0.0f) {
        grad_out[idx] = bfloat(0.0f);
        return;
    }
    float g = float(grad_normed[idx]);
    float y = float(normed[idx]);
    float dot = simd_sum(g * y);

    threadgroup float sh_dot[8];
    if (lane == 0) sh_dot[sgid] = dot;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float s_dot;
    if (tid == 0) {
        float tot = 0.0f;
        for (int i = 0; i < 8; ++i) tot += sh_dot[i];
        s_dot = tot;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float gc = inv_n * (g - y * s_dot);
    grad_out[idx] = bfloat(gc);

    float grs = simd_sum(gc * float(res_in[idx]));
    if (lane == 0) sh_dot[sgid] = grs;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        float tot_grs = 0.0f;
        for (int i = 0; i < 8; ++i) tot_grs += sh_dot[i];
        atomic_fetch_add_explicit(grad_res_scale, tot_grs, memory_order_relaxed);
    }
}

// ============================================================================
// 4. Fused CosineCTCHead + Custom Metal FP32 Log-CTC + Exact Scatter Softmax Bwd
// ============================================================================

kernel void fused_lse_gather_bf16(
    device const bfloat* logits [[buffer(0)]],
    device const int* active_ids [[buffer(1)]],
    device float* lse_out [[buffer(2)]],
    device float* lp_sub_out [[buffer(3)]],
    constant int& B [[buffer(4)]],
    constant int& T [[buffer(5)]],
    constant int& V [[buffer(6)]],
    constant int& U [[buffer(7)]],
    uint tgid [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    if (int(tgid) >= B * T) return;

    uint b = tgid / uint(T);
    uint t = tgid % uint(T);
    device const bfloat* row = logits + tgid * uint(V);

    float local_max = -1e30f;
    float local_sum = 0.0f;
    for (uint v = tid; v < uint(V); v += 256) {
        float val = float(row[v]);
        if (val > local_max) {
            local_sum = local_sum * metal::exp(local_max - val) + 1.0f;
            local_max = val;
        } else {
            local_sum += metal::exp(val - local_max);
        }
    }

    for (ushort offset = 16; offset > 0; offset >>= 1) {
        float other_max = simd_shuffle_down(local_max, offset);
        float other_sum = simd_shuffle_down(local_sum, offset);
        if (other_max > local_max) {
            local_sum = local_sum * metal::exp(local_max - other_max) + other_sum;
            local_max = other_max;
        } else {
            local_sum += other_sum * metal::exp(other_max - local_max);
        }
    }

    threadgroup float shared_max[8];
    threadgroup float shared_sum[8];
    if (lane == 0) {
        shared_max[sgid] = local_max;
        shared_sum[sgid] = local_sum;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float final_lse;
    if (tid == 0) {
        float m = shared_max[0];
        float s = shared_sum[0];
        for (uint i = 1; i < 8; ++i) {
            float om = shared_max[i];
            float os = shared_sum[i];
            if (om > m) {
                s = s * metal::exp(m - om) + os;
                m = om;
            } else {
                s += os * metal::exp(om - m);
            }
        }
        final_lse = m + metal::log(s);
        lse_out[tgid] = final_lse;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float row_lse = final_lse;
    uint out_base = (t * uint(B) + b) * uint(U);
    for (uint u = tid; u < uint(U); u += 256) {
        int col = active_ids[u];
        lp_sub_out[out_base + u] = float(row[col]) - row_lse;
    }
}

kernel void ctc_loss_fwd_bwd_fp32(
    device const float* lp_sub [[buffer(0)]],       // [T, B, U]
    device const int* targets [[buffer(1)]],        // [total_targets] (1..U-1)
    device const int* in_lens [[buffer(2)]],        // [B]
    device const int* tgt_lens [[buffer(3)]],       // [B]
    device const int* tgt_offsets [[buffer(4)]],    // [B]
    device float* alpha_ws [[buffer(5)]],           // [B, T, S_max]
    device atomic_float* g_sub_out [[buffer(6)]],   // [T, B, U] (pre-zeroed)
    device atomic_float* loss_accum [[buffer(7)]],  // [2]
    constant int& B [[buffer(8)]],
    constant int& T [[buffer(9)]],
    constant int& U [[buffer(10)]],
    constant int& S_max [[buffer(11)]],
    constant int& use_token_denom [[buffer(12)]],
    constant float& grad_norm_denom [[buffer(13)]],
    uint b [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]]
) {
    if (int(b) >= B) return;

    int T_b = min(in_lens[b], T);
    int L_b = tgt_lens[b];
    int t_off = tgt_offsets[b];
    int S = 2 * L_b + 1;

    threadgroup int sh_ext[1024];
    threadgroup float sh_prev[1024];
    threadgroup float sh_curr[1024];

    for (int s = int(tid); s < S; s += 256) {
        sh_ext[s] = ((s & 1) == 0) ? 0 : targets[t_off + (s >> 1)];
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (L_b <= 0) {
        for (int t = int(tid); t < T_b; t += 256) {
            uint base = uint(t * B + int(b)) * uint(U);
            atomic_fetch_add_explicit(&g_sub_out[base], -1.0f / grad_norm_denom, memory_order_relaxed);
        }
        return;
    }

    threadgroup int sh_valid_flag;
    if (tid == 0) {
        int repeats = 0;
        for (int i = 1; i < L_b; ++i) {
            if (targets[t_off + i] == targets[t_off + i - 1]) repeats += 1;
        }
        sh_valid_flag = (T_b >= L_b + repeats && S <= 1024 && U <= 1024) ? 1 : 0;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (sh_valid_flag == 0) {
        return;
    }

    device float* alpha_b = alpha_ws + uint(b) * uint(T) * uint(S_max);

    for (int s = int(tid); s < S; s += 256) {
        float val = -INFINITY;
        uint lp0 = uint(b) * uint(U);
        if (s == 0) val = lp_sub[lp0 + 0];
        else if (s == 1) val = lp_sub[lp0 + uint(sh_ext[1])];
        sh_prev[s] = val;
        alpha_b[s] = val;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (int t = 1; t < T_b; ++t) {
        uint lp_base = uint(t * B + int(b)) * uint(U);
        int s_min = max(0, S - 2 * (T_b - t));
        int s_max_t = min(S - 1, 2 * t + 1);
        for (int s = int(tid); s < S; s += 256) {
            float val = -INFINITY;
            if (s >= s_min && s <= s_max_t) {
                float a0 = sh_prev[s];
                float a1 = (s >= 1) ? sh_prev[s - 1] : -INFINITY;
                bool skip_ok = (s >= 2) && ((s & 1) == 1) && (sh_ext[s] != sh_ext[s - 2]);
                float a2 = skip_ok ? sh_prev[s - 2] : -INFINITY;
                float m3 = log_add3(a0, a1, a2);
                if (m3 > -INFINITY) val = m3 + lp_sub[lp_base + uint(sh_ext[s])];
            }
            sh_curr[s] = val;
            alpha_b[uint(t) * uint(S_max) + uint(s)] = val;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int s = int(tid); s < S; s += 256) sh_prev[s] = sh_curr[s];
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }

    threadgroup float s_ll;
    if (tid == 0) {
        s_ll = log_add(sh_prev[S - 1], sh_prev[S - 2]);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float ll = s_ll;
    if (!(ll > -INFINITY && ll < INFINITY)) {
        return;
    }

    if (tid == 0) {
        if (use_token_denom != 0) {
            atomic_fetch_add_explicit(&loss_accum[0], -ll, memory_order_relaxed);
            atomic_fetch_add_explicit(&loss_accum[1], float(L_b), memory_order_relaxed);
        } else {
            atomic_fetch_add_explicit(&loss_accum[0], (-ll) / float(L_b), memory_order_relaxed);
            atomic_fetch_add_explicit(&loss_accum[1], 1.0f, memory_order_relaxed);
        }
    }

    float g_scale = (use_token_denom != 0)
        ? (1.0f / grad_norm_denom)
        : (1.0f / (float(L_b) * grad_norm_denom));

    {
        int t = T_b - 1;
        uint lp_base = uint(t * B + int(b)) * uint(U);
        device const float* a_row = alpha_b + uint(t) * uint(S_max);
        for (int s = int(tid); s < S; s += 256) {
            float beta_val = (s >= S - 2) ? 0.0f : -INFINITY;
            float a_val = a_row[s];
            if (a_val > -INFINITY && beta_val > -INFINITY) {
                float post = -g_scale * metal::exp(metal::min(0.0f, a_val + beta_val - ll));
                atomic_fetch_add_explicit(&g_sub_out[lp_base + uint(sh_ext[s])], post, memory_order_relaxed);
            }
            sh_prev[s] = (beta_val > -INFINITY) ? (beta_val + lp_sub[lp_base + uint(sh_ext[s])]) : -INFINITY;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }

    for (int t = T_b - 2; t >= 0; --t) {
        uint lp_base = uint(t * B + int(b)) * uint(U);
        device const float* a_row = alpha_b + uint(t) * uint(S_max);
        int s_min = max(0, S - 2 * (T_b - t));
        int s_max_t = min(S - 1, 2 * t + 1);

        for (int s = int(tid); s < S; s += 256) {
            float beta_val = -INFINITY;
            if (s >= s_min && s <= s_max_t) {
                float b0 = sh_prev[s];
                float b1 = (s + 1 < S) ? sh_prev[s + 1] : -INFINITY;
                bool skip_ok = (s + 2 < S) && ((s & 1) == 1) && (sh_ext[s + 2] != sh_ext[s]);
                float b2 = skip_ok ? sh_prev[s + 2] : -INFINITY;
                beta_val = log_add3(b0, b1, b2);
            }
            float a_val = a_row[s];
            if (a_val > -INFINITY && beta_val > -INFINITY) {
                float post = -g_scale * metal::exp(metal::min(0.0f, a_val + beta_val - ll));
                atomic_fetch_add_explicit(&g_sub_out[lp_base + uint(sh_ext[s])], post, memory_order_relaxed);
            }
            sh_curr[s] = (beta_val > -INFINITY) ? (beta_val + lp_sub[lp_base + uint(sh_ext[s])]) : -INFINITY;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);

        for (int s = int(tid); s < S; s += 256) {
            sh_prev[s] = sh_curr[s];
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
}

kernel void fused_softmax_scatter_bwd_bf16(
    device bfloat* logits_in_dZ_out [[buffer(0)]],
    device const float* lse [[buffer(1)]],
    device const float* g_sub [[buffer(2)]],
    device const int* active_ids [[buffer(3)]],
    constant int& B [[buffer(4)]],
    constant int& T [[buffer(5)]],
    constant int& V [[buffer(6)]],
    constant int& U [[buffer(7)]],
    uint tgid [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]]
) {
    if (int(tgid) >= B * T) return;

    uint b = tgid / uint(T);
    uint t = tgid % uint(T);
    device bfloat* row = logits_in_dZ_out + tgid * uint(V);
    device const float* g_row = g_sub + (t * uint(B) + b) * uint(U);

    float saved_logits[4];
    int saved_cols[4];
    float saved_g[4];
    float local_g_sum = 0.0f;
    for (uint k = 0; k < 4; ++k) {
        uint u = tid + k * 256;
        if (int(u) < U) {
            int col = active_ids[u];
            float gv = g_row[u];
            saved_cols[k] = col;
            saved_logits[k] = float(row[col]);
            saved_g[k] = gv;
            local_g_sum += gv;
        }
    }
    local_g_sum = simd_sum(local_g_sum);

    threadgroup float shared_g_sum[8];
    if (lane == 0) {
        shared_g_sum[sgid] = local_g_sum;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    threadgroup float row_g_sum;
    if (tid == 0) {
        float s = 0.0f;
        for (uint i = 0; i < 8; ++i) s += shared_g_sum[i];
        row_g_sum = s;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float gsum = row_g_sum;
    float row_lse = lse[tgid];
    float neg_gsum = -gsum;

    if (gsum == 0.0f) {
        for (uint v = tid; v < uint(V); v += 256) {
            row[v] = bfloat(0.0f);
        }
    } else {
        for (uint v = tid; v < uint(V); v += 256) {
            float p = metal::exp(float(row[v]) - row_lse);
            row[v] = bfloat(p * neg_gsum);
        }
    }
    threadgroup_barrier(mem_flags::mem_device);

    for (uint k = 0; k < 4; ++k) {
        uint u = tid + k * 256;
        if (int(u) < U) {
            float p = (gsum == 0.0f) ? 0.0f : metal::exp(saved_logits[k] - row_lse);
            row[saved_cols[k]] = bfloat(p * neg_gsum + saved_g[k]);
        }
    }
}

// ============================================================================
// 5. Zero-Sync Flat-Buffer Metal GradNorm + In-Kernel Clipped AdamW
// ============================================================================

kernel void grad_norm_sq_bf16(
    device const bfloat* grad [[buffer(0)]],
    device atomic_float* total_sq [[buffer(1)]],
    constant int& numel [[buffer(2)]],
    uint tgid [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]],
    uint num_tgs [[threadgroups_per_grid]]
) {
    float acc = 0.0f;
    uint stride = num_tgs * 256u;
    for (uint i = tgid * 256u + tid; i < uint(numel); i += stride) {
        float g = float(grad[i]);
        acc += g * g;
    }
    acc = simd_sum(acc);
    threadgroup float sh[8];
    if (lane == 0) sh[sgid] = acc;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        float s = 0.0f;
        for (uint i = 0; i < 8; ++i) s += sh[i];
        atomic_fetch_add_explicit(total_sq, s, memory_order_relaxed);
    }
}

kernel void grad_norm_sq_fp32(
    device const float* grad [[buffer(0)]],
    device atomic_float* total_sq [[buffer(1)]],
    constant int& numel [[buffer(2)]],
    uint tgid [[threadgroup_position_in_grid]],
    uint tid [[thread_index_in_threadgroup]],
    uint sgid [[simdgroup_index_in_threadgroup]],
    uint lane [[thread_index_in_simdgroup]],
    uint num_tgs [[threadgroups_per_grid]]
) {
    float acc = 0.0f;
    uint stride = num_tgs * 256u;
    for (uint i = tgid * 256u + tid; i < uint(numel); i += stride) {
        float g = grad[i];
        acc += g * g;
    }
    acc = simd_sum(acc);
    threadgroup float sh[8];
    if (lane == 0) sh[sgid] = acc;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        float s = 0.0f;
        for (int i = 0; i < 8; ++i) s += sh[i];
        atomic_fetch_add_explicit(total_sq, s, memory_order_relaxed);
    }
}

kernel void fused_adamw_master_bf16(
    device bfloat* param_bf16 [[buffer(0)]],
    device float* master_fp32 [[buffer(1)]],
    device bfloat* grad_bf16 [[buffer(2)]],
    device float* exp_avg [[buffer(3)]],
    device float* exp_avg_sq [[buffer(4)]],
    device const float* total_sq_buf [[buffer(5)]],
    constant int& numel [[buffer(6)]],
    constant float& lr [[buffer(7)]],
    constant float& beta1 [[buffer(8)]],
    constant float& beta2 [[buffer(9)]],
    constant float& eps [[buffer(10)]],
    constant float& wd [[buffer(11)]],
    constant float& bc1 [[buffer(12)]],
    constant float& bc2_sqrt [[buffer(13)]],
    constant float& max_norm [[buffer(14)]],
    uint gid [[thread_position_in_grid]]
) {
    if (int(gid) >= numel) return;

    float tot_sq = total_sq_buf[0];
    if (!(tot_sq >= 0.0f && tot_sq < INFINITY)) {
        grad_bf16[gid] = bfloat(0.0f);
        return;
    }
    float norm_val = metal::sqrt(tot_sq);
    float clip_coef = metal::min(1.0f, max_norm / (norm_val + 1e-6f));

    float g = float(grad_bf16[gid]) * clip_coef;
    grad_bf16[gid] = bfloat(0.0f);

    float p = master_fp32[gid];
    if (wd != 0.0f) {
        p -= lr * wd * p;
    }
    float m = beta1 * exp_avg[gid] + (1.0f - beta1) * g;
    float v = beta2 * exp_avg_sq[gid] + (1.0f - beta2) * g * g;
    exp_avg[gid] = m;
    exp_avg_sq[gid] = v;

    float denom = (metal::sqrt(v) / bc2_sqrt) + eps;
    p -= (lr / bc1) * (m / denom);

    master_fp32[gid] = p;
    param_bf16[gid] = bfloat(p);
}

kernel void fused_adamw_fp32(
    device float* param_fp32 [[buffer(0)]],
    device float* grad_fp32 [[buffer(1)]],
    device float* exp_avg [[buffer(2)]],
    device float* exp_avg_sq [[buffer(3)]],
    device const float* total_sq_buf [[buffer(4)]],
    constant int& numel [[buffer(5)]],
    constant float& lr [[buffer(6)]],
    constant float& beta1 [[buffer(7)]],
    constant float& beta2 [[buffer(8)]],
    constant float& eps [[buffer(9)]],
    constant float& wd [[buffer(10)]],
    constant float& bc1 [[buffer(11)]],
    constant float& bc2_sqrt [[buffer(12)]],
    constant float& max_norm [[buffer(13)]],
    uint gid [[thread_position_in_grid]]
) {
    if (int(gid) >= numel) return;

    float tot_sq = total_sq_buf[0];
    if (!(tot_sq >= 0.0f && tot_sq < INFINITY)) {
        grad_fp32[gid] = 0.0f;
        return;
    }
    float norm_val = metal::sqrt(tot_sq);
    float clip_coef = metal::min(1.0f, max_norm / (norm_val + 1e-6f));

    float g = grad_fp32[gid] * clip_coef;
    grad_fp32[gid] = 0.0f;

    float p = param_fp32[gid];
    if (wd != 0.0f) {
        p -= lr * wd * p;
    }
    float m = beta1 * exp_avg[gid] + (1.0f - beta1) * g;
    float v = beta2 * exp_avg_sq[gid] + (1.0f - beta2) * g * g;
    exp_avg[gid] = m;
    exp_avg_sq[gid] = v;

    float denom = (metal::sqrt(v) / bc2_sqrt) + eps;
    p -= (lr / bc1) * (m / denom);

    param_fp32[gid] = p;
}
"""

_SHADER_LIB = None
_DIMS_CACHE: "OrderedDict[Tuple[int, ...], torch.Tensor]" = OrderedDict()
_DIMS_CACHE_MAX = 256
_SCRATCH_CACHE: Dict[Tuple[str, int, str], torch.Tensor] = {}
_BOOL_DUMMY_CACHE: Dict[str, torch.Tensor] = {}


def get_metal_lib():
    global _SHADER_LIB
    if _SHADER_LIB is None:
        if hasattr(torch.mps, "compile_shader") and torch.backends.mps.is_available():
            _SHADER_LIB = torch.mps.compile_shader(_METAL_SHADER_SOURCE)
    return _SHADER_LIB


def get_dims_tensor(shape_tuple: Tuple[int, ...], device: torch.device) -> torch.Tensor:
    """Bounded LRU helper preserved for backward compatibility."""
    t = _DIMS_CACHE.get(shape_tuple)
    if t is not None and t.device == device:
        _DIMS_CACHE.move_to_end(shape_tuple)
        return t
    t = torch.tensor(list(shape_tuple), device=device, dtype=torch.int32)
    _DIMS_CACHE[shape_tuple] = t
    if len(_DIMS_CACHE) > _DIMS_CACHE_MAX:
        _DIMS_CACHE.popitem(last=False)
    return t


def get_zeroed_scratch(name: str, numel: int, device: torch.device) -> torch.Tensor:
    """Returns a persistent pre-zeroed FP32 scratch buffer (reset inside each epilogue kernel)."""
    key = (name, numel, str(device))
    buf = _SCRATCH_CACHE.get(key)
    if buf is None or buf.device != device or buf.numel() < numel:
        buf = torch.zeros((numel,), device=device, dtype=torch.float32)
        _SCRATCH_CACHE[key] = buf
    return buf[:numel]


def _get_dummy_bool(device: torch.device) -> torch.Tensor:
    key = str(device)
    buf = _BOOL_DUMMY_CACHE.get(key)
    if buf is None or buf.device != device:
        buf = torch.zeros((1,), device=device, dtype=torch.bool)
        _BOOL_DUMMY_CACHE[key] = buf
    return buf


def _next_philox_seeds(active: bool) -> Tuple[int, int]:
    if not active:
        return 0, 0
    s64 = random.getrandbits(64)
    return int(s64 & 0xFFFFFFFF), int((s64 >> 32) & 0xFFFFFFFF)


# ==============================================================================
# 1. Autograd Functions for Fused Conformer Building Blocks & Reader Tail
# ==============================================================================

class MetalFlatLinearFunction(torch.autograd.Function):
    """
    Zero-allocation Linear projection for BF16 parameters packed in FlatBufferMetalAdamW.
    Accumulates weight gradients directly into `w_grad_buf` via in-place `addmm_` and
    optional bias gradients into `b_grad_buf`, avoiding temporary grad tensor allocations
    and AccumulateGrad copies across all 62 Linear / Pointwise layers.
    """
    @staticmethod
    def forward(
        ctx,
        x: torch.Tensor,
        w: torch.Tensor,
        b: Optional[torch.Tensor] = None,
        w_grad_buf: Optional[torch.Tensor] = None,
        b_grad_buf: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if any(ctx.needs_input_grad):
            ctx.save_for_backward(x, w)
            ctx.has_bias = b is not None
            ctx.w_grad_buf = w_grad_buf
            ctx.b_grad_buf = b_grad_buf
        return F.linear(x, w, b)

    @staticmethod
    def backward(ctx, grad_out: torch.Tensor):
        x, w = ctx.saved_tensors
        go_2d = grad_out.reshape(-1, grad_out.size(-1))
        x_2d = x.reshape(-1, x.size(-1))
        grad_x = torch.matmul(go_2d, w).view_as(x) if ctx.needs_input_grad[0] else None

        if ctx.w_grad_buf is not None:
            ctx.w_grad_buf.addmm_(go_2d.t(), x_2d)
            grad_w = None
        else:
            grad_w = torch.matmul(go_2d.t(), x_2d)

        grad_b = None
        if ctx.has_bias:
            gb = go_2d.sum(dim=0)
            if ctx.b_grad_buf is not None:
                ctx.b_grad_buf.add_(gb)
            else:
                grad_b = gb

        return grad_x, grad_w, grad_b, None, None


# Backward-compatible alias for QKV fused linear
MetalFusedQKVLinearFunction = MetalFlatLinearFunction


class MetalLayerNormFunction(torch.autograd.Function):
    """Single-kernel FP32-accumulated BF16 LayerNorm (D <= 512) with direct flat-grad writeback."""
    @staticmethod
    def forward(
        ctx,
        x: torch.Tensor,
        gamma: torch.Tensor,
        beta: torch.Tensor,
        wb_grad_buf: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        D = x.size(-1)
        x_c = x.contiguous()
        BT = x_c.numel() // D
        lib = get_metal_lib()
        y = torch.empty_like(x_c)
        mean = torch.empty((BT,), device=x.device, dtype=torch.float32)
        rstd = torch.empty((BT,), device=x.device, dtype=torch.float32)
        lib.layernorm_fwd_bf16(
            x_c, gamma, beta, y, mean, rstd, D,
            threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
        )
        if any(ctx.needs_input_grad):
            ctx.save_for_backward(x_c, gamma, mean, rstd)
            ctx.wb_grad_buf = wb_grad_buf
        return y

    @staticmethod
    def backward(ctx, grad_y: torch.Tensor):
        x_c, gamma, mean, rstd = ctx.saved_tensors
        D = x_c.size(-1)
        BT = x_c.numel() // D
        lib = get_metal_lib()
        gy_c = grad_y.contiguous()
        grad_x = torch.empty_like(x_c)
        scratch = get_zeroed_scratch("ln_bwd", 2 * D, x_c.device)

        lib.layernorm_bwd_bf16(
            gy_c, x_c, gamma, mean, rstd, grad_x, scratch, D,
            threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
        )
        if ctx.wb_grad_buf is not None:
            lib.accum_reset_fp32_to_bf16(
                scratch, ctx.wb_grad_buf, 2 * D,
                threads=(2 * D, 1, 1), group_size=(256, 1, 1)
            )
            return grad_x, None, None, None

        grad_wb = torch.empty((2 * D,), device=x_c.device, dtype=torch.bfloat16)
        lib.copy_reset_fp32_to_bf16(
            scratch, grad_wb, 2 * D,
            threads=(2 * D, 1, 1), group_size=(256, 1, 1)
        )
        return grad_x, grad_wb[:D], grad_wb[D:], None


class MetalFusedBiasDropResLayerNormFunction(torch.autograd.Function):
    """
    Fuses 5 Conformer sublayer boundary operations into 1 Metal kernel:
      x_out = x_res + res_scale * PhiloxDropout(sub_nobias + sub_bias, p=drop_p)
      normed_out = LayerNorm_FP32(x_out, ln_gamma, ln_beta)
    Returns (x_out, normed_out). Uses set_materialize_grads(False) so unused x_out
    at the end of ConformerBlock incurs zero zero-tensor allocation in backward.
    """
    @staticmethod
    def forward(
        ctx,
        x_res: torch.Tensor,
        sub_nobias: torch.Tensor,
        sub_bias: torch.Tensor,
        ln_gamma: torch.Tensor,
        ln_beta: torch.Tensor,
        res_scale: float,
        drop_p: float,
        training: bool,
        sub_b_grad_buf: Optional[torch.Tensor] = None,
        ln_wb_grad_buf: Optional[torch.Tensor] = None,
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        ctx.set_materialize_grads(False)
        D = x_res.size(-1)
        xr_c = x_res.contiguous()
        sub_c = sub_nobias.contiguous()
        BT = xr_c.numel() // D
        eff_p = float(drop_p) if (training and drop_p > 0.0) else 0.0
        inv_keep = 1.0 / (1.0 - eff_p) if eff_p > 0.0 else 1.0
        seed_lo, seed_hi = _next_philox_seeds(eff_p > 0.0)

        lib = get_metal_lib()
        x_out = torch.empty_like(xr_c)
        normed_out = torch.empty_like(xr_c)
        mean = torch.empty((BT,), device=xr_c.device, dtype=torch.float32)
        rstd = torch.empty((BT,), device=xr_c.device, dtype=torch.float32)

        lib.fused_bias_drop_res_ln_fwd_bf16(
            xr_c, sub_c, sub_bias, ln_gamma, ln_beta,
            x_out, normed_out, mean, rstd,
            D, float(res_scale), eff_p, inv_keep, seed_lo, seed_hi,
            threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
        )
        if any(ctx.needs_input_grad):
            ctx.save_for_backward(x_out, ln_gamma, mean, rstd)
            ctx.res_scale = float(res_scale)
            ctx.eff_p = eff_p
            ctx.inv_keep = inv_keep
            ctx.seed_lo = seed_lo
            ctx.seed_hi = seed_hi
            ctx.sub_b_grad_buf = sub_b_grad_buf
            ctx.ln_wb_grad_buf = ln_wb_grad_buf
        return x_out, normed_out

    @staticmethod
    def backward(ctx, grad_x_out: Optional[torch.Tensor], grad_normed: Optional[torch.Tensor]):
        x_out, ln_gamma, mean, rstd = ctx.saved_tensors
        if grad_x_out is None and grad_normed is None:
            return (None,) * 10

        D = x_out.size(-1)
        BT = x_out.numel() // D
        lib = get_metal_lib()

        has_gn = 1 if grad_normed is not None else 0
        has_gx = 1 if grad_x_out is not None else 0
        gn_c = grad_normed.contiguous() if has_gn else x_out
        gx_c = grad_x_out.contiguous() if has_gx else x_out

        grad_xr = torch.empty_like(x_out)
        grad_sub = torch.empty_like(x_out)
        scratch = get_zeroed_scratch("res_ln_bwd", 3 * D, x_out.device)

        lib.fused_bias_drop_res_ln_bwd_bf16(
            gn_c, gx_c, x_out, ln_gamma, mean, rstd,
            grad_xr, grad_sub, scratch,
            D, has_gn, has_gx, ctx.res_scale, ctx.eff_p, ctx.inv_keep, ctx.seed_lo, ctx.seed_hi,
            threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
        )

        if ctx.ln_wb_grad_buf is not None and ctx.sub_b_grad_buf is not None:
            lib.accum_reset_two_bf16(
                scratch, ctx.ln_wb_grad_buf, ctx.sub_b_grad_buf, 2 * D, D,
                threads=(3 * D, 1, 1), group_size=(256, 1, 1)
            )
            return grad_xr, grad_sub, None, None, None, None, None, None, None, None

        grad_all = torch.empty((3 * D,), device=x_out.device, dtype=torch.bfloat16)
        lib.copy_reset_fp32_to_bf16(
            scratch, grad_all, 3 * D,
            threads=(3 * D, 1, 1), group_size=(256, 1, 1)
        )
        g_gamma = grad_all[:D] if has_gn else None
        g_beta = grad_all[D : 2 * D] if has_gn else None
        g_sub_b = grad_all[2 * D :]
        return grad_xr, grad_sub, g_sub_b, g_gamma, g_beta, None, None, None, None, None


class MetalFusedBiasGELUDropFunction(torch.autograd.Function):
    """Fuses Linear bias + exact erf-poly GELU + stateless Philox dropout in 1 coalesced 2D kernel."""
    @staticmethod
    def forward(
        ctx,
        z_nobias: torch.Tensor,
        bias: torch.Tensor,
        drop_p: float,
        training: bool,
        bias_grad_buf: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        z_c = z_nobias.contiguous()
        D = z_c.size(-1)
        BT = z_c.numel() // D
        eff_p = float(drop_p) if (training and drop_p > 0.0) else 0.0
        inv_keep = 1.0 / (1.0 - eff_p) if eff_p > 0.0 else 1.0
        seed_lo, seed_hi = _next_philox_seeds(eff_p > 0.0)

        lib = get_metal_lib()
        out = torch.empty_like(z_c)
        lib.fused_bias_gelu_drop_fwd_bf16(
            z_c, bias, out, BT, D, eff_p, inv_keep, seed_lo, seed_hi,
            threads=(D, BT, 1), group_size=(64, 4, 1)
        )
        if any(ctx.needs_input_grad):
            ctx.save_for_backward(z_c, bias)
            ctx.eff_p = eff_p
            ctx.inv_keep = inv_keep
            ctx.seed_lo = seed_lo
            ctx.seed_hi = seed_hi
            ctx.bias_grad_buf = bias_grad_buf
        return out

    @staticmethod
    def backward(ctx, grad_out: torch.Tensor):
        z_c, bias = ctx.saved_tensors
        D = z_c.size(-1)
        BT = z_c.numel() // D
        go_c = grad_out.contiguous()
        lib = get_metal_lib()

        grad_z = torch.empty_like(z_c)
        scratch = get_zeroed_scratch("gelu_bwd", D, z_c.device)
        gx_32 = ((D + 31) // 32) * 32
        gy_8 = ((BT + 7) // 8) * 8

        lib.fused_bias_gelu_drop_bwd_bf16(
            go_c, z_c, bias, grad_z, scratch,
            BT, D, ctx.eff_p, ctx.inv_keep, ctx.seed_lo, ctx.seed_hi,
            threads=(gx_32, gy_8, 1), group_size=(32, 8, 1)
        )
        if ctx.bias_grad_buf is not None:
            lib.accum_reset_fp32_to_bf16(
                scratch, ctx.bias_grad_buf, D,
                threads=(D, 1, 1), group_size=(256, 1, 1)
            )
            return grad_z, None, None, None, None

        grad_b = torch.empty_like(bias)
        lib.copy_reset_fp32_to_bf16(
            scratch, grad_b, D,
            threads=(D, 1, 1), group_size=(256, 1, 1)
        )
        return grad_z, grad_b, None, None, None


class MetalFusedSelfAttentionFunction(torch.autograd.Function):
    """
    Fused Multi-Head Self-Attention core on MPS BF16:
    - Coalesced QKV split -> hardware torch.bmm -> fused Scale + Mask + Online FP32 Softmax + Philox Dropout
      -> hardware torch.bmm -> coalesced head merge.
    - Eliminates FP32 (B, H, T, T) softmax casts and cuts saved attention matrix memory by 50%
      via in-place backward softmax/dropout regeneration.
    """
    @staticmethod
    def forward(
        ctx,
        qkv: torch.Tensor,
        key_padding_mask: Optional[torch.Tensor],
         num_heads: int,
        scale: float,
        drop_p: float,
        training: bool,
    ) -> torch.Tensor:
        B, T, threeD = qkv.shape
        H = int(num_heads)
        Dh = (threeD // 3) // H
        BT = B * T
        HD = H * Dh
        qkv_c = qkv.contiguous()

        eff_p = float(drop_p) if (training and drop_p > 0.0) else 0.0
        inv_keep = 1.0 / (1.0 - eff_p) if eff_p > 0.0 else 1.0
        seed_lo, seed_hi = _next_philox_seeds(eff_p > 0.0)

        has_mask = 1 if key_padding_mask is not None else 0
        mask_c = key_padding_mask.contiguous() if has_mask else _get_dummy_bool(qkv.device)

        lib = get_metal_lib()
        q_m = torch.empty((B * H, T, Dh), device=qkv.device, dtype=torch.bfloat16)
        k_m = torch.empty((B * H, T, Dh), device=qkv.device, dtype=torch.bfloat16)
        v_m = torch.empty((B * H, T, Dh), device=qkv.device, dtype=torch.bfloat16)
        lib.qkv_split_heads_bf16(
            qkv_c, q_m, k_m, v_m, B, T, H, Dh,
            threads=(HD, BT, 1), group_size=(64, 4, 1)
        )

        scores = torch.bmm(q_m, k_m.transpose(1, 2))
        probs_drop = torch.empty_like(scores)
        lse = torch.empty((B * H, T), device=qkv.device, dtype=torch.float32)
        lib.attn_scale_mask_softmax_drop_fwd_bf16(
            scores, mask_c, probs_drop, lse,
            B, H, T, has_mask, float(scale), eff_p, inv_keep, seed_lo, seed_hi,
            threads=(B * H * T * 256, 1, 1), group_size=(256, 1, 1)
        )

        ctx_bh = torch.bmm(probs_drop, v_m)
        ctx_out = torch.empty((B, T, HD), device=qkv.device, dtype=torch.bfloat16)
        lib.attn_merge_ctx_bf16(
            ctx_bh, ctx_out, B, T, H, Dh,
            threads=(HD, BT, 1), group_size=(64, 4, 1)
        )

        if any(ctx.needs_input_grad):
            ctx.save_for_backward(q_m, k_m, v_m, scores, lse, mask_c)
            ctx.B = B
            ctx.T = T
            ctx.H = H
            ctx.Dh = Dh
            ctx.has_mask = has_mask
            ctx.scale = float(scale)
            ctx.eff_p = eff_p
            ctx.inv_keep = inv_keep
            ctx.seed_lo = seed_lo
            ctx.seed_hi = seed_hi

        return ctx_out

    @staticmethod
    def backward(ctx, grad_ctx: torch.Tensor):
        q_m, k_m, v_m, scores, lse, mask_c = ctx.saved_tensors
        B, T, H, Dh = ctx.B, ctx.T, ctx.H, ctx.Dh
        BT = B * T
        HD = H * Dh
        lib = get_metal_lib()

        gctx_bh = torch.empty((B * H, T, Dh), device=grad_ctx.device, dtype=torch.bfloat16)
        lib.attn_split_ctx_bf16(
            grad_ctx.contiguous(), gctx_bh, B, T, H, Dh,
            threads=(HD, BT, 1), group_size=(64, 4, 1)
        )

        gpdrop = torch.bmm(gctx_bh, v_m.transpose(1, 2))
        # In-place regeneration: overwrites `scores` with d_scores and `gpdrop` with probs_drop
        lib.attn_scale_mask_softmax_drop_bwd_bf16(
            scores, gpdrop, mask_c, lse,
            B, H, T, ctx.has_mask, ctx.scale, ctx.eff_p, ctx.inv_keep, ctx.seed_lo, ctx.seed_hi,
            threads=(B * H * T * 256, 1, 1), group_size=(256, 1, 1)
        )

        gv = torch.bmm(gpdrop.transpose(1, 2), gctx_bh)
        gq = torch.bmm(scores, k_m)
        gk = torch.bmm(scores.transpose(1, 2), q_m)

        gqkv = torch.empty((B, T, 3 * HD), device=grad_ctx.device, dtype=torch.bfloat16)
        lib.qkv_merge_heads_bf16(
            gq, gk, gv, gqkv, B, T, H, Dh,
            threads=(HD, BT, 1), group_size=(64, 4, 1)
        )
        return gqkv, None, None, None, None, None


class MetalFusedConvMidFunction(torch.autograd.Function):
    """
    2D-Coalesced Fused Conformer Convolution Mid-Block:
      u (B, T, 2D) -> GLU -> DepthwiseConv1d(k=15, pad=7) -> Shifted-Mean FP32 BatchNorm1d -> SiLU -> (B, T, D)
    Achieves 100% SIMD-coalesced memory reads/writes across channels D and writes parameter
    gradients directly into flat gradient buffers when provided.
    """
    @staticmethod
    def forward(
        ctx,
        u: torch.Tensor,
        conv_w: torch.Tensor,
        bn_w: torch.Tensor,
        bn_b: torch.Tensor,
        running_mean: torch.Tensor,
        running_var: torch.Tensor,
        training: bool,
        conv_w_grad_buf: Optional[torch.Tensor] = None,
        bn_w_grad_buf: Optional[torch.Tensor] = None,
        bn_b_grad_buf: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        B, T, twoD = u.shape
        D = twoD // 2
        BT = B * T
        lib = get_metal_lib()
        u_c = u.contiguous()
        glu_out = torch.empty((B, T, D), device=u.device, dtype=torch.bfloat16)
        out = torch.empty((B, T, D), device=u.device, dtype=torch.bfloat16)

        lib.glu_fwd_bf16(u_c, glu_out, BT, D, threads=(D, BT, 1), group_size=(64, 4, 1))

        if training:
            dw_out = torch.empty((B, T, D), device=u.device, dtype=torch.bfloat16)
            saved_mean = torch.empty((D,), device=u.device, dtype=torch.float32)
            saved_rstd = torch.empty((D,), device=u.device, dtype=torch.float32)
            stats_buf = get_zeroed_scratch("bn_fwd_stats", 2 * D, u.device)
            gx_32 = ((D + 31) // 32) * 32
            gy_8 = ((BT + 7) // 8) * 8

            lib.dwconv15_stats_coalesced_fwd_bf16(
                glu_out, conv_w, running_mean, dw_out, stats_buf,
                B, T, D, threads=(gx_32, gy_8, 1), group_size=(32, 8, 1)
            )
            lib.bn_finalize_stats_fp32(
                stats_buf, running_mean, running_var, saved_mean, saved_rstd,
                BT, D, threads=(D, 1, 1), group_size=(128, 1, 1)
            )
            lib.bn_silu_coalesced_fwd_bf16(
                dw_out, bn_w, bn_b, saved_mean, saved_rstd, out,
                BT, D, threads=(D, BT, 1), group_size=(64, 4, 1)
            )
            if any(ctx.needs_input_grad):
                ctx.save_for_backward(u_c, glu_out, dw_out, conv_w, bn_w, bn_b, saved_mean, saved_rstd)
                ctx.conv_w_grad_buf = conv_w_grad_buf
                ctx.bn_w_grad_buf = bn_w_grad_buf
                ctx.bn_b_grad_buf = bn_b_grad_buf
        else:
            lib.dwconv15_bn_silu_eval_coalesced_fwd_bf16(
                glu_out, conv_w, bn_w, bn_b, running_mean, running_var, out,
                B, T, D, threads=(D, BT, 1), group_size=(64, 4, 1)
            )
        return out

    @staticmethod
    def backward(ctx, grad_out: torch.Tensor):
        u_c, glu_out, dw_out, conv_w, bn_w, bn_b, saved_mean, saved_rstd = ctx.saved_tensors
        B, T, D = dw_out.shape
        BT = B * T
        lib = get_metal_lib()
        go_c = grad_out.contiguous()

        bwd_stats = get_zeroed_scratch("bn_bwd_stats", 2 * D, u_c.device)
        grad_dw = torch.empty_like(dw_out)
        grad_u = torch.empty_like(u_c)

        gx_32 = ((D + 31) // 32) * 32
        gy_8 = ((BT + 7) // 8) * 8

        lib.bn_silu_bwd_stats_coalesced_bf16(
            go_c, dw_out, bn_w, bn_b, saved_mean, saved_rstd, bwd_stats,
            BT, D, threads=(gx_32, gy_8, 1), group_size=(32, 8, 1)
        )
        lib.bn_bwd_dx_coalesced_bf16(
            go_c, dw_out, bn_w, bn_b, saved_mean, saved_rstd, bwd_stats,
            grad_dw, BT, D, threads=(D, BT, 1), group_size=(64, 4, 1)
        )
        lib.dwconv15_glu_bwd_x_bf16(
            grad_dw, conv_w, u_c, grad_u,
            B, T, D, threads=(D, BT, 1), group_size=(64, 4, 1)
        )

        if ctx.conv_w_grad_buf is not None:
            lib.dwconv15_bwd_w_simd_bf16(
                grad_dw, glu_out, ctx.conv_w_grad_buf,
                B, T, D, 1, threads=(D * 256, 1, 1), group_size=(256, 1, 1)
            )
            grad_conv_w = None
        else:
            grad_conv_w = torch.empty_like(conv_w)
            lib.dwconv15_bwd_w_simd_bf16(
                grad_dw, glu_out, grad_conv_w,
                B, T, D, 0, threads=(D * 256, 1, 1), group_size=(256, 1, 1)
            )

        if ctx.bn_w_grad_buf is not None and ctx.bn_b_grad_buf is not None:
            lib.accum_reset_two_fp32(
                bwd_stats, ctx.bn_w_grad_buf, ctx.bn_b_grad_buf, D,
                threads=(2 * D, 1, 1), group_size=(256, 1, 1)
            )
            grad_gamma, grad_beta = None, None
        else:
            grad_gamma = torch.empty_like(bn_w)
            grad_beta = torch.empty_like(bn_b)
            lib.copy_reset_two_fp32(
                bwd_stats, grad_gamma, grad_beta, D,
                threads=(2 * D, 1, 1), group_size=(256, 1, 1)
            )

        return grad_u, grad_conv_w, grad_gamma, grad_beta, None, None, None, None, None, None


class MetalFusedResL2NormFunction(torch.autograd.Function):
    """
    Fuses AudioToVectorReader tail:
      combined = masked_fill(res_scale * res + out, mask, 0.0)
      normed = masked_fill(F.normalize(combined.float(), p=2, dim=-1, eps=1e-5).bfloat16(), mask, 0.0)
    """
    @staticmethod
    def forward(
        ctx,
        out: torch.Tensor,
        res: torch.Tensor,
        res_scale: torch.Tensor,
        mask: torch.Tensor
    ) -> torch.Tensor:
        B, T, D = out.shape
        BT = B * T
        lib = get_metal_lib()
        out_c = out.contiguous()
        res_c = res.contiguous()
        mask_c = mask.contiguous()

        normed = torch.empty_like(out_c)
        inv_norm = torch.empty((BT,), device=out.device, dtype=torch.float32)

        lib.fused_res_l2norm_fwd_bf16(
            out_c, res_c, res_scale, mask_c, normed, inv_norm,
            threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
        )
        if any(ctx.needs_input_grad):
            ctx.save_for_backward(normed, res_c, inv_norm)
            ctx.res_scale_shape = res_scale.shape
        return normed

    @staticmethod
    def backward(ctx, grad_normed: torch.Tensor):
        normed, res_c, inv_norm = ctx.saved_tensors
        B, T, _ = normed.shape
        BT = B * T
        lib = get_metal_lib()
        gn_c = grad_normed.contiguous()

        grad_out = torch.empty_like(normed)
        grad_rs = torch.zeros((1,), device=normed.device, dtype=torch.float32)

        lib.fused_res_l2norm_bwd_bf16(
            gn_c, normed, res_c, inv_norm, grad_out, grad_rs,
            threads=(BT * 256, 1, 1), group_size=(256, 1, 1)
        )
        return grad_out, None, grad_rs.view(ctx.res_scale_shape), None


# ==============================================================================
# 2. 100% GPU Fused Metal CosineCTCHead + Log-CTC + Analytical Spherical Bank
# ==============================================================================

def _spherical_normalize_backward(
    grad_norm_w: torch.Tensor,
    norm_w: torch.Tensor,
    inv_norm_w: torch.Tensor,
    clamped_mask: torch.Tensor
) -> torch.Tensor:
    """Exact analytical Jacobian of F.normalize(w, p=2, dim=-1, eps=1e-5) without autograd overhead."""
    dot = (grad_norm_w * norm_w).sum(dim=-1, keepdim=True)
    proj = inv_norm_w * (grad_norm_w - norm_w * dot)
    return torch.where(clamped_mask, grad_norm_w * inv_norm_w, proj)


class FusedMetalCosineCTCLoss:
    """
    100% GPU-Resident CosineCTCHead + Online LogSumExp + Active-Gather + Metal FP32 Log-CTC Engine:
    - Caches normalized spherical Vector Bank across micro-steps (`mark_weights_dirty()` on step)
    - Eliminates CPU roundtrip (`lp_sub.to("cpu")`, `g_sub.to("mps")`) via `ctc_loss_fwd_bwd_fp32`
    - Fixes V2 active-gather softmax-backward `1 - P_active` gradient attenuation bug
    - Fixes missing `logit_scale` gradient accumulation and eliminates `logit_scale.item()` sync
    - Supports zero-sync loss accumulation (`sync_loss=False`) and unbiased dynamic-batch token scaling
    """
    def __init__(
        self,
        ctc_head: nn.Module,
        ctc_loss_fn: nn.Module,
        device: torch.device,
        accum_steps: int = 1,
        target_batch_tokens: Optional[float] = None,
    ):
        self.ctc_head = ctc_head
        self.ctc_loss_fn = ctc_loss_fn
        self.device = device
        self.accum_steps = max(1, int(accum_steps))
        self.target_batch_tokens = float(target_batch_tokens) if (target_batch_tokens is not None and target_batch_tokens > 0) else None

        vb = ctc_head.vector_bank
        self.D = vb.size(1)
        self.is_full_bank = (vb.size(0) == 2048)
        self.V = vb.size(0) if self.is_full_bank else (vb.size(0) + 1)

        self.W_all_bf16 = torch.empty((self.V, self.D), device=device, dtype=torch.bfloat16)
        self.b_all_bf16 = torch.zeros((self.V,), device=device, dtype=torch.bfloat16)
        self.loss_accum_buf = torch.zeros((2,), device=device, dtype=torch.float32)
        self._alpha_ws = torch.empty((0,), device=device, dtype=torch.float32)

        self._cached_norm_vb: Optional[torch.Tensor] = None
        self._cached_inv_norm_vb: Optional[torch.Tensor] = None
        self._cached_clamped_vb: Optional[torch.Tensor] = None
        self._cached_norm_blank: Optional[torch.Tensor] = None
        self._cached_inv_norm_blank: Optional[torch.Tensor] = None
        self._cached_clamped_blank: Optional[torch.Tensor] = None
        self._cached_scale: Optional[torch.Tensor] = None
        self._cached_in_bounds: Optional[torch.Tensor] = None
        self._weights_dirty = True

        if not ctc_head.trainable_vector_bank:
            vb_f32 = vb.to(device=device, dtype=torch.float32)
            norm_vb = F.normalize(vb_f32, p=2, dim=-1, eps=1e-5)
            if self.is_full_bank:
                self.W_all_bf16.copy_(norm_vb.to(torch.bfloat16))
            else:
                self.W_all_bf16[1:].copy_(norm_vb.to(torch.bfloat16))

    def mark_weights_dirty(self) -> None:
        self._weights_dirty = True

    @torch.no_grad()
    def _refresh_head_cache(self) -> None:
        if self.is_full_bank:
            if self.ctc_head.trainable_vector_bank:
                vb_f32 = self.ctc_head.vector_bank.float()
                raw_n = vb_f32.norm(p=2, dim=-1, keepdim=True)
                self._cached_clamped_vb = (raw_n <= 1e-5)
                self._cached_inv_norm_vb = 1.0 / raw_n.clamp(min=1e-5)
                self._cached_norm_vb = vb_f32 * self._cached_inv_norm_vb
                self.W_all_bf16.copy_(self._cached_norm_vb.to(torch.bfloat16))
            if hasattr(self.ctc_head, "vocab_bias") and self.ctc_head.vocab_bias is not None:
                self.b_all_bf16.copy_(self.ctc_head.vocab_bias.to(torch.bfloat16))
        else:
            bvec_f32 = self.ctc_head.blank_vec.float()
            raw_nb = bvec_f32.norm(p=2, dim=-1, keepdim=True)
            self._cached_clamped_blank = (raw_nb <= 1e-5)
            self._cached_inv_norm_blank = 1.0 / raw_nb.clamp(min=1e-5)
            self._cached_norm_blank = bvec_f32 * self._cached_inv_norm_blank
            self.W_all_bf16[0].copy_(self._cached_norm_blank.squeeze(0).to(torch.bfloat16))

            if self.ctc_head.trainable_vector_bank:
                vb_f32 = self.ctc_head.vector_bank.float()
                raw_n = vb_f32.norm(p=2, dim=-1, keepdim=True)
                self._cached_clamped_vb = (raw_n <= 1e-5)
                self._cached_inv_norm_vb = 1.0 / raw_n.clamp(min=1e-5)
                self._cached_norm_vb = vb_f32 * self._cached_inv_norm_vb
                self.W_all_bf16[1:].copy_(self._cached_norm_vb.to(torch.bfloat16))

            self.b_all_bf16[0] = self.ctc_head.blank_bias.squeeze(0).to(torch.bfloat16)
            self.b_all_bf16[1:].copy_(self.ctc_head.vocab_bias.to(torch.bfloat16))

        ls = self.ctc_head.logit_scale
        clamped_log = torch.clamp(ls, min=-5.0, max=5.2983)
        self._cached_scale = torch.exp(clamped_log)
        self._cached_in_bounds = ((ls >= -5.0) & (ls <= 5.2983)).to(torch.float32)
        self._weights_dirty = False

    @torch.no_grad()
    def pop_accumulated_loss(self) -> Tuple[float, float]:
        """Reads accumulated [sum_loss, count_or_tokens] from GPU in a single 8-byte sync and resets it."""
        vals = self.loss_accum_buf.cpu()
        self.loss_accum_buf.zero_()
        num = float(vals[0].item())
        den = float(vals[1].item())
        if den <= 0.0:
            return 0.0, 0.0
        return num / den, den

    @torch.no_grad()
    def forward_and_backward_head(
        self,
        embeddings: torch.Tensor,
        flat_targets: torch.Tensor,
        input_lengths: torch.Tensor,
        target_lengths: torch.Tensor,
        active_ids_cpu: Optional[torch.Tensor] = None,
        compact_targets: Optional[torch.Tensor] = None,
        packed_ctc_meta: Optional[torch.Tensor] = None,
        packed_ctc_sizes: Optional[Tuple[int, int, int, int]] = None,
        sync_loss: bool = True,
    ) -> Tuple[Optional[float], torch.Tensor]:
        lib = get_metal_lib()
        B, T, D = embeddings.shape
        V = self.V

        if self._weights_dirty or self._cached_scale is None:
            self._refresh_head_cache()

        # 1. Single-DMA H2D transfer when PadCollate provides packed_ctc_meta
        if packed_ctc_meta is not None and packed_ctc_sizes is not None:
            U, sum_L, max_L, tot_toks = packed_ctc_sizes
            meta_mps = packed_ctc_meta.to(self.device)
            active_ids_mps = meta_mps[:U]
            compact_t_mps = meta_mps[U : U + sum_L]
            in_lens_mps = meta_mps[U + sum_L : U + sum_L + B]
            tgt_lens_mps = meta_mps[U + sum_L + B : U + sum_L + 2 * B]
            tgt_offs_mps = meta_mps[U + sum_L + 2 * B : U + sum_L + 3 * B]
        else:
            if active_ids_cpu is None or compact_targets is None:
                uniq_t, inv_idx = torch.unique(flat_targets, sorted=True, return_inverse=True)
                active_ids_cpu = torch.cat([torch.zeros(1, dtype=torch.int32), uniq_t.to(torch.int32)])
                compact_targets = inv_idx + 1
            U = int(active_ids_cpu.numel())
            sum_L = int(compact_targets.numel())
            max_L = int(target_lengths.max().item()) if target_lengths.numel() > 0 else 0
            tot_toks = int(target_lengths.sum().item())
            t_offs_cpu = torch.zeros((B,), dtype=torch.int32)
            if B > 1:
                t_offs_cpu[1:] = torch.cumsum(target_lengths[:-1].to(torch.int32), dim=0)
            packed_cpu = torch.cat([
                active_ids_cpu.to(torch.int32),
                compact_targets.to(torch.int32),
                input_lengths.to(torch.int32),
                target_lengths.to(torch.int32),
                t_offs_cpu,
            ], dim=0)
            meta_mps = packed_cpu.to(self.device)
            active_ids_mps = meta_mps[:U]
            compact_t_mps = meta_mps[U : U + sum_L]
            in_lens_mps = meta_mps[U + sum_L : U + sum_L + B]
            tgt_lens_mps = meta_mps[U + sum_L + B : U + sum_L + 2 * B]
            tgt_offs_mps = meta_mps[U + sum_L + 2 * B : U + sum_L + 3 * B]

        scale = self._cached_scale
        emb_f32 = embeddings.detach().float()
        scaled_emb_bf16 = (emb_f32 * scale).to(torch.bfloat16)

        # 2. Cosine similarity GEMM in BF16: (B, T, V)
        logits = F.linear(scaled_emb_bf16, self.W_all_bf16, self.b_all_bf16)

        # 3. Fused Online FP32 LogSumExp + Active-Column Gather -> (T, B, U)
        lse_out = torch.empty((B * T,), device=self.device, dtype=torch.float32)
        lp_sub_mps = torch.empty((T, B, U), device=self.device, dtype=torch.float32)
        lib.fused_lse_gather_bf16(
            logits, active_ids_mps, lse_out, lp_sub_mps,
            B, T, V, U,
            threads=(B * T * 256, 1, 1), group_size=(256, 1, 1)
        )

        # 4. 100% GPU Custom Metal FP32 Log-CTC Forward + Backward (with CPU fallback if S_max > 1024)
        S_max = 2 * max_L + 1
        use_token_denom = 1 if self.target_batch_tokens is not None else 0
        if use_token_denom:
            grad_norm_denom = max(float(self.target_batch_tokens), 0.4 * float(max(tot_toks, 1))) * float(self.accum_steps)
        else:
            grad_norm_denom = float(max(B, 1) * self.accum_steps)

        if S_max <= 1024 and U <= 1024 and sum_L > 0:
            req_ws = B * T * max(S_max, 1)
            if self._alpha_ws.numel() < req_ws:
                self._alpha_ws = torch.empty((int(req_ws * 1.25),), device=self.device, dtype=torch.float32)
            alpha_ws = self._alpha_ws[:req_ws]
            g_sub_mps = torch.zeros((T, B, U), device=self.device, dtype=torch.float32)

            lib.ctc_loss_fwd_bwd_fp32(
                lp_sub_mps, compact_t_mps, in_lens_mps, tgt_lens_mps, tgt_offs_mps,
                alpha_ws, g_sub_mps, self.loss_accum_buf,
                B, T, U, S_max, use_token_denom, float(grad_norm_denom),
                threads=(B * 256, 1, 1), group_size=(256, 1, 1)
            )
            loss_val: Optional[float] = None
            if sync_loss:
                loss_val, _ = self.pop_accumulated_loss()
        else:
            # Rare fallback (>511 tokens in a single utterance or >1023 active tokens)
            lp_sub_cpu = lp_sub_mps.to("cpu")
            ct_cpu = compact_targets if compact_targets is not None else compact_t_mps.to("cpu", dtype=torch.long)
            with torch.enable_grad():
                lp_leaf = lp_sub_cpu.requires_grad_(True)
                if use_token_denom:
                    loss_sum = F.ctc_loss(
                        lp_leaf, ct_cpu.long(), input_lengths.long(), target_lengths.long(),
                        blank=0, reduction="sum", zero_infinity=True
                    )
                    loss_val_f = float(loss_sum.detach().item()) / max(tot_toks, 1)
                    (loss_sum / grad_norm_denom).backward()
                    in_mask = (torch.arange(T).unsqueeze(1) < input_lengths.view(1, B)).unsqueeze(-1).float()
                    pure_g = lp_leaf.grad - (1.0 / grad_norm_denom) * lp_sub_cpu.exp() * in_mask
                    self.loss_accum_buf[0] += float(loss_sum.detach().item())
                    self.loss_accum_buf[1] += float(max(tot_toks, 1))
                else:
                    loss_m = self.ctc_loss_fn(lp_leaf, ct_cpu.long(), input_lengths.long(), target_lengths.long())
                    loss_val_f = float(loss_m.detach().item())
                    (loss_m / self.accum_steps).backward()
                    in_mask = (torch.arange(T).unsqueeze(1) < input_lengths.view(1, B)).unsqueeze(-1).float()
                    wb = (1.0 / (target_lengths.float().clamp(min=1.0).view(1, B, 1) * grad_norm_denom)) * in_mask
                    pure_g = lp_leaf.grad - wb * lp_sub_cpu.exp()
                    self.loss_accum_buf[0] += loss_val_f
                    self.loss_accum_buf[1] += 1.0
            g_sub_mps = pure_g.to(self.device)
            loss_val = self.pop_accumulated_loss()[0] if sync_loss else None

        # 5. Exact Fused Softmax Backward + Active Scatter in-place into logits -> dZ_bf16
        lib.fused_softmax_scatter_bwd_bf16(
            logits, lse_out, g_sub_mps, active_ids_mps,
            B, T, V, U,
            threads=(B * T * 256, 1, 1), group_size=(256, 1, 1)
        )
        dZ_bf16 = logits

        # 6. CosineCTCHead Parameter Gradients & Analytical Spherical Jacobian (0 CPU Sync!)
        grad_bias_all = dZ_bf16.sum(dim=(0, 1)).float()
        grad_scaled_emb = torch.matmul(dZ_bf16, self.W_all_bf16).float()
        grad_emb = (grad_scaled_emb * scale).to(embeddings.dtype)

        grad_scale = (
            (grad_scaled_emb * emb_f32).sum().view_as(self.ctc_head.logit_scale)
            * scale
            * self._cached_in_bounds
        )
        self._accum_grad(self.ctc_head.logit_scale, grad_scale)

        if self.is_full_bank:
            if hasattr(self.ctc_head, "vocab_bias") and self.ctc_head.vocab_bias is not None:
                self._accum_grad(self.ctc_head.vocab_bias, grad_bias_all)

            if self.ctc_head.trainable_vector_bank and self.ctc_head.vector_bank.requires_grad:
                grad_norm_vb = torch.matmul(dZ_bf16.reshape(-1, V).t(), scaled_emb_bf16.reshape(-1, D)).float()
                grad_vb = _spherical_normalize_backward(
                    grad_norm_vb, self._cached_norm_vb, self._cached_inv_norm_vb, self._cached_clamped_vb
                )
                self._accum_grad(self.ctc_head.vector_bank, grad_vb)
        else:
            grad_norm_blank = torch.matmul(dZ_bf16[:, :, 0:1].transpose(1, 2), scaled_emb_bf16).sum(dim=0).float()
            grad_bvec = _spherical_normalize_backward(
                grad_norm_blank, self._cached_norm_blank, self._cached_inv_norm_blank, self._cached_clamped_blank
            )
            self._accum_grad(self.ctc_head.blank_vec, grad_bvec)
            self._accum_grad(self.ctc_head.blank_bias, grad_bias_all[0:1])
            self._accum_grad(self.ctc_head.vocab_bias, grad_bias_all[1:])

            if self.ctc_head.trainable_vector_bank and self.ctc_head.vector_bank.requires_grad:
                grad_norm_vb = torch.matmul(dZ_bf16[:, :, 1:].reshape(-1, V - 1).t(), scaled_emb_bf16.reshape(-1, D)).float()
                grad_vb = _spherical_normalize_backward(
                    grad_norm_vb, self._cached_norm_vb, self._cached_inv_norm_vb, self._cached_clamped_vb
                )
                self._accum_grad(self.ctc_head.vector_bank, grad_vb)

        return loss_val, grad_emb

    @staticmethod
    def _accum_grad(param: nn.Parameter, g: torch.Tensor) -> None:
        if not param.requires_grad:
            return
        if param.grad is None:
            param.grad = g.to(dtype=param.dtype)
        else:
            param.grad.add_(g.to(dtype=param.dtype))


# ==============================================================================
# 3. Zero-Sync Contiguous Flat-Buffer Metal AdamW + In-Kernel Grad Clipping
# ==============================================================================

class FlatBufferMetalAdamW(torch.optim.Optimizer):
    """
    Packs all model parameters and gradients into 3 contiguous flat buffers on MPS:
      1. BF16 Decay Group (Conformer Linear/Conv weights) with FP32 Master Weights
      2. BF16 No-Decay Group (Conformer LayerNorm weights/biases & Linear/Conv biases) with FP32 Master Weights
      3. FP32 No-Decay Group (BatchNorm1d weights/biases, res_scale, CosineCTCHead parameters)
    Eliminates per-step `total_sq_buf.item()` GPU->CPU sync by computing `clip_coef` and
    `isfinite` guards directly inside the Metal AdamW shaders.
    """
    def __init__(
        self,
        model: nn.Module,
        lr: float = 2e-4,
        betas: Tuple[float, float] = (0.9, 0.98),
        eps: float = 1e-8,
        weight_decay: float = 1e-2,
        fp32_init: Optional[Dict[str, torch.Tensor]] = None
    ):
        self.model = model
        self.device = next(model.parameters()).device
        self.betas = betas
        self.eps = eps
        self.step_count = 0
        self.ctc_engine: Optional[FusedMetalCosineCTCLoss] = None

        self.bf16_decay_list: List[Tuple[str, nn.Parameter]] = []
        self.bf16_nodecay_list: List[Tuple[str, nn.Parameter]] = []
        self.fp32_nodecay_list: List[Tuple[str, nn.Parameter]] = []

        for name, param in model.named_parameters():
            if not param.requires_grad:
                continue
            is_no_decay = (
                "ctc_head" in name
                or name.endswith(".bias")
                or "norm" in name.lower()
                or "bn" in name.lower()
                or "res_scale" in name
            )
            if param.dtype == torch.bfloat16:
                if is_no_decay:
                    self.bf16_nodecay_list.append((name, param))
                else:
                    self.bf16_decay_list.append((name, param))
            else:
                self.fp32_nodecay_list.append((name, param))

        self.g1_numel, self.g1_param_buf, self.g1_master_buf, self.g1_grad_buf, self.g1_m, self.g1_v, self.g1_slices = (
            self._pack_bf16_group(self.bf16_decay_list, fp32_init)
        )
        self.g2_numel, self.g2_param_buf, self.g2_master_buf, self.g2_grad_buf, self.g2_m, self.g2_v, self.g2_slices = (
            self._pack_bf16_group(self.bf16_nodecay_list, fp32_init)
        )
        self.g3_numel, self.g3_param_buf, self.g3_grad_buf, self.g3_m, self.g3_v, self.g3_slices = (
            self._pack_fp32_group(self.fp32_nodecay_list)
        )

        self.total_sq_buf = torch.zeros((1,), device=self.device, dtype=torch.float32)

        param_groups = [
            {"params": [p for _, p in self.bf16_decay_list], "lr": lr, "initial_lr": lr, "weight_decay": weight_decay, "betas": betas, "eps": eps},
            {"params": [p for _, p in self.bf16_nodecay_list] + [p for _, p in self.fp32_nodecay_list], "lr": lr, "initial_lr": lr, "weight_decay": 0.0, "betas": betas, "eps": eps},
        ]
        defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
        super().__init__(param_groups, defaults)
        self._bind_fused_views()

    def _bind_fused_views(self) -> None:
        """
        Binds contiguous parameter & gradient views from flat buffers onto all
        Linear, Conv1d, LayerNorm, BatchNorm1d, and MultiHeadAttention modules so
        forward/backward kernels accumulate gradients directly into flat buffers.
        """
        for mod_name, mod in self.model.named_modules():
            prefix = f"{mod_name}." if mod_name else ""

            # 1. Fused QKV views on ExplicitMultiHeadAttention
            if all(hasattr(mod, attr) for attr in ("q_proj", "k_proj", "v_proj", "embed_dim")):
                qw_k, kw_k, vw_k = f"{prefix}q_proj.weight", f"{prefix}k_proj.weight", f"{prefix}v_proj.weight"
                qb_k, kb_k, vb_k = f"{prefix}q_proj.bias", f"{prefix}k_proj.bias", f"{prefix}v_proj.bias"
                if (
                    qw_k in self.g1_slices and kw_k in self.g1_slices and vw_k in self.g1_slices
                    and qb_k in self.g2_slices and kb_k in self.g2_slices and vb_k in self.g2_slices
                ):
                    sq, eq, _ = self.g1_slices[qw_k]
                    sk, ek, _ = self.g1_slices[kw_k]
                    sv, ev, _ = self.g1_slices[vw_k]
                    sqb, eqb, _ = self.g2_slices[qb_k]
                    skb, ekb, _ = self.g2_slices[kb_k]
                    svb, evb, _ = self.g2_slices[vb_k]
                    d = mod.embed_dim
                    if eq == sk and ek == sv and eqb == skb and ekb == svb:
                        mod._qkv_w_view = self.g1_param_buf[sq:ev].view(3 * d, d)
                        mod._qkv_w_grad_view = self.g1_grad_buf[sq:ev].view(3 * d, d)
                        mod._qkv_b_view = self.g2_param_buf[sqb:evb].view(3 * d)
                        mod._qkv_b_grad_view = self.g2_grad_buf[sqb:evb].view(3 * d)

            # 2. Individual Linear & Conv1d flat grad views
            if isinstance(mod, (nn.Linear, nn.Conv1d)):
                wk = f"{prefix}weight"
                bk = f"{prefix}bias"
                if wk in self.g1_slices:
                    sw, ew, sh_w = self.g1_slices[wk]
                    if isinstance(mod, nn.Conv1d) and len(sh_w) == 3 and sh_w[2] == 1:
                        mod._flat_w_2d = self.g1_param_buf[sw:ew].view(sh_w[0], sh_w[1])
                        mod._flat_w_grad = self.g1_grad_buf[sw:ew].view(sh_w[0], sh_w[1])
                    else:
                        mod._flat_w_grad = self.g1_grad_buf[sw:ew].view(sh_w)
                if bk in self.g2_slices:
                    sb, eb, sh_b = self.g2_slices[bk]
                    mod._flat_b_grad = self.g2_grad_buf[sb:eb].view(sh_b)

            # 3. LayerNorm contiguous [gamma, beta] 2D grad view
            elif isinstance(mod, nn.LayerNorm):
                wk, bk = f"{prefix}weight", f"{prefix}bias"
                if wk in self.g2_slices and bk in self.g2_slices:
                    sw, ew, _ = self.g2_slices[wk]
                    sb, eb, _ = self.g2_slices[bk]
                    if ew == sb:
                        mod._flat_wb_grad = self.g2_grad_buf[sw:eb]

            # 4. BatchNorm1d FP32 grad views
            elif isinstance(mod, nn.BatchNorm1d):
                wk, bk = f"{prefix}weight", f"{prefix}bias"
                if wk in self.g3_slices and bk in self.g3_slices:
                    sw, ew, sh_w = self.g3_slices[wk]
                    sb, eb, sh_b = self.g3_slices[bk]
                    mod._flat_w_grad = self.g3_grad_buf[sw:ew].view(sh_w)
                    mod._flat_b_grad = self.g3_grad_buf[sb:eb].view(sh_b)

    # Alias preserved for backward compatibility
    _bind_fused_qkv_views = _bind_fused_views

    def _pack_bf16_group(
        self,
        named_params: List[Tuple[str, nn.Parameter]],
        fp32_init: Optional[Dict[str, torch.Tensor]] = None
    ):
        total_n = sum(p.numel() for _, p in named_params)
        if total_n == 0:
            empty_bf = torch.empty((0,), device=self.device, dtype=torch.bfloat16)
            empty_fp = torch.empty((0,), device=self.device, dtype=torch.float32)
            return 0, empty_bf, empty_fp, empty_bf, empty_fp, empty_fp, {}

        param_buf = torch.empty((total_n,), device=self.device, dtype=torch.bfloat16)
        master_buf = torch.empty((total_n,), device=self.device, dtype=torch.float32)
        grad_buf = torch.zeros((total_n,), device=self.device, dtype=torch.bfloat16)
        m_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
        v_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
        slices: Dict[str, Tuple[int, int, torch.Size]] = {}

        offset = 0
        for name, p in named_params:
            n = p.numel()
            shape = p.shape
            src_fp32 = fp32_init[name] if (fp32_init is not None and name in fp32_init) else p.data.float()
            master_buf[offset : offset + n].copy_(src_fp32.view(-1))
            param_buf[offset : offset + n].copy_(src_fp32.to(torch.bfloat16).view(-1))
            p.data = param_buf[offset : offset + n].view(shape)
            p.grad = grad_buf[offset : offset + n].view(shape)
            slices[name] = (offset, offset + n, shape)
            offset += n

        return total_n, param_buf, master_buf, grad_buf, m_buf, v_buf, slices

    def _pack_fp32_group(self, named_params: List[Tuple[str, nn.Parameter]]):
        total_n = sum(p.numel() for _, p in named_params)
        if total_n == 0:
            empty_fp = torch.empty((0,), device=self.device, dtype=torch.float32)
            return 0, empty_fp, empty_fp, empty_fp, empty_fp, {}

        param_buf = torch.empty((total_n,), device=self.device, dtype=torch.float32)
        grad_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
        m_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
        v_buf = torch.zeros((total_n,), device=self.device, dtype=torch.float32)
        slices: Dict[str, Tuple[int, int, torch.Size]] = {}

        offset = 0
        for name, p in named_params:
            n = p.numel()
            shape = p.shape
            param_buf[offset : offset + n].copy_(p.data.float().view(-1))
            p.data = param_buf[offset : offset + n].view(shape)
            p.grad = grad_buf[offset : offset + n].view(shape)
            slices[name] = (offset, offset + n, shape)
            offset += n

        return total_n, param_buf, grad_buf, m_buf, v_buf, slices

    def step(self, closure=None):
        """Hook called by clip_grad_and_step so PyTorch LRScheduler step-order tracking is satisfied."""
        pass

    @torch.no_grad()
    def clip_grad_and_step(self, max_norm: float = 1.0, sync_norm: bool = True) -> Optional[float]:
        """
        Zero-sync global L2 GradNorm + In-Kernel Clipped AdamW + FP32->BF16 writeback + zero_grad.
        When `sync_norm=False`, executes 100% asynchronously on MPS with zero CPU stalls; any
        non-finite gradient norm is caught inside the Metal shader itself (skipping the update
        while zeroing gradients). When `sync_norm=True`, returns the scalar global grad norm.
        """
        lib = get_metal_lib()
        self.total_sq_buf.zero_()

        if self.g1_numel > 0:
            lib.grad_norm_sq_bf16(
                self.g1_grad_buf, self.total_sq_buf, int(self.g1_numel),
                threads=(1024 * 256, 1, 1), group_size=(256, 1, 1)
            )
        if self.g2_numel > 0:
            lib.grad_norm_sq_bf16(
                self.g2_grad_buf, self.total_sq_buf, int(self.g2_numel),
                threads=(256 * 256, 1, 1), group_size=(256, 1, 1)
            )
        if self.g3_numel > 0:
            lib.grad_norm_sq_fp32(
                self.g3_grad_buf, self.total_sq_buf, int(self.g3_numel),
                threads=(256 * 256, 1, 1), group_size=(256, 1, 1)
            )

        next_step = self.step_count + 1
        beta1, beta2 = self.betas
        bc1 = float(1.0 - (beta1 ** next_step))
        bc2_sqrt = float(math.sqrt(1.0 - (beta2 ** next_step)))
        lr1 = float(self.param_groups[0]["lr"])
        wd1 = float(self.param_groups[0]["weight_decay"])
        lr2 = float(self.param_groups[1]["lr"])
        eps_f = float(self.eps)
        max_n = float(max_norm)

        if self.g1_numel > 0:
            lib.fused_adamw_master_bf16(
                self.g1_param_buf, self.g1_master_buf, self.g1_grad_buf, self.g1_m, self.g1_v,
                self.total_sq_buf, int(self.g1_numel),
                lr1, float(beta1), float(beta2), eps_f, wd1, bc1, bc2_sqrt, max_n,
                threads=(self.g1_numel, 1, 1), group_size=(256, 1, 1)
            )
        if self.g2_numel > 0:
            lib.fused_adamw_master_bf16(
                self.g2_param_buf, self.g2_master_buf, self.g2_grad_buf, self.g2_m, self.g2_v,
                self.total_sq_buf, int(self.g2_numel),
                lr2, float(beta1), float(beta2), eps_f, 0.0, bc1, bc2_sqrt, max_n,
                threads=(self.g2_numel, 1, 1), group_size=(256, 1, 1)
            )
        if self.g3_numel > 0:
            lib.fused_adamw_fp32(
                self.g3_param_buf, self.g3_grad_buf, self.g3_m, self.g3_v,
                self.total_sq_buf, int(self.g3_numel),
                lr2, float(beta1), float(beta2), eps_f, 0.0, bc1, bc2_sqrt, max_n,
                threads=(self.g3_numel, 1, 1), group_size=(256, 1, 1)
            )

        if self.ctc_engine is not None:
            self.ctc_engine.mark_weights_dirty()

        if sync_norm:
            total_sq = float(self.total_sq_buf.item())
            if math.isnan(total_sq) or math.isinf(total_sq) or total_sq < 0.0:
                return float("nan")
            self.step_count = next_step
            self.step()
            return math.sqrt(total_sq)

        self.step_count = next_step
        self.step()
        return None

    @torch.no_grad()
    def zero_grad(self, set_to_none: bool = False) -> None:
        if self.g1_numel > 0:
            self.g1_grad_buf.zero_()
        if self.g2_numel > 0:
            self.g2_grad_buf.zero_()
        if self.g3_numel > 0:
            self.g3_grad_buf.zero_()

    @torch.no_grad()
    def sync_master_from_model(self) -> None:
        for name, p in self.bf16_decay_list:
            s, e, shape = self.g1_slices[name]
            self.g1_master_buf[s:e].copy_(p.data.float().view(-1))
            self.g1_param_buf[s:e].copy_(p.data.to(torch.bfloat16).view(-1))
            p.data = self.g1_param_buf[s:e].view(shape)
            p.grad = self.g1_grad_buf[s:e].view(shape)
        for name, p in self.bf16_nodecay_list:
            s, e, shape = self.g2_slices[name]
            self.g2_master_buf[s:e].copy_(p.data.float().view(-1))
            self.g2_param_buf[s:e].copy_(p.data.to(torch.bfloat16).view(-1))
            p.data = self.g2_param_buf[s:e].view(shape)
            p.grad = self.g2_grad_buf[s:e].view(shape)
        for name, p in self.fp32_nodecay_list:
            s, e, shape = self.g3_slices[name]
            self.g3_param_buf[s:e].copy_(p.data.float().view(-1))
            p.data = self.g3_param_buf[s:e].view(shape)
            p.grad = self.g3_grad_buf[s:e].view(shape)
        self._bind_fused_views()

    @torch.no_grad()
    def get_fp32_model_state_dict(self) -> Dict[str, torch.Tensor]:
        """Returns a full FP32 model_state_dict using the exact FP32 master weights for lossless checkpoint saving."""
        sd = self.model.state_dict()
        out_sd: Dict[str, torch.Tensor] = {}
        for k, v in sd.items():
            if k in self.g1_slices:
                s, e, shape = self.g1_slices[k]
                out_sd[k] = self.g1_master_buf[s:e].view(shape).cpu().clone()
            elif k in self.g2_slices:
                s, e, shape = self.g2_slices[k]
                out_sd[k] = self.g2_master_buf[s:e].view(shape).cpu().clone()
            else:
                out_sd[k] = v.float().cpu().clone() if v.is_floating_point() else v.cpu().clone()
        return out_sd

    def state_dict(self, include_master: bool = False) -> Dict[str, Any]:
        """
        When saved alongside `get_fp32_model_state_dict()`, omitting `g1_master` / `g2_master`
        eliminates ~84 MB of duplicate FP32 weights per checkpoint while remaining 100% lossless.
        """
        sd: Dict[str, Any] = {
            "flat_metal_adamw": True,
            "step_count": self.step_count,
            "lr0": self.param_groups[0]["lr"],
            "lr1": self.param_groups[1]["lr"],
            "g1_m": self.g1_m.cpu(),
            "g1_v": self.g1_v.cpu(),
            "g2_m": self.g2_m.cpu(),
            "g2_v": self.g2_v.cpu(),
            "g3_m": self.g3_m.cpu(),
            "g3_v": self.g3_v.cpu(),
        }
        if include_master:
            sd["g1_master"] = self.g1_master_buf.cpu()
            sd["g2_master"] = self.g2_master_buf.cpu()
        return sd

    def load_state_dict(self, sd: Dict[str, Any]) -> None:
        if not sd.get("flat_metal_adamw", False):
            return
        self.step_count = int(sd.get("step_count", 0))
        if "lr0" in sd:
            self.param_groups[0]["lr"] = float(sd["lr0"])
        if "lr1" in sd:
            self.param_groups[1]["lr"] = float(sd["lr1"])
        if "g1_master" in sd and sd["g1_master"].numel() == self.g1_numel:
            self.g1_master_buf.copy_(sd["g1_master"].to(self.device))
            self.g1_param_buf.copy_(self.g1_master_buf.to(torch.bfloat16))
        if "g1_m" in sd and sd["g1_m"].numel() == self.g1_numel:
            self.g1_m.copy_(sd["g1_m"].to(self.device))
            self.g1_v.copy_(sd["g1_v"].to(self.device))
        if "g2_master" in sd and sd["g2_master"].numel() == self.g2_numel:
            self.g2_master_buf.copy_(sd["g2_master"].to(self.device))
            self.g2_param_buf.copy_(self.g2_master_buf.to(torch.bfloat16))
        if "g2_m" in sd and sd["g2_m"].numel() == self.g2_numel:
            self.g2_m.copy_(sd["g2_m"].to(self.device))
            self.g2_v.copy_(sd["g2_v"].to(self.device))
        if "g3_m" in sd and sd["g3_m"].numel() == self.g3_numel:
            self.g3_m.copy_(sd["g3_m"].to(self.device))
            self.g3_v.copy_(sd["g3_v"].to(self.device))
        if self.ctc_engine is not None:
            self.ctc_engine.mark_weights_dirty()