inky-engine 3.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
// ================================ batched prefill kernels ================================
// Activations are [T][dim] row-major f32 in the arena A. Included after kernels.metal.

#define GM_BM 64
#define GM_BN 32
#define GM_BK 32

// dequantize 16 consecutive weights (k0 % 16 == 0) of one row into half
// 4 nibbles (one per byte of u, values 0..15) -> 4 exact halves via the 0x6400|n trick (= 1024 + n), minus 1024
inline half4 nib4(uint u) {
    const uint lo = (u & 0xFFu) | ((u & 0xFF00u) << 8), hi = ((u >> 16) & 0xFFu) | ((u >> 8) & 0xFF0000u);
    return half4(as_type<half2>(lo | 0x64006400u), as_type<half2>(hi | 0x64006400u)) - half4(1024.0h);
}

// fast Q4_K dequant of 16 weights: vectorized nibble -> half, w = q*d - m in fp16 FMA (single rounding)
inline void deq16_q4k(device const uchar * row, uint k0, thread half * out) {
    device const block_q4_K * b = (device const block_q4_K *) row + k0 / 256;
    const uint w = k0 % 256, j = w / 32, hp = (w % 32) / 16;
    float sc, m;
    scale_min_k4(j, b->scales, sc, m);
    // fp32 scale/offset, single rounding to half at the end (same numerics as the scalar path)
    const float df = float(b->d) * sc, mf = float(b->dmin) * m;
    const uint4 v = *(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16);
    const uint sh = (j & 1) * 4;
    thread half4 * o = (thread half4 *) out;
    o[0] = half4(fma(float4(nib4((v.x >> sh) & 0x0F0F0F0Fu)), df, -mf));
    o[1] = half4(fma(float4(nib4((v.y >> sh) & 0x0F0F0F0Fu)), df, -mf));
    o[2] = half4(fma(float4(nib4((v.z >> sh) & 0x0F0F0F0Fu)), df, -mf));
    o[3] = half4(fma(float4(nib4((v.w >> sh) & 0x0F0F0F0Fu)), df, -mf));
}

inline void deq16(device const uchar * row, uint wtype, uint k0, thread half * out) {
    if (wtype == 12) { deq16_q4k(row, k0, out); return; }
    if (wtype == 11) {          // Q3_K: 110 bytes per 256 weights (3.4375 bpw)
        device const block_q3_K * b = (device const block_q3_K *) (row + (ulong) (k0 / 256u) * 110u);
        const uint w = k0 % 256u, n = w / 128u, g = (w % 128u) / 32u, hp = (w % 32u) / 16u;
        const float dl = float(b->d) * float(q3k_scale(b->scales, 8u * n + 2u * g + hp));
        device const uchar * qp = b->qs + 32u * n + 16u * hp;
        device const uchar * hm = b->hmask + 16u * hp;
        const uint sh = 2u * g;
        const uchar m = uchar(1u << (4u * n + g));
        for (int i = 0; i < 16; i++) {
            const int q = int((qp[i] >> sh) & 3u) - ((hm[i] & m) ? 0 : 4);
            out[i] = half(dl * float(q));
        }
        return;
    }
    if (wtype == 10) {          // Q2_K: 84 bytes per 256 weights (2.625 bpw)
        device const block_q2_K * b = (device const block_q2_K *) (row + (ulong) (k0 / 256u) * 84u);
        const uint w = k0 % 256u, n = w / 128u, g = (w % 128u) / 32u, hp = (w % 32u) / 16u;
        const uchar sc = b->scales[8u * n + 2u * g + hp];
        const float dl = float(b->d) * float(sc & 0xFu);
        const float ml = float(b->dmin) * float(sc >> 4);
        device const uchar * qp = b->qs + 32u * n + 16u * hp;
        const uint sh = 2u * g;
        for (int i = 0; i < 16; i++) {
            out[i] = half(dl * float((qp[i] >> sh) & 3u) - ml);
        }
        return;
    }
    if (wtype == 202) {         // Q3_0: 14 bytes per 32 weights (3.50 bpw)
        device const block_q3_0 * b = (device const block_q3_0 *) (row + (ulong) (k0 / 32u) * 14u);
        const float d = float(b->d);
        const bool hi = (k0 % 32u) != 0u;
        const uint hb = ((device const ushort *) b->qh)[hi ? 1 : 0];
        device const uchar * qp = b->qs + (hi ? 4 : 0);
        for (int i = 0; i < 16; i++) {
            const uint q2 = (qp[i >> 2] >> ((i & 3) * 2)) & 3u;
            const uint qh = ((hb >> i) & 1u) << 2;
            out[i] = half(d * float(int(q2 | qh) - 4));
        }
        return;
    }
    if (wtype == 200) {         // NV4: fp4 * e4m3 scale is exact in half (|w| <= 6 * 448); expert gscale applied later in fp32
        device const uchar * b = row + (k0 / 32) * 18;
        const uint hp = (k0 % 32) / 16;
        const float s = e4m3f(b[hp]) * NV4_K;
        // four codes a word: the sign and magnitude bits of each placed into a half (as fp4f), two halves a word
        // 16-bit loads: a block is 18 bytes, so its codes are only 2-byte aligned (a 32-bit load there reads the wrong bytes)
        // Ported from chadlyb/erisinky 36c497fb by Chad: "My changes are Copyright (C) 2026 Rewt", GPL-3.0-or-later.
        device const ushort * p = (device const ushort *) (b + 2);
        thread half4 * o = (thread half4 *) out;
        for (int i = 0; i < 4; i++) {
            const uint u = (uint(p[2 * i]) | (uint(p[2 * i + 1]) << 16)) >> (hp * 4), lo = (u & 0xFu) | ((u & 0xF00u) << 8), hi = ((u >> 16) & 0xFu) | ((u >> 8) & 0xF0000u);
            const half4 h = half4(as_type<half2>(((lo & 0x00080008u) << 12) | ((lo & 0x00070007u) << 9)), as_type<half2>(((hi & 0x00080008u) << 12) | ((hi & 0x00070007u) << 9)));
            o[i] = half4(float4(h) * s);
        }
        return;
    }
    if (wtype == 201) {         // MX8: e4m3 * a power of two
        device const uchar * b = row + (k0 / 32) * 34;
        const float d = float(*(device const half *) b) * MX8_K;
        device const packed_uchar4 * q4 = (device const packed_uchar4 *) (b + 2 + (k0 % 32));
        thread half4 * o = (thread half4 *) out;
        for (int i = 0; i < 4; i++) o[i] = half4(e4m3f4(uchar4(q4[i])) * d);
        return;
    }
    if (wtype == 8) {           // Q8_0: int8 * d. |q| <= 127 is exact in half, so the half product is the correctly rounded w
        device const block_q8_0 * b = (device const block_q8_0 *) row + k0 / 32;
        const half d = b->d;
        device const packed_char4 * q = (device const packed_char4 *) (b->qs + (k0 % 32));
        thread half4 * o = (thread half4 *) out;
        for (int i = 0; i < 4; i++) o[i] = half4(char4(q[i])) * d;
        return;
    }
    if (wtype == 30) {          // BF16: the upper half of a float
        device const packed_ushort4 * p = (device const packed_ushort4 *) ((device const ushort *) row + k0);
        thread half4 * o = (thread half4 *) out;
        for (int i = 0; i < 4; i++) o[i] = half4(as_type<float4>(uint4(ushort4(p[i])) << 16));
        return;
    }
    if (wtype == 6) {           // Q5_0: (nibble | high bit << 4) - 16, * d; SWAR unpack of 4 weights per word
        device const block_q5_0 * b = (device const block_q5_0 *) row + k0 / 32;
        const half d = b->d;
        const bool hi = (k0 % 32) != 0;
        // (qs is only 2-byte aligned: load it as ushorts)
        const ushort4 qa = ushort4(((device const packed_ushort4 *) b->qs)[0]), qb = ushort4(((device const packed_ushort4 *) b->qs)[1]);
        const uint4 v = uint4(uint(qa.x) | uint(qa.y) << 16, uint(qa.z) | uint(qa.w) << 16, uint(qb.x) | uint(qb.y) << 16, uint(qb.z) | uint(qb.w) << 16);
        const uint hb = ((device const ushort *) b->qh)[hi ? 1 : 0];     // the 16 high bits of this half-block
        const uint sh = hi ? 4 : 0;
        thread half4 * o = (thread half4 *) out;
        for (int i = 0; i < 4; i++) {
            const uint n = (v[i] >> sh) & 0x0F0F0F0Fu;
            const uint h = (((hb >> (4 * i)) & 0xFu) * 0x00204081u) & 0x01010101u;     // bit j -> byte j
            // q - 16 as int8: nibble | 0xF0 when the high bit is clear
            const uint qb = n | ((0x01010101u - h) * 0xF0u);
            o[i] = half4(as_type<char4>(qb)) * d;
        }
        return;
    }
    if (wtype == 12) {          // Q4_K
        device const block_q4_K * b = (device const block_q4_K *) row + k0 / 256;
        const uint w = k0 % 256, j = w / 32, hp = (w % 32) / 16;
        float sc, m;
        scale_min_k4(j, b->scales, sc, m);
        const float d = float(b->d) * sc, dm = float(b->dmin) * m;
        const uint4 q = *(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16);
        const uint sh = (j & 1) * 4;
        thread const uchar * qb = (thread const uchar *) &q;
        for (int i = 0; i < 16; i++) out[i] = half(d * float((qb[i] >> sh) & 0xF) - dm);
    } else if (wtype == 14) {   // Q6_K
        device const block_q6_K * b = (device const block_q6_K *) row + k0 / 256;
        const uint w = k0 % 256, n = w / 128, g = (w % 128) / 32, l0 = w % 32;
        const float d = float(b->d) * float(b->scales[8 * n + l0 / 16 + 2 * g]);
        device const uchar * ql = b->ql + 64 * n + (g & 1) * 32 + l0;
        device const uchar * qh = b->qh + 32 * n + l0;
        const uint s4 = (g >> 1) * 4, s2 = 2 * g;
        for (int i = 0; i < 16; i++) out[i] = half(d * float(int(((ql[i] >> s4) & 0xF) | (((qh[i] >> s2) & 3) << 4)) - 32));
    } else if (wtype == 8) {    // Q8_0
        device const block_q8_0 * b = (device const block_q8_0 *) row + k0 / 32;
        const float d = b->d;
        device const char * q = b->qs + (k0 % 32);
        for (int i = 0; i < 16; i++) out[i] = half(d * float(q[i]));
    } else if (wtype == 6) {    // Q5_0
        device const block_q5_0 * b = (device const block_q5_0 *) row + k0 / 32;
        const float d = b->d;
        const uint qh = uint(b->qh[0]) | (uint(b->qh[1]) << 8) | (uint(b->qh[2]) << 16) | (uint(b->qh[3]) << 24);
        const bool hi = (k0 % 32) != 0;
        for (int i = 0; i < 16; i++) {
            const uint q = hi ? (b->qs[i] >> 4) | (((qh >> (i + 16)) & 1) << 4) : (b->qs[i] & 0xF) | (((qh >> i) & 1) << 4);
            out[i] = half(d * float(int(q) - 16));
        }
    } else {                    // BF16
        device const ushort * p = (device const ushort *) row + k0;
        for (int i = 0; i < 16; i++) out[i] = half(bf16f(p[i]));
    }
}

struct GSeg {
    uint w_lo, w_hi, row_bytes, wtype;
    uint nrows, K, tile_start, in_off;
    uint out_off, ldo, wsrc, in2;    // in2 != 0: columns [K/2, K) come from a second [T][K/2] input
};
struct GemmArgs { uint nseg, T, pad0, pad1; GSeg seg[10]; };

// core tile loop: C[32 tokens x 64 rows] += X[tokens][K] * W[rows][K]^T
// xrow(t) gives the device pointer to token t's input row (or null for padding)
struct GemmTile {
    simdgroup_float8x8 mc[8];
};

// Y[t][n] = sum_k X[t][k] W[n][k]; grid: (row tiles over all segments, token tiles); 128 threads
kernel void k_gemm(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                   constant GemmArgs & args [[buffer(5)]],
                   uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                   ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup half sa[GM_BM * GM_BK];
    threadgroup half sb[GM_BN * GM_BK];
    threadgroup float sc[GM_BN * GM_BM];
    uint si = 0;
    while (si + 1 < args.nseg && tgp.x >= args.seg[si + 1].tile_start) si++;
    constant GSeg & S = args.seg[si];
    const uint r0 = (tgp.x - S.tile_start) * GM_BM, t0 = tgp.y * GM_BN;
    const uint T = args.T, K = S.K;
    device const uchar * wb = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
    const uint wr = tid / 2, wh = tid % 2;
    const uint xt = tid / 4, xk = (tid % 4) * 8;
    const bool wvalid = r0 + wr < S.nrows, xvalid = t0 + xt < T;
    device const uchar * wrow = wb + (ulong) min(r0 + wr, S.nrows - 1) * S.row_bytes;
    // split input (in2 != 0): columns [K/2, K) come from a second [T][K/2] array
    const uint Kx = S.in2 ? K / 2 : K, xtc = min(t0 + xt, T - 1);
    device const float * xrow = A + S.in_off + (ulong) xtc * Kx;
    device const float * xrow2 = A + S.in2 + (ulong) xtc * Kx;
    simdgroup_float8x8 mc[8];
    for (int i = 0; i < 8; i++) mc[i] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
    for (uint k0 = 0; k0 < K; k0 += GM_BK) {
        half wv[16];
        deq16(wrow, S.wtype, k0 + 16 * wh, wv);
        for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wvalid ? wv[i] : half(0);
        device const float * xs = k0 < Kx ? xrow + k0 + xk : xrow2 + (k0 - Kx) + xk;
        const float4 x0 = *(device const float4 *) xs, x1 = *(device const float4 *) (xs + 4);
        for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int kk = 0; kk < GM_BK / 8; kk++) {
            simdgroup_half8x8 ma[4], mb[2];
            for (int t = 0; t < 4; t++) simdgroup_load(ma[t], sb + t * 8 * GM_BK + kk * 8, GM_BK);
            for (int r = 0; r < 2; r++) simdgroup_load(mb[r], sa + (sg * 16 + r * 8) * GM_BK + kk * 8, GM_BK, ulong2(0, 0), true);
            for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++) simdgroup_multiply_accumulate(mc[t * 2 + r], ma[t], mb[r], mc[t * 2 + r]);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++)
        simdgroup_store(mc[t * 2 + r], sc + (t * 8) * GM_BM + sg * 16 + r * 8, GM_BM);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
        const uint t = i / GM_BM, r = i % GM_BM;
        if (t0 + t < T && r0 + r < S.nrows) A[S.out_off + (t0 + t) * S.ldo + r0 + r] = sc[i];
    }
}

// ---- MoE grouped GEMM over a tile list (expert, assignment start, count<=32).
struct MoeGemmArgs {
    uint w_lo, w_hi, expert_bytes, row_bytes;
    uint wtype, nrows, K, x_off;
    uint gather, perm_off, tiles_off, ntiles_off;
    uint out_off, ldo, situ, pad;
    float beta, lbeta; uint gs_lo, gs_hi;
};

kernel void k_moe_gemm(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmArgs & a [[buffer(5)]],
                       uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup half sa[GM_BM * GM_BK];
    threadgroup half sb[GM_BN * GM_BK];
    threadgroup float sc[GM_BN * GM_BM];
    const uint ntiles = as_type<uint>(A[a.ntiles_off]);
    if (tgp.y >= ntiles) return;
    device const uint * tl = (device const uint *) (A + a.tiles_off) + tgp.y * 4;
    const uint e = tl[0], as0 = tl[1], cnt = tl[2];
    device const uint * perm = (device const uint *) (A + a.perm_off);
    // row tile: situ -> 32 gate rows (i0..i0+31) + 32 up rows (FF+i0..); else 64 consecutive rows
    const uint wr = tid / 2, wh = tid % 2;
    uint row;
    if (a.situ) row = (wr < 32) ? tgp.x * 32 + wr : FF + tgp.x * 32 + (wr - 32);
    else row = tgp.x * GM_BM + wr;
    device const uchar * wrow = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) row * a.row_bytes;
    const uint xt = tid / 4, xk = (tid % 4) * 8;
    const bool xvalid = xt < cnt;
    const uint arow = as0 + min(xt, cnt - 1);
    const uint xsrc = a.gather ? perm[arow] : arow;
    device const float * xrow = A + a.x_off + (ulong) xsrc * a.K;
    simdgroup_float8x8 mc[8];
    for (int i = 0; i < 8; i++) mc[i] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
    for (uint k0 = 0; k0 < a.K; k0 += GM_BK) {
        half wv[16];
        deq16(wrow, a.wtype, k0 + 16 * wh, wv);
        for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wv[i];
        const float4 x0 = *(device const float4 *) (xrow + k0 + xk), x1 = *(device const float4 *) (xrow + k0 + xk + 4);
        for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int kk = 0; kk < GM_BK / 8; kk++) {
            simdgroup_half8x8 ma[4], mb[2];
            for (int t = 0; t < 4; t++) simdgroup_load(ma[t], sb + t * 8 * GM_BK + kk * 8, GM_BK);
            for (int r = 0; r < 2; r++) simdgroup_load(mb[r], sa + (sg * 16 + r * 8) * GM_BK + kk * 8, GM_BK, ulong2(0, 0), true);
            for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++) simdgroup_multiply_accumulate(mc[t * 2 + r], ma[t], mb[r], mc[t * 2 + r]);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    for (int t = 0; t < 4; t++) for (int r = 0; r < 2; r++)
        simdgroup_store(mc[t * 2 + r], sc + (t * 8) * GM_BM + sg * 16 + r * 8, GM_BM);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (a.wtype == 200) {
        const float g = gscale_at(W, a.gs_lo, a.gs_hi, e);
        for (uint i = tid; i < GM_BN * GM_BM; i += 128) sc[i] *= g;
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    if (a.situ) {
        for (uint i = tid; i < GM_BN * 32; i += 128) {
            const uint t = i / 32, r = i % 32;
            if (t < cnt) {
                const float gt = sc[t * GM_BM + r], up = sc[t * GM_BM + 32 + r];
                const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
                A[a.out_off + (as0 + t) * a.ldo + tgp.x * 32 + r] = act;
            }
        }
    } else {
        for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
            const uint t = i / GM_BM, r = i % GM_BM;
            if (t < cnt) A[a.out_off + (as0 + t) * a.ldo + tgp.x * GM_BM + r] = sc[i];
        }
    }
}

// ---- small-batch (T <= GM_DT = 8 tokens) forms of k_gemm and k_moe_gemm for the Metal 3 path. A 128-thread
// threadgroup owns a GM_RR = 32-row tile, one simdgroup per 8 rows running its MMA chain over the first 8-token
// tile, so a step of a few tokens spreads over twice as many threadgroups, does a quarter of the MMAs, and all 128
// threads stage GM_RS = 4 k-steps of 32 per stage into a two-stage ring, loading stage s + 1 while stage s's MMAs
// run. Each output still accumulates mc = ma(tokens, kk) x mb(rows, kk) + mc over k0 += 32, kk = 0..3 in order,
// from the same half weights (deq16) and half inputs, and an 8x8 MMA block does not read the other blocks of the
// tile, so the outputs are bit-identical to k_gemm / k_moe_gemm (engine test
// small_batch_metal3_gemms_match_k_gemm_and_k_moe_gemm_bit_for_bit; inky dbatch INK_DB_GEMM_DEC=1).
#define GM_DT 8
#define GM_RR 32
#define GM_RS 4
#define GM_RK (GM_RS * GM_BK)
#define GM_TPR (128 / GM_RR)
#define GM_WPT (GM_RK / GM_TPR)
#define GM_XPT (GM_RK / 16)
inline void gemm_ring_chain(threadgroup half (*sa)[GM_RR * GM_RK], threadgroup half (*sb)[GM_DT * GM_RK],
                            device const uchar * wrow, uint wtype, uint K, bool wvalid,
                            device const float * xrow, device const float * xrow2, uint Kx, bool xvalid,
                            ushort tid, ushort sg, thread simdgroup_float8x8 & mc) {
    // loads: thread tid -> GM_WPT weights of row tid / GM_TPR from k (tid % GM_TPR) * GM_WPT of the stage, and
    // GM_XPT inputs of token tid / 16 from k (tid % 16) * GM_XPT
    const uint wr = tid / GM_TPR, wk = (tid % GM_TPR) * GM_WPT, xt = tid / 16, xk = (tid % 16) * GM_XPT;
    half wv[GM_WPT / 16][16];
    float4 xv[GM_XPT / 4];
    auto load = [&](uint kb) {
        for (uint j = 0; j < GM_WPT / 16; j++)
            if (kb + wk + 16 * j < K) deq16(wrow, wtype, kb + wk + 16 * j, wv[j]);
        for (uint j = 0; j < GM_XPT / 4; j++) {
            const uint k0 = kb + xk + 4 * j;
            if (k0 < K) xv[j] = *(device const float4 *) (k0 < Kx ? xrow + k0 : xrow2 + (k0 - Kx));
        }
    };
    auto store = [&](uint s) {
        for (uint j = 0; j < GM_WPT / 16; j++)
            for (int i = 0; i < 16; i++) sa[s][wr * GM_RK + wk + 16 * j + i] = wvalid ? wv[j][i] : half(0);
        for (uint j = 0; j < GM_XPT / 4; j++)
            for (int i = 0; i < 4; i++) sb[s][xt * GM_RK + xk + 4 * j + i] = xvalid ? half(xv[j][i]) : half(0);
    };
    load(0);
    store(0);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    uint s = 0;
    const bool mine = sg < GM_RR / 8;
    for (uint kb = 0; kb < K; kb += GM_RK) {
        const bool more = kb + GM_RK < K;
        if (more) load(kb + GM_RK);
        if (mine) {
            for (uint kk = 0; kk < GM_RK / 8 && kb + kk * 8 < K; kk++) {
                simdgroup_half8x8 ma, mb;
                simdgroup_load(ma, sb[s] + kk * 8, GM_RK);
                simdgroup_load(mb, sa[s] + (sg * 8) * GM_RK + kk * 8, GM_RK, ulong2(0, 0), true);
                simdgroup_multiply_accumulate(mc, ma, mb, mc);
            }
        }
        if (more) store(s ^ 1);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        s ^= 1;
    }
}

kernel void k_gemm_dec(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                        constant GemmArgs & args [[buffer(5)]], uint2 tgp [[threadgroup_position_in_grid]],
                        ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
    threadgroup half sa[2][GM_RR * GM_RK];
    threadgroup half sb[2][GM_DT * GM_RK];
    uint si = 0;
    while (si + 1 < args.nseg && tgp.x >= args.seg[si + 1].tile_start) si++;
    constant GSeg & S = args.seg[si];
    const uint r0 = (tgp.x - S.tile_start) * GM_RR;
    const uint T = args.T, K = S.K;
    device const uchar * wb = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
    const uint wr = tid / GM_TPR, xt = tid / 16;
    device const uchar * wrow = wb + (ulong) min(r0 + wr, S.nrows - 1) * S.row_bytes;
    const uint Kx = S.in2 ? K / 2 : K, xtc = min(xt, T - 1);
    simdgroup_float8x8 mc = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
    gemm_ring_chain(sa, sb, wrow, S.wtype, K, r0 + wr < S.nrows, A + S.in_off + (ulong) xtc * Kx,
                    A + S.in2 + (ulong) xtc * Kx, Kx, xt < T, tid, sg, mc);
    threadgroup float * sc = (threadgroup float *) sa[0];
    if (sg < GM_RR / 8) simdgroup_store(mc, sc + sg * 8, GM_RR);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint i = tid; i < GM_DT * GM_RR; i += 128) {
        const uint t = i / GM_RR, r = i % GM_RR;
        if (t < T && r0 + r < S.nrows) A[S.out_off + t * S.ldo + r0 + r] = sc[i];
    }
}

// situ: GM_RR / 2 gate rows (i0..) + their GM_RR / 2 up rows (FF + i0..); else GM_RR consecutive rows.
kernel void k_moe_gemm_dec(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmArgs & a [[buffer(5)]],
                            uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                            ushort sg [[simdgroup_index_in_threadgroup]]) {
    threadgroup half sa[2][GM_RR * GM_RK];
    threadgroup half sb[2][GM_DT * GM_RK];
    const uint ntiles = as_type<uint>(A[a.ntiles_off]);
    if (tgp.y >= ntiles) return;
    device const uint * tl = (device const uint *) (A + a.tiles_off) + tgp.y * 4;
    const uint e = tl[0], as0 = tl[1], cnt = tl[2];
    device const uint * perm = (device const uint *) (A + a.perm_off);
    const uint wr = tid / GM_TPR, xt = tid / 16;
    uint row;
    if (a.situ) row = (wr < GM_RR / 2) ? tgp.x * (GM_RR / 2) + wr : FF + tgp.x * (GM_RR / 2) + (wr - GM_RR / 2);
    else row = tgp.x * GM_RR + wr;
    device const uchar * wrow = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) row * a.row_bytes;
    const uint arow = as0 + min(xt, cnt - 1);
    const uint xsrc = a.gather ? perm[arow] : arow;
    device const float * xrow = A + a.x_off + (ulong) xsrc * a.K;
    simdgroup_float8x8 mc = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
    gemm_ring_chain(sa, sb, wrow, a.wtype, a.K, true, xrow, xrow, a.K, xt < cnt, tid, sg, mc);
    threadgroup float * sc = (threadgroup float *) sa[0];
    if (sg < GM_RR / 8) simdgroup_store(mc, sc + sg * 8, GM_RR);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (a.wtype == 200) {
        const float g = gscale_at(W, a.gs_lo, a.gs_hi, e);
        for (uint i = tid; i < GM_DT * GM_RR; i += 128) sc[i] *= g;
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    if (a.situ) {
        for (uint i = tid; i < GM_DT * (GM_RR / 2); i += 128) {
            const uint t = i / (GM_RR / 2), r = i % (GM_RR / 2);
            if (t < cnt) {
                const float gt = sc[t * GM_RR + r], up = sc[t * GM_RR + GM_RR / 2 + r];
                const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
                A[a.out_off + (as0 + t) * a.ldo + tgp.x * (GM_RR / 2) + r] = act;
            }
        }
    } else {
        for (uint i = tid; i < GM_DT * GM_RR; i += 128) {
            const uint t = i / GM_RR, r = i % GM_RR;
            if (t < cnt) A[a.out_off + (as0 + t) * a.ldo + tgp.x * GM_RR + r] = sc[i];
        }
    }
}

// ---- top-k per token (grid T, 32 threads) -> sel[t][16] = ids (as float) + weights
struct TopkBArgs { uint logits_off, bias_off, sel_off, T; float wscale; uint pad0, pad1, pad2; };
kernel void k_topk_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant TopkBArgs & a [[buffer(5)]],
                     uint t [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) {
    topk_sg(A, PB, a.logits_off + t * NEXP, a.bias_off, a.sel_off + t * 2 * TOPK, a.wscale, lane);
}

// ---- routing: counting sort of (token, slot) assignments by expert + 32-row tile list. 1 TG x 1024 threads.
struct RouteArgs { uint sel_off, T, perm_off, inv_off, tiles_off, ntiles_off, tile, pad1; };
kernel void k_moe_route(device float * A [[buffer(2)]], constant RouteArgs & a [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup atomic_uint cnt[NEXP];
    threadgroup uint off[NEXP], toff[NEXP];
    threadgroup atomic_uint fill[NEXP];
    if (tid < NEXP) { atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed); atomic_store_explicit(&fill[tid], 0, memory_order_relaxed); }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const uint n = a.T * TOPK;
    for (uint i = tid; i < n; i += 1024) {
        const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
        atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        uint s = 0, ts = 0;
        for (int e = 0; e < NEXP; e++) {
            const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed);
            off[e] = s; toff[e] = ts; s += c; ts += (c + a.tile - 1) / a.tile;
        }
        A[a.ntiles_off] = as_type<float>(ts);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device uint * perm = (device uint *) (A + a.perm_off);
    device uint * inv = (device uint *) (A + a.inv_off);
    device uint * tiles = (device uint *) (A + a.tiles_off);
    for (uint i = tid; i < n; i += 1024) {
        const uint t = i / TOPK, k = i % TOPK;
        const uint e = (uint) A[a.sel_off + t * 16 + k];
        const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
        perm[slot] = t;
        inv[i] = slot;
    }
    if (tid < NEXP) {
        const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed);
        for (uint j = 0; j < (c + a.tile - 1) / a.tile; j++) {
            device uint * tt = tiles + (toff[tid] + j) * 4;
            tt[0] = tid; tt[1] = off[tid] + j * a.tile; tt[2] = min(a.tile, c - j * a.tile); tt[3] = 0;
        }
    }
}

struct MoeCombArgs { uint yd_off, inv_off, sel_off, out_off; };
// ---- routing for the fp16 path: counting sort of (token, slot) assignments by expert, per-assignment routing weights,
// and tile lists in two classes: class 0 = 8-simdgroup tiles (65..128 tokens), class 1 = 4-simdgroup tiles (1..64 tokens).
// An expert with c tokens gets c/128 full tiles and one tile for the remainder (simdgroups without tokens idle in the kernel).
// Also writes the indirect dispatch sizes (tiles, column blocks, 1) for gate/up and down per class. 1 TG x 1024 threads.
#define NTC 2
struct Route3Args { uint sel_off, T, perm_off, inv_off, aw_off, ind_off, gu_y, dn_y; uint tiles_off[NTC]; uint pad0, pad1; };
kernel void k_moe_route3(device float * A [[buffer(2)]], constant Route3Args & a [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup atomic_uint cnt[NEXP];
    threadgroup uint off[NEXP], toff[NTC][NEXP];
    threadgroup atomic_uint fill[NEXP];
    if (tid < NEXP) { atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed); atomic_store_explicit(&fill[tid], 0, memory_order_relaxed); }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const uint n = a.T * TOPK;
    for (uint i = tid; i < n; i += 1024) {
        const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
        atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        uint s = 0, ts[NTC] = {0, 0};
        for (int e = 0; e < NEXP; e++) {
            const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed), r = c % 128;
            off[e] = s; s += c;
            toff[0][e] = ts[0]; toff[1][e] = ts[1];
            ts[0] += c / 128 + (r > 64 ? 1 : 0);
            ts[1] += (r > 0 && r <= 64) ? 1 : 0;
        }
        device uint * ind = (device uint *) (A + a.ind_off);
        for (int c = 0; c < NTC; c++) {
            ind[c * 4 + 0] = ts[c]; ind[c * 4 + 1] = a.gu_y; ind[c * 4 + 2] = 1; ind[c * 4 + 3] = ts[c];
            ind[4 * NTC + c * 4 + 0] = ts[c]; ind[4 * NTC + c * 4 + 1] = a.dn_y; ind[4 * NTC + c * 4 + 2] = 1; ind[4 * NTC + c * 4 + 3] = ts[c];
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device uint * perm = (device uint *) (A + a.perm_off);
    device uint * inv = (device uint *) (A + a.inv_off);
    for (uint i = tid; i < n; i += 1024) {
        const uint t = i / TOPK, k = i % TOPK;
        const uint e = (uint) A[a.sel_off + t * 16 + k];
        const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
        perm[slot] = t;
        inv[i] = slot;
        A[a.aw_off + slot] = A[a.sel_off + t * 16 + TOPK + k];
    }
    if (tid < NEXP) {
        const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed), n128 = c / 128, r = c % 128;
        device uint * t8 = (device uint *) (A + a.tiles_off[0]) + toff[0][tid] * 4;
        for (uint j = 0; j < n128; j++) { t8[j * 4] = tid; t8[j * 4 + 1] = off[tid] + j * 128; t8[j * 4 + 2] = 128; t8[j * 4 + 3] = 0; }
        if (r > 0) {
            device uint * tt = r > 64 ? t8 + n128 * 4 : (device uint *) (A + a.tiles_off[1]) + toff[1][tid] * 4;
            tt[0] = tid; tt[1] = off[tid] + n128 * 128; tt[2] = r; tt[3] = 0;
        }
    }
}

// ---- fused top-k + routing for n <= 64 (fp16 path): 1 TG x 1024 threads (32 simdgroups).
// Simdgroups execute the exact `topk_sg` arithmetic of `k_topk_b` across rows [0, T), writing `sel`,
// then synchronize via a device+threadgroup barrier before executing the exact body of `k_moe_route3`.
struct TopkRoute3Args {
    uint logits_off, bias_off, sel_off, T;
    float wscale; uint perm_off, inv_off, aw_off;
    uint ind_off, gu_y, dn_y; uint tiles_off[NTC];
    uint pad0, pad1, pad2;
};
kernel void k_moe_topk_route3(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                              constant TopkRoute3Args & a [[buffer(5)]],
                              ushort tid [[thread_index_in_threadgroup]],
                              ushort sg [[simdgroup_index_in_threadgroup]],
                              ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup atomic_uint cnt[NEXP];
    threadgroup uint off[NEXP], toff[NTC][NEXP];
    threadgroup atomic_uint fill[NEXP];
    if (tid < NEXP) {
        atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed);
        atomic_store_explicit(&fill[tid], 0, memory_order_relaxed);
    }
    for (uint row = sg; row < a.T; row += 32) {
        topk_sg(A, PB, a.logits_off + row * NEXP, a.bias_off, a.sel_off + row * 2 * TOPK, a.wscale, lane);
    }
    threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);
    const uint n = a.T * TOPK;
    for (uint i = tid; i < n; i += 1024) {
        const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
        atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        uint s = 0, ts[NTC] = {0, 0};
        for (int e = 0; e < NEXP; e++) {
            const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed), r = c % 128;
            off[e] = s; s += c;
            toff[0][e] = ts[0]; toff[1][e] = ts[1];
            ts[0] += c / 128 + (r > 64 ? 1 : 0);
            ts[1] += (r > 0 && r <= 64) ? 1 : 0;
        }
        device uint * ind = (device uint *) (A + a.ind_off);
        for (int c = 0; c < NTC; c++) {
            ind[c * 4 + 0] = ts[c]; ind[c * 4 + 1] = a.gu_y; ind[c * 4 + 2] = 1; ind[c * 4 + 3] = ts[c];
            ind[4 * NTC + c * 4 + 0] = ts[c]; ind[4 * NTC + c * 4 + 1] = a.dn_y; ind[4 * NTC + c * 4 + 2] = 1; ind[4 * NTC + c * 4 + 3] = ts[c];
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device uint * perm = (device uint *) (A + a.perm_off);
    device uint * inv = (device uint *) (A + a.inv_off);
    for (uint i = tid; i < n; i += 1024) {
        const uint t = i / TOPK, k = i % TOPK;
        const uint e = (uint) A[a.sel_off + t * 16 + k];
        const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
        perm[slot] = t;
        inv[i] = slot;
        A[a.aw_off + slot] = A[a.sel_off + t * 16 + TOPK + k];
    }
    if (tid < NEXP) {
        const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed), n128 = c / 128, r = c % 128;
        device uint * t8 = (device uint *) (A + a.tiles_off[0]) + toff[0][tid] * 4;
        for (uint j = 0; j < n128; j++) { t8[j * 4] = tid; t8[j * 4 + 1] = off[tid] + j * 128; t8[j * 4 + 2] = 128; t8[j * 4 + 3] = 0; }
        if (r > 0) {
            device uint * tt = r > 64 ? t8 + n128 * 4 : (device uint *) (A + a.tiles_off[1]) + toff[1][tid] * 4;
            tt[0] = tid; tt[1] = off[tid] + n128 * 128; tt[2] = r; tt[3] = 0;
        }
    }
}

// ---- fused top-k + expert grouping for decode-size batches (T <= 128):
// Groups active (row, slot) assignments by expert_id into two width classes:
//   class 0: 65..128 tokens -> k_moe_dec_sg8 (256 threads, 8 simdgroups)
//   class 1:  1..64  tokens -> k_moe_dec_sg4 (128 threads, 4 simdgroups)
// Indirect dispatch grids are (ts[c], gu_y, 1) and (ts[c], dn_y, 1): Metal sweeps tgq.y fastest, so all 36 column
// blocks of ~2 active experts run together while their gathered activations and page-table entries stay in SLC/TLB.
// When a.no_grp != 0 (INK_NO_GRP_MOE=1), emits one cnt=1 tile per (row, slot) assignment in class 1 (0-bit-diff
// ungrouped reference).
#define NTC_DEC 2
struct TopkRouteDecArgs {
    uint logits_off, bias_off, sel_off, T;
    float wscale; uint perm_off, inv_off, aw_off;
    uint ind_off, gu_y, dn_y, no_grp;
    uint tiles_off[NTC_DEC];
    uint gu_y1, dn_y1;      // class 1's column threadgroups (gu_y, dn_y over the register-fed kernel's blocks per threadgroup)
};
kernel void k_moe_topk_route_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                                 constant TopkRouteDecArgs & a [[buffer(5)]],
                                 ushort tid [[thread_index_in_threadgroup]],
                                 ushort sg [[simdgroup_index_in_threadgroup]],
                                 ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup atomic_uint cnt[NEXP];
    threadgroup uint off[NEXP], toff[NTC_DEC][NEXP];
    threadgroup atomic_uint fill[NEXP];
    if (tid < NEXP) {
        atomic_store_explicit(&cnt[tid], 0, memory_order_relaxed);
        atomic_store_explicit(&fill[tid], 0, memory_order_relaxed);
    }
    for (uint row = sg; row < a.T; row += 32) {
        topk_sg(A, PB, a.logits_off + row * NEXP, a.bias_off, a.sel_off + row * 2 * TOPK, a.wscale, lane);
    }
    threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);
    const uint n = a.T * TOPK;
    device uint * perm = (device uint *) (A + a.perm_off);
    device uint * inv = (device uint *) (A + a.inv_off);
    if (a.no_grp != 0) {
        for (uint i = tid; i < n; i += 1024) {
            const uint t = i / TOPK, k = i % TOPK;
            const uint e = (uint) A[a.sel_off + t * 16 + k];
            perm[i] = t;
            inv[i] = i;
            A[a.aw_off + i] = A[a.sel_off + t * 16 + TOPK + k];
            device uint * tt = (device uint *) (A + a.tiles_off[1]) + i * 4;
            tt[0] = e; tt[1] = i; tt[2] = 1; tt[3] = 0;
        }
        if (tid == 0) {
            device uint * ind = (device uint *) (A + a.ind_off);
            ind[0] = 0;                 ind[1] = 0; ind[2] = 1; ind[3] = 0;
            ind[4] = n ? a.gu_y1 : 0;   ind[5] = n; ind[6] = 1; ind[7] = n;
            ind[8] = 0;                 ind[9] = 0; ind[10] = 1; ind[11] = 0;
            ind[12] = n ? a.dn_y1 : 0;  ind[13] = n; ind[14] = 1; ind[15] = n;
        }
        return;
    }
    for (uint i = tid; i < n; i += 1024) {
        const uint e = (uint) A[a.sel_off + (i / TOPK) * 16 + (i % TOPK)];
        atomic_fetch_add_explicit(&cnt[e], 1, memory_order_relaxed);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) {
        uint s = 0, ts[NTC_DEC] = {0, 0};
        for (int e = 0; e < NEXP; e++) {
            const uint c = atomic_load_explicit(&cnt[e], memory_order_relaxed), r = c % 128;
            off[e] = s; s += c;
            toff[0][e] = ts[0]; toff[1][e] = ts[1];
            ts[0] += c / 128 + (r > 64 ? 1 : 0);
            ts[1] += (r > 0 && r <= 64) ? 1 : 0;
        }
        device uint * ind = (device uint *) (A + a.ind_off);
        for (int c = 0; c < NTC_DEC; c++) {
            ind[c * 4 + 0] = ts[c] ? (c ? a.gu_y1 : a.gu_y) : 0; ind[c * 4 + 1] = ts[c]; ind[c * 4 + 2] = 1; ind[c * 4 + 3] = ts[c];
            ind[4 * NTC_DEC + c * 4 + 0] = ts[c] ? (c ? a.dn_y1 : a.dn_y) : 0; ind[4 * NTC_DEC + c * 4 + 1] = ts[c]; ind[4 * NTC_DEC + c * 4 + 2] = 1; ind[4 * NTC_DEC + c * 4 + 3] = ts[c];
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint i = tid; i < n; i += 1024) {
        const uint t = i / TOPK, k = i % TOPK;
        const uint e = (uint) A[a.sel_off + t * 16 + k];
        const uint slot = off[e] + atomic_fetch_add_explicit(&fill[e], 1, memory_order_relaxed);
        perm[slot] = t;
        inv[i] = slot;
        A[a.aw_off + slot] = A[a.sel_off + t * 16 + TOPK + k];
    }
    if (tid < NEXP) {
        const uint c = atomic_load_explicit(&cnt[tid], memory_order_relaxed), n128 = c / 128, r = c % 128;
        device uint * t8 = (device uint *) (A + a.tiles_off[0]) + toff[0][tid] * 4;
        for (uint j = 0; j < n128; j++) { t8[j * 4] = tid; t8[j * 4 + 1] = off[tid] + j * 128; t8[j * 4 + 2] = 128; t8[j * 4 + 3] = 0; }
        if (r > 0) {
            device uint * tt = r > 64 ? t8 + n128 * 4 : (device uint *) (A + a.tiles_off[1]) + toff[1][tid] * 4;
            tt[0] = tid; tt[1] = off[tid] + n128 * 128; tt[2] = r; tt[3] = 0;
        }
    }
}

// ---- expert sum per token for the fp16 path (routing weights are already folded into the activations):
// y[t][c] = sum_k ydh[inv[t*8+k]][c], ydh half. grid (T, ceil(E/1024)), 256 threads x 4 columns
kernel void k_moe_comb_h(device float * A [[buffer(2)]], constant MoeCombArgs & a [[buffer(5)]],
                         uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint t = tgp.x, c = (tgp.y * 256 + tid) * 4;
    if (c >= E) return;
    device const uint * inv = (device const uint *) (A + a.inv_off) + t * TOPK;
    device const half * yd = (device const half *) (A + a.yd_off);
    float4 y = 0;
    for (int k = 0; k < TOPK; k++) y += float4(*(device const half4 *) (yd + (ulong) inv[k] * E + c));
    *(device float4 *) (A + a.out_off + t * E + c) = y;
}

// ---- weighted expert sum per token: y[t][c] = sum_k w[t][k] * yd[inv[t*8+k]][c]. grid (E/256, T), 256 threads
kernel void k_moe_comb_b(device float * A [[buffer(2)]], constant MoeCombArgs & a [[buffer(5)]],
                         uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint t = tgp.y, c = tgp.x * 256 + tid;
    device const uint * inv = (device const uint *) (A + a.inv_off);
    float y = 0;
    for (int k = 0; k < TOPK; k++) y += A[a.sel_off + t * 16 + TOPK + k] * A[a.yd_off + inv[t * TOPK + k] * E + c];
    A[a.out_off + t * E + c] = y;
}

// ---- causal short conv over a token sequence with state history, + optional residual. grid (nch/256, T)
// out[t][c] = res[t][c] + (y_t + w0*y_{t-3} + w1*y_{t-2} + w2*y_{t-1} + w3*y_t) / sqrt(5)
struct ConvBArgs { uint y_off, ldy, res_off, out_off, cs_off, convw_off, has_res, pad; };
kernel void k_postconv_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device float * CS [[buffer(4)]],
                         constant ConvBArgs & a [[buffer(5)]], uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint t = tgp.y, c = tgp.x * 256 + tid;
    device const float * h = CS + a.cs_off + c * 3;
    device const float * w = (device const float *) (PB + a.convw_off) + c * 4;
    float x[4];
    for (int j = 0; j < 4; j++) {   // x[j] = y_{t-3+j}
        const int tt = int(t) - 3 + j;
        x[j] = tt >= 0 ? A[a.y_off + tt * a.ldy + c] : h[3 + tt];
    }
    const float o = (x[3] + w[0] * x[0] + w[1] * x[1] + w[2] * x[2] + w[3] * x[3]) * 0.4472135954999579f;
    A[a.out_off + t * E + c] = (a.has_res ? A[a.res_off + t * E + c] : 0.0f) + o;
}

// ---- conv-state update after a chunk: state <- last 3 raw inputs. grid (nch/256), 256 threads
struct StateArgs { uint x_off, ldx, cs_off, nch, T, pad0, pad1, pad2; };
kernel void k_state_upd(device float * A [[buffer(2)]], device float * CS [[buffer(4)]], constant StateArgs & a [[buffer(5)]],
                        uint tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint c = tg * 256 + tid;
    if (c >= a.nch) return;
    device float * h = CS + a.cs_off + c * 3;
    float v[3];
    for (int j = 0; j < 3; j++) {   // new h[j] = seq[T + j] where seq = [h0 h1 h2 x0 .. x_{T-1}]
        const int s = int(a.T) + j;
        v[j] = s >= 3 ? A[a.x_off + (s - 3) * a.ldx + c] : h[s];
    }
    h[0] = v[0]; h[1] = v[1]; h[2] = v[2];
}

// ---- fused decode post-conv + conv-state update across all lanes in a decode batch.
// grid (E/256, nspans, 1), 256 threads. Bit-identical to `k_postconv_b` (T=1) followed by `k_state_upd` (T=1).
// When `no_state_write != 0`, computes `A[out_off + ...]` identically without modifying `CS` (LoopCD dry weak pass).
struct PostConvDecArgs { uint desc_off, y_off, res_off, out_off, cs_slot_off, convw_off, has_res, no_state_write; };
kernel void k_postconv_state_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device float * CS [[buffer(4)]],
                                 constant PostConvDecArgs & a [[buffer(5)]],
                                 uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint c = tgp.x * 256 + tid, si = tgp.y;
    device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
    device float * h = CS + d.cs_base + a.cs_slot_off + c * 3;
    device const float * w = (device const float *) (PB + a.convw_off) + c * 4;
    const float h0 = h[0], h1 = h[1], h2 = h[2];
    const float y = A[a.y_off + si * E + c];
    const float o = (y + w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y) * 0.4472135954999579f;
    A[a.out_off + si * E + c] = (a.has_res ? A[a.res_off + si * E + c] : 0.0f) + o;
    if (a.no_state_write == 0u) { h[0] = h1; h[1] = h2; h[2] = y; }
}

// ---- per-position conv state inside a span. Same rule as k_state_upd, for every prefix length m = lo..T (lo = max(m_lo, 1)),
// written into a side image that has cs's layout. Does not write CS. There is no second forward. A verify span keeps every
// prefix (m_lo 0 or 1); a prefill span that runs through a start-point checkpoint keeps the one prefix ending there (m_lo = T).
struct StateKeepArgs { uint x_off, ldx, cs_off, nch, T, snap_off, stride, m_lo; };
kernel void k_state_keep(device float * A [[buffer(2)]], device const float * CS [[buffer(4)]], device float * SNAP [[buffer(9)]],
                         constant StateKeepArgs & a [[buffer(5)]],
                         uint tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint c = tg * 256 + tid;
    if (c >= a.nch) return;
    device const float * h = CS + a.cs_off + c * 3;
    const uint lo = max(a.m_lo, 1u);
    for (uint m = lo; m <= a.T; m++) {
        device float * o = SNAP + a.snap_off + (m - lo) * a.stride + a.cs_off + c * 3;
        for (int j = 0; j < 3; j++) {
            const int s = int(m) + j;
            o[j] = s >= 3 ? A[a.x_off + (s - 3) * a.ldx + c] : h[s];
        }
    }
}

// ---- K/V row copies between a sliding-window ring (KV, cap keys per group) and the linear prefill scratch (in the arena A).
// The persistent cache of a sliding-window layer holds exactly its window; a prefill batch attends through a scratch copy
// [window history | batch keys] and afterwards leaves the last window of keys in the ring. grid (n, NKV), 32 threads.
struct KvCopyArgs { uint n, pos0, ring_k, ring_v, cap, sk_off, sv_off, scap; int kpos0; uint to_ring, pad0, pad1; };
// Zero words [r.x, r.x + r.y) of the arena: 4 per thread. The batch's sliding-window K/V scratch is cleared this way at the
// start of every prefill, because attention reads its guard rows and unfilled history (masked with a zero weight) through
// the tensor multiply, and a zero weight does not cancel a NaN: those rows must hold finite values whatever was there.
kernel void k_zero(device uint * A [[buffer(2)]], constant uint2 & r [[buffer(5)]], uint tg [[threadgroup_position_in_grid]],
                   uint tid [[thread_index_in_threadgroup]]) {
    const uint i = (tg * 256 + tid) * 4;
    for (uint j = 0; j < 4; j++) { if (i + j < r.y) A[r.x + i + j] = 0; }
}

kernel void k_kvcopy(device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]], constant KvCopyArgs & a [[buffer(5)]],
                     uint2 tgp [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) {
#ifdef KV4
    const uint pos = a.pos0 + tgp.x, g = tgp.y;
    const uint ri = g * a.cap + pos % a.cap, si = g * a.scap + (uint) ((int) pos - a.kpos0);
    device ushort * rk = (device ushort *) (KV + a.ring_k + ri), * rv = (device ushort *) (KV + a.ring_v + ri);
    device ushort * sk = (device ushort *) ((device kv_t *) (A + a.sk_off) + si), * sv = (device ushort *) ((device kv_t *) (A + a.sv_off) + si);
    if (a.to_ring == 2) {
        sk[lane] = 0; sv[lane] = 0;
        if (lane == 0) { sk[32] = 0; sv[32] = 0; }
    } else if (a.to_ring) {
        rk[lane] = sk[lane]; rv[lane] = sv[lane];
        if (lane == 0) { rk[32] = sk[32]; rv[32] = sv[32]; }
    } else {
        sk[lane] = rk[lane]; sv[lane] = rv[lane];
        if (lane == 0) { sk[32] = rk[32]; sv[32] = rv[32]; }
    }
#else
    const uint pos = a.pos0 + tgp.x, g = tgp.y;
    const uint ri = (g * a.cap + pos % a.cap) * HD + lane * 4, si = (g * a.scap + (uint) ((int) pos - a.kpos0)) * HD + lane * 4;
    device kvw_t * rk = (device kvw_t *) (KV + a.ring_k + ri), * rv = (device kvw_t *) (KV + a.ring_v + ri);
    device kvw_t * sk = (device kvw_t *) ((device kv_t *) (A + a.sk_off) + si), * sv = (device kvw_t *) ((device kv_t *) (A + a.sv_off) + si);
    if (a.to_ring == 2) { *sk = kvw_t(0); *sv = kvw_t(0); }       // zero scratch rows (the ring is not touched)
    else if (a.to_ring) { *rk = *sk; *rv = *sv; } else { *sk = *rk; *sv = *rv; }
#endif
}

// dev: copy 32-bit words from the arena to a side buffer
struct DevCopyArgs { uint src, dst, n, pad; };
kernel void k_devcopy(device const uint * A [[buffer(2)]], device uint * D [[buffer(3)]], constant DevCopyArgs & a [[buffer(5)]],
                      uint gid [[thread_position_in_grid]]) {
    if (gid < a.n) D[a.dst + gid] = A[a.src + gid];
}

// ---- row-range copies inside the arena for the multi-span last-layer tail trim: per span, `rows` rows of `words`
// 32-bit words from row `src_row` (row stride `src_stride` words) to row `dst_row` (stride `dst_stride`). A gather moves
// each span's tail rows to the compact rows the trimmed layer works on; a scatter moves them back. A plain word copy
// (no float arithmetic), so it is bit-exact for f32 and half rows alike. grid (words/256, max rows, spans), 256 threads.
struct RowCopySpan { uint src_row, dst_row, rows, pad; };
struct RowCopyArgs { uint src_off, dst_off, words, src_stride, dst_stride, nspan, pad0, pad1; RowCopySpan sp[128]; };
kernel void k_rowcopy(device uint * A [[buffer(2)]], constant RowCopyArgs & a [[buffer(5)]],
                      uint3 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint c = tgp.x * 256 + tid, r = tgp.y;
    const RowCopySpan s = a.sp[tgp.z];
    if (c >= a.words || r >= s.rows) return;
    A[a.dst_off + (ulong) (s.dst_row + r) * a.dst_stride + c] = A[a.src_off + (ulong) (s.src_row + r) * a.src_stride + c];
}

// ---- per-token K/V conv + clip/norm + cache write, Q and R preparation. grid (T, NKV), 128 threads.
struct KvPrepArgs {
    uint T, p0, ring, cap, k_base, v_base, cs_off, q_off;
    uint k_off, v_off, r_off; int kdyn_off, vdyn_off; uint qp_off, rp_off, qhalf;
    uint kconv_w, vconv_w, qclip_w, relclip_w; float log_alpha, log_floor; uint is_full; int kpos0;   // kpos0: position of K/V index 0
    uint sink_off, slot_idx, pad0, pad1;
};
#pragma clang fp contract(off) reassociate(off)
kernel void k_kvprep_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
                       device float * CS [[buffer(4)]], constant KvPrepArgs & a [[buffer(5)]],
                       uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup float red[4][8];
    const uint t = tgp.x, g = tgp.y, pos = a.p0 + t;
    const float tau = a.is_full ? 1.0f + a.log_alpha * log(max(1.0f, float(pos + 1) / a.log_floor)) : 1.0f;
    device const float * qclip = (device const float *) (PB + a.qclip_w);
    float q[3];
    for (int h = 0; h < 3; h++) {
        const uint H = g * 3 + h, qi = t * (NH * HD) + H * HD + tid;
        q[h] = ((a.qhalf & 2) ? float(((device const half *) (A + a.q_off))[qi]) : A[a.q_off + qi]) * qclip[H * HD + tid];
    }
    const uint c = g * HD + tid;
    float kv[2];
    const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
    for (int which = 0; which < 2; which++) {
        const uint xo = which == 0 ? a.k_off : a.v_off;
        device const float * hh = CS + a.cs_off + (which * NKV * HD + c) * 3;
        device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
        float x[4];
        for (int j = 0; j < 4; j++) { const int tt = int(t) - 3 + j; x[j] = tt >= 0 ? A[xo + tt * (NKV * HD) + c] : hh[3 + tt]; }
        float acc = w[0] * x[0] + w[1] * x[1] + w[2] * x[2] + w[3] * x[3];
        const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
        if (dyn >= 0) { device const float * tp = A + dyn + t * 32 + g * 4; acc += tp[0] * x[3] + tp[1] * x[2] + tp[2] * x[1] + tp[3] * x[0]; }
        kv[which] = (x[3] + acc) * scl;
    }
    float r = 0;
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        r = A[a.r_off + t * (NH * NREL) + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
    }
    float rn = r * r;
    rn += simd_shuffle_xor(rn, 1); rn += simd_shuffle_xor(rn, 2); rn += simd_shuffle_xor(rn, 4); rn += simd_shuffle_xor(rn, 8);
    {
        const float s0 = simd_sum(q[0] * q[0]), s1 = simd_sum(q[1] * q[1]), s2 = simd_sum(q[2] * q[2]);
        const float s3 = simd_sum(kv[0] * kv[0]), s4 = simd_sum(kv[1] * kv[1]);
        const float s5 = simd_max(fabs(kv[0])), s6 = simd_max(fabs(kv[1]));
        if (lane == 0) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; red[sg][5] = s5; red[sg][6] = s6; }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    float tot[5];
    for (int i = 0; i < 5; i++) tot[i] = red[0][i] + red[1][i] + red[2][i] + red[3][i];
#ifdef KV4
    threadgroup float wht_sh[128];
    const uint slot = a.slot_idx;
    const float sk_rad = kv4_rademacher(slot * 2u, g, tid);
    const float sv_rad = kv4_rademacher(slot * 2u + 1u, g, tid);
    const float mu_r = kv4_finite_or_zero(float(((device const half *) (PB + KV4_DC_OFF))[(slot * NKV + g) * HD + tid]));
    for (int h = 0; h < 3; h++) {
        const uint H = g * 3 + h;
        const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
        const float qr = wht128_tg(sk_rad * (q[h] * f), tid, sg, lane, wht_sh);
        const float qstored = (a.qhalf & 1) ? float(half(qr)) : qr;
        if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + H * HD + tid] = half(qr);
        else A[a.qp_off + t * (NH * HD) + H * HD + tid] = qr;
        const float dc_b = kv4_finite_or_zero(kv4_reduce128(qstored * mu_r, sg, lane, wht_sh));
        if (tid == 0) A[a.sink_off + t * NH + H] -= dc_b;
    }
#else
    for (int h = 0; h < 3; h++) {
        const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
        if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + (g * 3 + h) * HD + tid] = half(q[h] * f);
        else A[a.qp_off + t * (NH * HD) + (g * 3 + h) * HD + tid] = q[h] * f;
    }
#endif
    if (tid < 48) A[a.rp_off + t * (NH * NREL) + (g * 3 + tid / 16) * NREL + tid % 16] = r * clamp(REL_CLIP / (sqrt(rn) + 1e-6f), 0.0f, 1.0f) * tau;
    const float kf = clamp(QK_CLIP / (sqrt(tot[3]) + 1e-6f), 0.0f, 1.0f), vf = rsqrt(tot[4] / HD + 1e-6f);
    const float k = kv[0] * kf, v = kv[1] * vf;
    const uint idx = a.ring ? (pos % a.cap) : (uint) ((int) pos - a.kpos0);
#ifdef KV4
    const float k_rot = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
    const float v_rot = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
    (void) kv4_pack_row(k_rot, tid, sg, lane, wht_sh, KV + a.k_base + (g * a.cap + idx), true);
    (void) kv4_pack_row(v_rot, tid, sg, lane, wht_sh, KV + a.v_base + (g * a.cap + idx), true);
#elif defined(KV8)
    const uint ck = kv_code(max(max(red[0][5], red[1][5]), max(red[2][5], red[3][5])) * kf);
    const uint cv = kv_code(max(max(red[0][6], red[1][6]), max(red[2][6], red[3][6])) * vf);
    KV[a.k_base + (g * a.cap + idx) * HD + tid] = (kv_t) (int) kv_quant(k, kv_scale(ck), ck, tid);
    KV[a.v_base + (g * a.cap + idx) * HD + tid] = (kv_t) (int) kv_quant(v, kv_scale(cv), cv, tid);
#else
    KV[a.k_base + (g * a.cap + idx) * HD + tid] = half(k);
    KV[a.v_base + (g * a.cap + idx) * HD + tid] = half(v);
#endif
}
#pragma clang fp contract(fast) reassociate(on)

// ---- batched causal attention: TG = (8-token query tile, kv group g) -> 24 query rows. 128 threads.
// keys are read from the KV cache (chunk keys already written). sink = zero logit (init m=0, l=1).
#define AQT 8
struct AttnBArgs {
    uint T, p0, ring, cap, k_base, v_base, window, qp_off;
    uint rp_off, sink_off, gate_off, out_off, relbias_w, ghalf; int kpos0; uint pad2;   // ghalf: half gate array; kpos0: position of K/V index 0
};
kernel void k_attn_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
                     constant AttnBArgs & a [[buffer(5)]],
                     uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup half qs[AQT * 3][HD];
    threadgroup half ks[32][HD];
    threadgroup half vs[32][HD];
    threadgroup float ss[AQT * 3][33];
    threadgroup float rs[AQT * 3][NREL];
    threadgroup float sk[AQT * 3];
    const uint g = tgp.y, t0 = tgp.x * AQT;
    const uint nq = min((uint) AQT, a.T - t0);
    for (uint i = tid; i < AQT * 3 * HD; i += 128) {
        const uint row = i / HD, d = i % HD, tt = row / 3, h = row % 3;
        qs[row][d] = tt < nq ? half(A[a.qp_off + (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + d]) : half(0);
    }
    if (tid < AQT * 3 * 4) {
        const uint row = tid / 4, part = tid % 4, tt = row / 3, h = row % 3;
        for (int i = 0; i < 4; i++) rs[row][part * 4 + i] = tt < nq ? A[a.rp_off + (t0 + tt) * (NH * NREL) + (g * 3 + h) * NREL + part * 4 + i] : 0.0f;
    }
    if (tid < AQT * 3) { const uint tt = tid / 3, h = tid % 3; sk[tid] = tt < nq ? A[a.sink_off + (t0 + tt) * NH + g * 3 + h] : 0.0f; }
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint plast = a.p0 + t0 + nq - 1;
    const uint pfirst = a.p0 + t0;
    const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
    const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
    const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) & ~31u) : 0u;
    // Align `kstart` down to a cache-fixed 32-key tile boundary so online-softmax reduction tiles
    // `[32*b, 32*b + 32)` are independent of how prefill chunks were split (`a.p0`).
    const uint kstart = ((a.window > 0 && pfirst + 1 > a.window) ? (pfirst + 1 - a.window) : 0u) & ~31u;
    float o[AQT * 3];
    for (int r = 0; r < AQT * 3; r++) o[r] = 0;
    // running stats in registers of every thread (identical copies)
    float m[AQT * 3], l[AQT * 3];
    for (int r = 0; r < AQT * 3; r++) { m[r] = 0.0f; l[r] = 1.0f; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 32u && recent_kstart > 64u) ? recent_kstart : (kc + 32u)) {
        const uint nk = min(32u, plast + 1 - kc);
        for (uint i = tid; i < 32 * HD / 4; i += 128) {
            const uint j = i / (HD / 4), d4 = i % (HD / 4);
            const uint p = kc + min(j, nk - 1);
            const uint idx = (uint) ((int) p - a.kpos0);
#ifdef KV4
            device const kv4_row * krow = KV + a.k_base + (g * a.cap + idx), * vrow = KV + a.v_base + (g * a.cap + idx);
            ((threadgroup half4 *) ks[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) krow->qs)[d4]) * float(krow->sc));
            ((threadgroup half4 *) vs[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) vrow->qs)[d4]) * float(vrow->sc));
#elif defined(KV8)
            device const kv_t * krow = KV + a.k_base + (g * a.cap + idx) * HD, * vrow = KV + a.v_base + (g * a.cap + idx) * HD;
            ((threadgroup half4 *) ks[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (krow + d4 * 4))) * kv_vscale(krow));
            ((threadgroup half4 *) vs[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (vrow + d4 * 4))) * kv_vscale(vrow));
#else
            ((threadgroup half4 *) ks[j])[d4] = *(device const half4 *) (KV + a.k_base + (g * a.cap + idx) * HD + d4 * 4);
            ((threadgroup half4 *) vs[j])[d4] = *(device const half4 *) (KV + a.v_base + (g * a.cap + idx) * HD + d4 * 4);
#endif
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        // scores: 24 rows x 32 keys = 768 -> 6 per thread
        for (uint i = tid; i < AQT * 3 * 32; i += 128) {
            const uint row = i / 32, j = i % 32, tt = row / 3;
            const uint qp = a.p0 + t0 + tt, kp = kc + j;
            float s = -INFINITY;
            if (j < nk && tt < nq && kp <= qp && (a.window == 0 || qp - kp < a.window) && (!pruned || kp < 64u || qp - kp < recent_win)) {
                float acc = 0;
                for (int d4 = 0; d4 < HD / 4; d4++)
                    acc += dot(float4(((threadgroup const half4 *) qs[row])[d4]), float4(((threadgroup const half4 *) ks[j])[d4]));
                const uint dist = qp - kp;
                if (dist < EXT) for (int r = 0; r < NREL; r++) acc += rs[row][r] * relb[dist * NREL + r];
                s = acc - sk[row];
            }
            ss[row][j] = s;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        // online softmax: bound each query row `r` to its own causal prefix `jend = min(32, qp - kc + 1)`
        // and skip tiles completely outside `[qp + 1 - window, qp]` so every split executes identical FP steps.
        for (int r = 0; r < AQT * 3; r++) {
            const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
            const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
            if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
            float mx = m[r];
            for (uint j = 0; j < jend; j++) mx = max(mx, ss[r][j]);
            const float f = exp(m[r] - mx);
            l[r] *= f; o[r] *= f; m[r] = mx;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (uint i = tid; i < AQT * 3 * 32; i += 128) { const uint row = i / 32, j = i % 32; ss[row][j] = j < nk ? exp(ss[row][j] - m[row]) : 0.0f; }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int r = 0; r < AQT * 3; r++) {
            const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
            const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
            if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
            float acc = 0, ls = 0;
            for (uint j = 0; j < jend; j++) { const float p = ss[r][j]; ls += p; acc += p * float(vs[j][tid]); }
            l[r] += ls; o[r] += acc;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    for (int r = 0; r < AQT * 3; r++) {
        const uint tt = r / 3, h = r % 3;
        if (tt < nq) {
            const uint i = (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + tid;
            A[a.out_off + i] = o[r] / l[r] * sigm(A[a.gate_off + i]);
        }
    }
}

#ifndef NO_MPP
// ======================= tensor-core (M5 neural accelerator) GEMM variants via MetalPerformancePrimitives =======================
typedef mpp::tensor_ops::matmul2d<
    mpp::tensor_ops::matmul2d_descriptor(GM_BN, GM_BM, GM_BK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
    execution_simdgroups<4>> GemmOp;

kernel void k_gemm_t(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                     constant GemmArgs & args [[buffer(5)]],
                     uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup half sa[GM_BM * GM_BK];
    threadgroup half sb[GM_BN * GM_BK];
    threadgroup float sc[GM_BN * GM_BM];
    uint si = 0;
    while (si + 1 < args.nseg && tgp.x >= args.seg[si + 1].tile_start) si++;
    constant GSeg & S = args.seg[si];
    const uint r0 = (tgp.x - S.tile_start) * GM_BM, t0 = tgp.y * GM_BN;
    const uint T = args.T, K = S.K;
    device const uchar * wb = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
    const uint wr = tid / 2, wh = tid % 2;
    const uint xt = tid / 4, xk = (tid % 4) * 8;
    const bool wvalid = r0 + wr < S.nrows, xvalid = t0 + xt < T;
    device const uchar * wrow = wb + (ulong) min(r0 + wr, S.nrows - 1) * S.row_bytes;
    const uint xr = min(t0 + xt, T - 1);
    const uint KX = S.in2 ? K / 2 : K;
    device const float * xrow = A + S.in_off + (ulong) xr * KX;
    device const float * xrow2 = A + S.in2 + (ulong) xr * KX - KX;
    auto tA = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(GM_BK, GM_BM));
    auto tB = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(GM_BK, GM_BN));
    GemmOp mm;
    auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
    for (uint k0 = 0; k0 < K; k0 += GM_BK) {
        half wv[16];
        deq16(wrow, S.wtype, k0 + 16 * wh, wv);
        device const float * xs = (S.in2 && k0 >= KX) ? xrow2 : xrow;
        const float4 x0 = *(device const float4 *) (xs + k0 + xk), x1 = *(device const float4 *) (xs + k0 + xk + 4);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wvalid ? wv[i] : half(0);
        for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        mm.run(tB, tA, cT);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    auto tC = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(GM_BM, GM_BN));
    cT.store(tC);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
        const uint t = i / GM_BM, r = i % GM_BM;
        if (t0 + t < T && r0 + r < S.nrows) A[S.out_off + (t0 + t) * S.ldo + r0 + r] = sc[i];
    }
}

kernel void k_moe_gemm_t(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmArgs & a [[buffer(5)]],
                         uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup half sa[GM_BM * GM_BK];
    threadgroup half sb[GM_BN * GM_BK];
    threadgroup float sc[GM_BN * GM_BM];
    const uint ntiles = as_type<uint>(A[a.ntiles_off]);
    if (tgp.y >= ntiles) return;
    device const uint * tl = (device const uint *) (A + a.tiles_off) + tgp.y * 4;
    const uint e = tl[0], as0 = tl[1], cnt = tl[2];
    device const uint * perm = (device const uint *) (A + a.perm_off);
    const uint wr = tid / 2, wh = tid % 2;
    uint row;
    if (a.situ) row = (wr < 32) ? tgp.x * 32 + wr : FF + tgp.x * 32 + (wr - 32);
    else row = tgp.x * GM_BM + wr;
    device const uchar * wrow = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) row * a.row_bytes;
    const uint xt = tid / 4, xk = (tid % 4) * 8;
    const bool xvalid = xt < cnt;
    const uint arow = as0 + min(xt, cnt - 1);
    const uint xsrc = a.gather ? perm[arow] : arow;
    device const float * xrow = A + a.x_off + (ulong) xsrc * a.K;
    auto tA = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(GM_BK, GM_BM));
    auto tB = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(GM_BK, GM_BN));
    GemmOp mm;
    auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
    for (uint k0 = 0; k0 < a.K; k0 += GM_BK) {
        half wv[16];
        deq16(wrow, a.wtype, k0 + 16 * wh, wv);
        const float4 x0 = *(device const float4 *) (xrow + k0 + xk), x1 = *(device const float4 *) (xrow + k0 + xk + 4);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int i = 0; i < 16; i++) sa[wr * GM_BK + 16 * wh + i] = wv[i];
        for (int i = 0; i < 4; i++) { sb[xt * GM_BK + xk + i] = xvalid ? half(x0[i]) : half(0); sb[xt * GM_BK + xk + 4 + i] = xvalid ? half(x1[i]) : half(0); }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        mm.run(tB, tA, cT);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    auto tC = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(GM_BM, GM_BN));
    cT.store(tC);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (a.wtype == 200) {
        const float g = gscale_at(W, a.gs_lo, a.gs_hi, e);
        for (uint i = tid; i < GM_BN * GM_BM; i += 128) sc[i] *= g;
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    if (a.situ) {
        for (uint i = tid; i < GM_BN * 32; i += 128) {
            const uint t = i / 32, r = i % 32;
            if (t < cnt) {
                const float gt = sc[t * GM_BM + r], up = sc[t * GM_BM + 32 + r];
                const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
                A[a.out_off + (as0 + t) * a.ldo + tgp.x * 32 + r] = act;
            }
        }
    } else {
        for (uint i = tid; i < GM_BN * GM_BM; i += 128) {
            const uint t = i / GM_BM, r = i % GM_BM;
            if (t < cnt) A[a.out_off + (as0 + t) * a.ldo + tgp.x * GM_BM + r] = sc[i];
        }
    }
}

// ---- tensor-core flash attention for prefill: TG = (32-query tile, q head), 8 simdgroups, 64-key steps.
// logit = q.k (q pre-scaled) + r.B[dist] - sink ; sink is a zero logit (M=0, L=1 initially). Output gated by sigmoid.
#define FQ 32
#define FCK 64
#define FNSG 8
kernel void k_attn_bt(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
                      constant AttnBArgs & a [[buffer(5)]],
                      uint2 tgp [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], ushort sgitg [[simdgroup_index_in_threadgroup]]) {
#ifdef KV4
    (void) PB; (void) A; (void) KV; (void) a; (void) tgp; (void) tiisg; (void) sgitg;
#else
    threadgroup float region0[FQ * HD];            // 16 KB: [sq half FQ*HD | ss float FQ*FCK]; reused for O at the end
    threadgroup half sp[FQ * FCK];
    threadgroup float sr[FQ];
    threadgroup float rsh[FQ][NREL];
    threadgroup float sk[FQ];
    threadgroup half * sq = (threadgroup half *) region0;
    threadgroup float * ss = region0 + FQ * HD / 2;
    const ushort tid = sgitg * 32 + tiisg;
    const uint h = tgp.y, g = h / 3, t0 = tgp.x * FQ;
    const uint nq = min((uint) FQ, a.T - t0);
    for (uint i = tid; i < FQ * HD / 4; i += FNSG * 32) {
        const uint row = i / (HD / 4), d4 = i % (HD / 4);
        float4 q = 0;
        if (row < nq) q = *(device const float4 *) (A + a.qp_off + (t0 + row) * (NH * HD) + h * HD + d4 * 4);
        ((threadgroup half4 *) sq)[i] = half4(q);
    }
    for (uint i = tid; i < FQ * NREL; i += FNSG * 32) {
        const uint row = i / NREL, r = i % NREL;
        rsh[row][r] = row < nq ? A[a.rp_off + (t0 + row) * (NH * NREL) + h * NREL + r] : 0.0f;
    }
    if (tid < FQ) sk[tid] = tid < nq ? A[a.sink_off + (t0 + tid) * NH + h] : 0.0f;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    auto tq = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sq, dextents<int32_t, 2>(HD, FQ));
    auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(FCK, FQ));
    auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(FCK, FQ));
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, FCK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
                              execution_simdgroups<FNSG>> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, HD, FCK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
                              execution_simdgroups<FNSG>> mm_pv;
    device kv_t * kbase = KV + a.k_base + g * a.cap * HD;
    device kv_t * vbase = KV + a.v_base + g * a.cap * HD;
    auto tv0 = tensor(vbase, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
    auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
    for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] = 0.0f;

    constexpr short NQR = FQ / FNSG;   // rows per simdgroup
    float M[NQR], S[NQR];
    // P is stored in half scaled by e^8 (cancels in O/S) so small probabilities stay out of fp16 subnormals
    for (short jj = 0; jj < NQR; jj++) { M[jj] = 0.0f; S[jj] = 2980.9579870417283f; }   // the sink: logit 0 -> e^8
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
    const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
    const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
    const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / FCK * FCK) : 0u;
    uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
    kstart = kstart / FCK * FCK;
    for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > FCK) ? recent_kstart : (kc + FCK)) {
        const uint idx = (uint) ((int) kc - a.kpos0);
        auto tk = tensor(kbase + idx * HD, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
        mm_qk.run(tq, tk, ts);
        threadgroup_barrier(mem_flags::mem_threadgroup);
#ifdef KV8
        float ksc[FCK / 32], vsc[FCK / 32];      // scales of this lane's keys
        for (short ii = 0; ii < FCK / 32; ii++) { ksc[ii] = kv_vscale(kbase + (idx + ii * 32 + tiisg) * HD); vsc[ii] = kv_vscale(vbase + (idx + ii * 32 + tiisg) * HD); }
#endif
        for (short jj = 0; jj < NQR; jj++) {
            const uint j = jj * FNSG + sgitg;
            const uint qp = a.p0 + t0 + j;
            float s[FCK / 32];
            float m = M[jj];
            for (short ii = 0; ii < FCK / 32; ii++) {
                const uint col = ii * 32 + tiisg, kp = kc + col;
                const bool valid = j < nq && kp <= qp && (a.window == 0 || qp - kp < a.window)
                    && (!pruned || kp < 64u || qp - kp < recent_win);
                float v = -INFINITY;
                if (valid) {
#ifdef KV8
                    v = ss[j * FCK + col] * ksc[ii] - sk[j];
#else
                    v = ss[j * FCK + col] - sk[j];
#endif
                    const uint dist = qp - kp;
                    if (dist < EXT) {
                        device const float4 * b4 = (device const float4 *) (relb + dist * NREL);
                        threadgroup const float4 * r4 = (threadgroup const float4 *) rsh[j];
                        v += dot(r4[0], b4[0]) + dot(r4[1], b4[1]) + dot(r4[2], b4[2]) + dot(r4[3], b4[3]);
                    }
                }
                s[ii] = v;
                m = max(m, v);
            }
            m = simd_max(m);
            const float ms = exp(M[jj] - m);
            M[jj] = m;
            float sum = 0;
            for (short ii = 0; ii < FCK / 32; ii++) {
                const half p = half(exp(s[ii] - m + 8.0f));
#ifdef KV8
                sp[j * FCK + ii * 32 + tiisg] = half(float(p) * vsc[ii]);
#else
                sp[j * FCK + ii * 32 + tiisg] = p;
#endif
                sum += float(p);
            }
            S[jj] = S[jj] * ms + simd_sum(sum);
            if (tiisg == 0) sr[j] = ms;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
        auto tv = tensor(vbase + idx * HD, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
        mm_pv.run(tp, tv, co);
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    for (short jj = 0; jj < NQR; jj++) { const uint j = jj * FNSG + sgitg; if (tiisg == 0) sr[j] = 1.0f / S[jj]; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
    auto to = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(region0, dextents<int32_t, 2>(HD, FQ));
    co.store(to);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint i = tid; i < FQ * HD; i += FNSG * 32) {
        const uint row = i / HD, d = i % HD;
        if (row < nq) {
            const uint o = (t0 + row) * (NH * HD) + h * HD + d;
            A[a.out_off + o] = region0[i] * sigm(A[a.gate_off + o]);
        }
    }
#endif
}


// ---- tensor-core flash attention, low-ALU version. TG = (32-query tile, head), 8 simdgroups; grid (T/32, NH).
// Q (half), R and the sinks are read straight from device memory. Per 64-key chunk:
//   S = Q.K^T (tensor), G = R.B[dlo..dlo+95]^T (tensor: relative bias for every distance the tile can see; pair (j, col) reads
//   G[j][dist - dlo], the usual skew), online softmax in ALU (P in half, pre-scaled by e^8), O = O*ms + P.V (tensor, accumulators
//   in registers). Epilogue in registers: O/S * sigmoid(gate) -> half, the input of the output projection GEMM.
#define AQ 32
#define AK 64
#define AG 96
kernel void k_attn_h(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]],
                     constant AttnBArgs & a [[buffer(5)]],
                     uint2 tgp [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
#ifdef KV4
    (void) PB; (void) A; (void) KV; (void) a; (void) tgp; (void) lane; (void) sg;
#else
    threadgroup float ss[AQ * AK];
    threadgroup float G[AQ * AG];
    threadgroup half sp[AQ * AK];
    threadgroup float sr[AQ];
    const uint h = tgp.y, g = h / 3, t0 = tgp.x * AQ;
    const uint nq = min((uint) AQ, a.T - t0);
    auto tq = tensor((device half *) (A + a.qp_off) + (ulong) t0 * (NH * HD) + h * HD, dextents<int32_t, 2>(HD, (int) nq), array<int, 2>({1, NH * HD}));
    auto tr = tensor(A + a.rp_off + t0 * (NH * NREL) + h * NREL, dextents<int32_t, 2>(NREL, (int) nq), array<int, 2>({1, NH * NREL}));
    auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(AK, AQ));
    auto tg = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(G, dextents<int32_t, 2>(AG, AQ));
    auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(AK, AQ));
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
                              execution_simdgroups<8>> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AG, NREL, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
                              execution_simdgroups<8>> mm_g;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, HD, AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
                              execution_simdgroups<8>> mm_pv;
    device kv_t * kbase = KV + a.k_base + g * a.cap * HD;
    device kv_t * vbase = KV + a.v_base + g * a.cap * HD;
    auto tv0 = tensor(vbase, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
    auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
    for (short i = 0; i < 16; ++i) co[i] = 0.0f;
    // this thread's accumulators: 4 quads of (4 consecutive dims, one query row)
    ushort cd[4], cr[4];
    for (short q = 0; q < 4; ++q) { const auto ix = co.get_multidimensional_index(4 * q); cd[q] = ix[0]; cr[q] = ix[1]; }
    // this simdgroup's query rows: j = jj * 8 + sg
    float M[4], S[4];
    for (short jj = 0; jj < 4; jj++) {
        const uint j = jj * 8 + sg;
        // the sink is one more key with logit sink[j] (running max starts there, its probability e^8 in the scaled sum)
        M[jj] = j < nq ? A[a.sink_off + (t0 + j) * NH + h] : 0.0f; S[jj] = 2980.9579870417283f;
    }
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
    const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
    const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
    const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / AK * AK) : 0u;
    uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
    kstart = kstart / AK * AK;
    for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > AK) ? recent_kstart : (kc + AK)) {
        const uint idx = (uint) ((int) kc - a.kpos0);
        auto tk = tensor(kbase + idx * HD, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
        // (a threadgroup-memory destination is far slower than register accumulators + store)
        { auto cs = mm_qk.template get_destination_cooperative_tensor<decltype(tq), decltype(tk), float>(); mm_qk.run(tq, tk, cs); cs.store(ts); }
        const int D0 = int(pfirst) - int(kc);            // dist(j, col) = D0 + j - col
        const int dlo = max(D0 - (AK - 1), 0);
        const bool bias = dlo < EXT;
        if (bias) {
            auto tb = tensor((device float *) relb + dlo * NREL, dextents<int32_t, 2>(NREL, AG), array<int, 2>({1, NREL}));
            auto cg = mm_g.template get_destination_cooperative_tensor<decltype(tr), decltype(tb), float>(); mm_g.run(tr, tb, cg); cg.store(tg);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        // interior chunk: every key is visible to every query of the tile and inside the bias table (or entirely beyond it)
        const bool fast = !pruned && nq == AQ && D0 >= AK - 1 && (a.window == 0 || D0 + AQ - 1 < (int) a.window) && (!bias || D0 + AQ - 1 < EXT);
        const int gofs = D0 - dlo - int(lane);
#ifdef KV8
        // scales of this lane's two keys: K into the scores, V into the probabilities that weight the stored integers
        const float ks0 = kv_vscale(kbase + (idx + lane) * HD), ks1 = kv_vscale(kbase + (idx + 32 + lane) * HD);
        const float vs0 = kv_vscale(vbase + (idx + lane) * HD), vs1 = kv_vscale(vbase + (idx + 32 + lane) * HD);
#endif
        for (short jj = 0; jj < 4; jj++) {
            const uint j = jj * 8 + sg;
#ifdef KV8
            float s0 = ss[j * AK + lane] * ks0, s1 = ss[j * AK + 32 + lane] * ks1;
#else
            float s0 = ss[j * AK + lane], s1 = ss[j * AK + 32 + lane];
#endif
            if (fast) {
                if (bias) { threadgroup const float * gp = G + j * AG + j + gofs; s0 += gp[0]; s1 += gp[-32]; }
            } else {
                const int d0 = D0 + int(j) - int(lane), d1 = d0 - 32;
                if (bias && d0 < EXT) s0 += G[j * AG + clamp(d0 - dlo, 0, AG - 1)];
                if (bias && d1 < EXT) s1 += G[j * AG + clamp(d1 - dlo, 0, AG - 1)];
                if (!(j < nq && d0 >= 0 && (a.window == 0 || d0 < (int) a.window) && (!pruned || (kc + lane < 64u) || d0 < (int) recent_win))) s0 = -INFINITY;
                if (!(j < nq && d1 >= 0 && (a.window == 0 || d1 < (int) a.window) && (!pruned || (kc + 32u + lane < 64u) || d1 < (int) recent_win))) s1 = -INFINITY;
            }
            const float m = simd_max(max(M[jj], max(s0, s1)));
            const float ms = exp(M[jj] - m);
            M[jj] = m;
            const half p0 = half(exp(s0 - m + 8.0f)), p1 = half(exp(s1 - m + 8.0f));
#ifdef KV8
            sp[j * AK + lane] = half(float(p0) * vs0);
            sp[j * AK + 32 + lane] = half(float(p1) * vs1);
#else
            sp[j * AK + lane] = p0;
            sp[j * AK + 32 + lane] = p1;
#endif
            S[jj] = S[jj] * ms + simd_sum(float(p0) + float(p1));
            if (lane == 0) sr[j] = ms;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        {
            const float r0 = sr[cr[0]], r1 = sr[cr[1]], r2 = sr[cr[2]], r3 = sr[cr[3]];
            co[0] *= r0; co[1] *= r0; co[2] *= r0; co[3] *= r0;
            co[4] *= r1; co[5] *= r1; co[6] *= r1; co[7] *= r1;
            co[8] *= r2; co[9] *= r2; co[10] *= r2; co[11] *= r2;
            co[12] *= r3; co[13] *= r3; co[14] *= r3; co[15] *= r3;
        }
        auto tv = tensor(vbase + idx * HD, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
        mm_pv.run(tp, tv, co);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (short jj = 0; jj < 4; jj++) { if (lane == 0) sr[jj * 8 + sg] = 1.0f / S[jj]; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device half * out = (device half *) (A + a.out_off);
    for (short q = 0; q < 4; ++q) {
        const uint row = cr[q];
        if (row < nq) {
            const uint o = (t0 + row) * (NH * HD) + h * HD + cd[q];
            const float4 gt = a.ghalf ? float4(*(device const half4 *) ((device const half *) (A + a.gate_off) + o)) : *(device const float4 *) (A + a.gate_off + o);
            const float4 v = float4(co[4 * q], co[4 * q + 1], co[4 * q + 2], co[4 * q + 3]) * sr[row] / (1.0f + exp(-gt));
            *(device half4 *) (out + o) = half4(v);
        }
    }
#endif
}
// accumulator layout probe for k_attn_h's P.V op (same format as k_layout)
kernel void k_layout_att(device float * A [[buffer(2)]], device kv_t * KV [[buffer(3)]], constant uint & out_off [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup half sp[AQ * AK];
    auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(AK, AQ));
#ifdef KV4
    auto tv0 = tensor((device half *) KV, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
#else
    auto tv0 = tensor(KV, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
#endif
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, HD, AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
                              execution_simdgroups<8>> mm_pv;
    auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
    device int * o = (device int *) (A + out_off) + tid * 64;
    for (short i = 0; i < co.get_capacity() && i < 63; ++i) {
        if (co.is_valid_element(i)) { const auto ix = co.get_multidimensional_index(i); o[i] = (ix[0] << 16) | ix[1]; } else o[i] = -1;
    }
    o[63] = co.get_capacity();
}
#endif // NO_MPP

// ---- batched loop-controller apply: out = u*(1 - tanh(f)) + tanh(g)*m, then RMSNorm(weight). grid (T, nC), 256 threads
struct CtrlBJob { uint u_off, m_off, g_off, f_off, out_off, norm_w; int h_off; uint nof32; };   // h_off >= 0: also (nof32: only) half output
struct CtrlBArgs { uint n; uint pad0, pad1, pad2; CtrlBJob job[4]; };
kernel void k_ctrl_apply_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant CtrlBArgs & a [[buffer(5)]],
                           uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                           ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup float sh[32];
    constant CtrlBJob & J = a.job[tgp.y];
    const uint t = tgp.x, off = t * E;
    float o[9], ss = 0;
    for (int k = 0; k < 9; k++) {
        const uint i = tid + k * 256;
        const float u = A[J.u_off + off + i];
        if (J.m_off == 0xFFFFFFFFu) o[k] = u;      // already applied by k_ctrl_gf
        else { const float m = A[J.m_off + off + i]; o[k] = u - tanh(A[J.f_off + off + i]) * u + tanh(A[J.g_off + off + i]) * m; }
        ss += o[k] * o[k];
    }
    ss = tg_sum(ss, sh, sg, lane, 8);
    const float r = rsqrt(ss / E + 1e-6f);
    device const float * w = (device const float *) (PB + J.norm_w);
    for (int k = 0; k < 9; k++) {
        const uint i = tid + k * 256;
        const float v = o[k] * r * w[i];
        if (J.h_off >= 0) ((device half *) (A + J.h_off))[off + i] = half(v);
        if (!J.nof32) A[J.out_off + off + i] = v;
    }
}

// ---- batched depth mix (same math as k_mix): one simdgroup per (job, token), no barriers.
// pass 1 accumulates per-state dot products with the queries AND the Gram matrix of the states, so the output
// RMS norm is known analytically (|sum a_i s_i|^2 = sum a_i a_j <s_i,s_j>); pass 2 writes normalized outputs directly.
// Specialized on (number of states, number of queries) so every register array is statically indexed.
template <int NS, int NQ, bool IDENT>
inline void mix_b_job(device const uchar * PB, device float * A, constant MixJob & J, uint tg, ushort sg, ushort lane) {
    const uint tok = tg * 4 + sg;
    if (tok >= J.pad_t) return;
    const uint toff = tok * J.tstride;
    device const float4 * S[NS];
    #pragma unroll
    for (int i = 0; i < NS; i++) S[i] = (device const float4 *) (A + J.s_off[i] + toff);
    float G[NS][NS], D[NS][NQ];
    #pragma unroll
    for (int i = 0; i < NS; i++) {
        #pragma unroll
        for (int j = 0; j < NS; j++) G[i][j] = 0;
        #pragma unroll
        for (int q = 0; q < NQ; q++) D[i][q] = 0;
    }
    device const float4 * Q = (device const float4 *) (PB + max(J.q_off, 0));
    for (uint k = lane; k < E / 4; k += 32) {
        float4 v[NS];
        #pragma unroll
        for (int i = 0; i < NS; i++) v[i] = S[i][k];
        float4 qv[NQ];
        #pragma unroll
        for (int q = 0; q < NQ; q++) qv[q] = IDENT ? float4(0) : Q[q * (E / 4) + k];
        #pragma unroll
        for (int i = 0; i < NS; i++) {
            #pragma unroll
            for (int j = i; j < NS; j++) G[i][j] += dot(v[i], v[j]);
            #pragma unroll
            for (int q = 0; q < NQ; q++) D[i][q] += dot(v[i], qv[q]);
        }
    }
    #pragma unroll
    for (int i = 0; i < NS; i++) {
        #pragma unroll
        for (int j = i; j < NS; j++) { G[i][j] = simd_sum(G[i][j]); G[j][i] = G[i][j]; }
        #pragma unroll
        for (int q = 0; q < NQ; q++) D[i][q] = simd_sum(D[i][q]);
    }
    float al[NQ][NS], rn[NQ], rw[NQ];
    #pragma unroll
    for (int q = 0; q < NQ; q++) {
        if (IDENT) {
            #pragma unroll
            for (int i = 0; i < NS; i++) al[q][i] = i == 0 ? 1.0f : 0.0f;
        } else {
            float sc[NS], mx = -INFINITY;
            #pragma unroll
            for (int i = 0; i < NS; i++) { sc[i] = rsqrt(G[i][i] / E + 1e-6f) * D[i][q] * (1.0f / 48.0f); mx = max(mx, sc[i]); }
            float den = 0;
            #pragma unroll
            for (int i = 0; i < NS; i++) { sc[i] = exp(sc[i] - mx); den += sc[i]; }
            #pragma unroll
            for (int i = 0; i < NS; i++) al[q][i] = sc[i] / den * rsqrt(G[i][i] / E + 1e-6f);
        }
        float nn = 0;
        #pragma unroll
        for (int i = 0; i < NS; i++) {
            #pragma unroll
            for (int j = 0; j < NS; j++) nn += al[q][i] * al[q][j] * G[i][j];
        }
        rn[q] = rsqrt(nn / E + 1e-6f);
        rw[q] = rsqrt(nn / E + J.eps);
    }
    for (uint k = lane; k < E / 4; k += 32) {
        float4 v[NS];
        #pragma unroll
        for (int i = 0; i < NS; i++) v[i] = S[i][k];
        #pragma unroll
        for (int q = 0; q < NQ; q++) {
            float4 o = 0;
            #pragma unroll
            for (int i = 0; i < NS; i++) o += al[q][i] * v[i];
            #pragma unroll
            for (int c2 = 0; c2 < 3; c2++) {
                if (J.ncopy[q][c2] >= 0) ((device float4 *) (A + J.ncopy[q][c2] + toff))[k] = o * rn[q];
                if (J.hcopy[q][c2] >= 0) ((device half4 *) ((device half *) (A + J.hcopy[q][c2]) + (ulong) tok * J.hstride))[k] = half4(o * rn[q]);
            }
            if (J.norm_off[q] >= 0) o *= rw[q] * ((device const float4 *) (PB + J.norm_off[q]))[k];
            if (J.hout[q] >= 0) ((device half4 *) ((device half *) (A + J.hout[q]) + (ulong) tok * E))[k] = half4(o);
            if (!((J.nof32 >> q) & 1)) ((device float4 *) (A + J.out_off[q] + toff))[k] = o;
        }
    }
}
template <int NS, int NQ, bool IDENT>
kernel void k_mix_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MixJob & J [[buffer(5)]],
                    uint tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    mix_b_job<NS, NQ, IDENT>(PB, A, J, tg, sg, lane);
}
#define MIXB(NS, NQ) template [[host_name("k_mix_b_" #NS "_" #NQ)]] kernel void k_mix_b<NS, NQ, false>(device const uchar *, device float *, constant MixJob &, uint, ushort, ushort);
MIXB(1, 1) MIXB(2, 1) MIXB(3, 1) MIXB(4, 1) MIXB(5, 1) MIXB(6, 1)
MIXB(1, 3) MIXB(2, 3) MIXB(3, 3) MIXB(4, 3) MIXB(5, 3) MIXB(6, 3)
MIXB(1, 4) MIXB(2, 4) MIXB(3, 4) MIXB(4, 4) MIXB(5, 4) MIXB(6, 4)
template [[host_name("k_mix_b_id")]] kernel void k_mix_b<1, 1, true>(device const uchar *, device float *, constant MixJob &, uint, ushort, ushort);
template <int NS>
inline void mix_wave_q(device const uchar * PB, device float * A, constant MixJob & J, uint tg, ushort sg, ushort lane) {
    if (J.nQ == 3) mix_b_job<NS, 3, false>(PB, A, J, tg, sg, lane);
    else if (J.nQ == 4) mix_b_job<NS, 4, false>(PB, A, J, tg, sg, lane);
    else mix_b_job<NS, 1, false>(PB, A, J, tg, sg, lane);
}
// One dispatch for every job of a mix: the same per-job arithmetic as k_mix_b_*, run together.
// Grid (tokens/4, njobs). Each threadgroup's job is uniform, so the switch does not diverge.
kernel void k_mix_wave(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MixJob * jobs [[buffer(5)]],
                       uint2 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    constant MixJob & J = jobs[tg.y];
    if (J.q_off < 0) { mix_b_job<1, 1, true>(PB, A, J, tg.x, sg, lane); return; }
    switch (J.nS) {
    case 1: mix_wave_q<1>(PB, A, J, tg.x, sg, lane); break;
    case 2: mix_wave_q<2>(PB, A, J, tg.x, sg, lane); break;
    case 3: mix_wave_q<3>(PB, A, J, tg.x, sg, lane); break;
    case 4: mix_wave_q<4>(PB, A, J, tg.x, sg, lane); break;
    case 5: mix_wave_q<5>(PB, A, J, tg.x, sg, lane); break;
    default: mix_wave_q<6>(PB, A, J, tg.x, sg, lane); break;
    }
}

// ======================= fp16-activation tensor GEMMs (activations streamed from device memory as half) =======================
#define HB_M 64
#define HB_N 64
#define HB_K 32

// f32 [rows][K] -> half; optionally gathered rows (perm) ; grid (K/256, rows), 256 threads... generic elementwise
struct ToHalfArgs { uint src_off, dst_off, K, rows, perm_off, gather, src_stride, dst_stride; };
kernel void k_tohalf(device float * A [[buffer(2)]], constant ToHalfArgs & a [[buffer(5)]],
                     uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    const uint r = tgp.y, c = (tgp.x * 256 + tid) * 4;
    if (c >= a.K) return;
    const uint sr = (a.gather & 1) ? ((device const uint *) (A + a.perm_off))[r] : r;
    device half4 * dst = (device half4 *) ((device half *) (A + a.dst_off) + (ulong) r * a.dst_stride + c);
    if (a.gather & 2) *dst = *(device const half4 *) ((device const half *) (A + a.src_off) + (ulong) sr * a.src_stride + c);   // half source
    else *dst = half4(*(device const float4 *) (A + a.src_off + (ulong) sr * a.src_stride + c));
}

// ---- weight tile staging (64 rows x 32 k, half) for the tensor GEMMs below.
// Q4_K fast path: the block header (d, dmin, 12 scale bytes) is loaded once per super-block and kept in registers, so a k-step
// is one 16-byte load + unpack with no dependent loads in front of it: the staging latency stalls every simdgroup of the tile.
struct WHead { float d, m; uint s0, s1, s2; };
inline void wstage(device const uchar * wr, uint wtype, uint k0, uint hp, thread WHead & h, thread half4 * w) {
    if (wtype != 12) { deq16(wr, wtype, k0 + hp * 16, (thread half *) w); return; }
    device const block_q4_K * b = (device const block_q4_K *) wr + k0 / 256;
    const uint j = (k0 % 256) / 32;
    if (j == 0) { h.d = b->d; h.m = b->dmin; const uint3 sc3 = *(device const packed_uint3 *) b->scales; h.s0 = sc3.x; h.s1 = sc3.y; h.s2 = sc3.z; }
    uint sc, mn;    // 6-bit scale / min of sub-block j (same decoding as scale_min_k4)
    if (j < 4) { sc = (h.s0 >> (8 * j)) & 63; mn = (h.s1 >> (8 * j)) & 63; }
    else {
        const uint hi = (h.s2 >> (8 * (j - 4))) & 0xFF;
        sc = (hi & 0xF) | (((h.s0 >> (8 * (j - 4) + 6)) & 3) << 4);
        mn = (hi >> 4) | (((h.s1 >> (8 * (j - 4) + 6)) & 3) << 4);
    }
    // fp32 scale/offset, one rounding to half (bit-identical to the scalar reference path)
    const float df = h.d * float(sc), mf = h.m * float(mn);
    const uint4 v = (*(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16) >> ((j & 1) * 4)) & 0x0F0F0F0Fu;
    w[0] = half4(fma(float4(as_type<uchar4>(v.x)), df, -mf)); w[1] = half4(fma(float4(as_type<uchar4>(v.y)), df, -mf));
    w[2] = half4(fma(float4(as_type<uchar4>(v.z)), df, -mf)); w[3] = half4(fma(float4(as_type<uchar4>(v.w)), df, -mf));
}

// All fp16 GEMMs share one tile shape: a threadgroup of NSG simdgroups stages a 64-row x 32-k weight tile per k-step (first
// 128 threads, double-buffered), and every simdgroup runs its OWN tensor op (execution_simdgroup) on its own 16 tokens with the
// accumulators (64 x 16) in registers. Compared with one op over the whole threadgroup this is a little faster, and simdgroups
// whose tokens do not exist simply skip the matmul, so ragged token counts cost 16-token granularity instead of a whole tile.
// Register epilogues rely on the op's accumulator layout: 8 quads of 4 consecutive rows per thread, quads q and q+4 holding rows
// r and r+32 of the same token. Engine::load verifies this with k_layout_sg before enabling the path.
#ifndef NO_MPP
#define SGOP(mm) mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(16, HB_M, HB_K, false, true, false, \
    mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), execution_simdgroup> mm

// segmented dense GEMM: Y[t][r] = sum_k Xh[t][k] W[r][k]; Xh half [T][K]. grid (token tiles of 16*NSG, row tiles of 64):
// Metal sweeps y fastest, so the row tiles of one token tile run together and its X stays cached.
struct HSeg { uint w_lo, w_hi, row_bytes, wtype, nrows, K, tile_start, xh_off, out_off, ldo, wsrc, hout; };   // hout: half output [T][ldo]
struct GemmHArgs { uint nseg, T, pad0, pad1; HSeg seg[10]; };
template <int NSG>
kernel void k_gemm_sg(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                      constant GemmHArgs & args [[buffer(5)]], uint2 tgq [[threadgroup_position_in_grid]],
                      ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
    threadgroup half sa[2][HB_M * HB_K];
    uint si = 0;
    while (si + 1 < args.nseg && tgq.y >= args.seg[si + 1].tile_start) si++;
    constant HSeg & S = args.seg[si];
    const uint r0 = (tgq.y - S.tile_start) * HB_M, t0 = (tgq.x * NSG + sg) * 16, K = S.K, T = args.T;
    const bool on = t0 < T;
    const int nt = on ? min(16, (int) (T - t0)) : 0;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(HB_K, HB_M));
    auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[1], dextents<int32_t, 2>(HB_K, HB_M));
    auto tX = tensor((device half *) (A + S.xh_off) + (ulong) (on ? t0 : 0) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
    SGOP(mm);
    auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
    const bool wact = tid < 128;
    const uint widx = tid * 16, hp = (widx % HB_K) / 16;
    device const uchar * wr = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo) + (ulong) min(r0 + widx / HB_K, S.nrows - 1) * S.row_bytes;
    WHead wh; half4 wv[4];
    if (wact) { wstage(wr, S.wtype, 0, hp, wh, wv); for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[0] + widx))[i] = wv[i]; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    uint buf = 0;
    for (uint k0 = 0; k0 < K; k0 += HB_K) {
        const bool more = k0 + HB_K < K;
        if (more && wact) wstage(wr, S.wtype, k0 + HB_K, hp, wh, wv);
        if (on) { auto sx = tX.slice(k0, 0); if (buf == 0) mm.run(sx, tA0, cT); else mm.run(sx, tA1, cT); }
        if (more && wact) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[buf ^ 1] + widx))[i] = wv[i];
        threadgroup_barrier(mem_flags::mem_threadgroup);
        buf ^= 1;
    }
    if (!on) return;
    if (S.hout) {
        device half * yo = (device half *) (A + S.out_off);
        for (short q = 0; q < 8; ++q) {
            const auto ix = cT.get_multidimensional_index(4 * q);
            const uint r = r0 + ix[0], t = t0 + ix[1];
            if (r < S.nrows && t < T) *(device half4 *) (yo + (ulong) t * S.ldo + r) = half4(float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]));
        }
        return;
    }
    auto tC = tensor(A + S.out_off + (ulong) t0 * S.ldo + r0, dextents<int32_t, 2>(min(HB_M, (int) (S.nrows - r0)), nt), array<int, 2>({1, (int) S.ldo}));
    cT.store(tC);
}
template [[host_name("k_gemm_sg8")]] kernel void k_gemm_sg<8>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort);
template [[host_name("k_gemm_sg4")]] kernel void k_gemm_sg<4>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort);

// grouped MoE GEMM (contiguous half rows per tile: gathered gate_up input / act rows). grid (tiles, column blocks).
// situ=1: rows = 32 gate + 32 up of column block y; SiTU * routing weight in registers -> half act [A][FF]. situ=0: half out [A][ldo].
struct MoeGemmHArgs {
    uint w_lo, w_hi, expert_bytes, row_bytes, wtype, nrows, K, xh_off;
    uint tiles_off, ntiles_off, out_off, ldo, situ, aw_off; float beta, lbeta;
    uint gs_lo, gs_hi, pad0, pad1;
};
// WT: the weights' type, SITU: gate/up (1) or down (0), as compile-time constants. The staging loop is latency-bound, and
// the code of formats a kernel never reads still costs it registers and branches (deq16 walks Q3_K, Q2_K, Q3_0, NV4 and MX8
// before Q8_0). WT = 0: any type, either use, decided at run time from the arguments. The arithmetic is the same either way.
// Ported from chadlyb/erisinky 36c497fb by Chad: "My changes are Copyright (C) 2026 Rewt", GPL-3.0-or-later.
template <int NSG, uint WT, uint SITU>
kernel void k_moe_sg(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmHArgs & a [[buffer(5)]],
                     uint2 tgq [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
    threadgroup half sa[2][HB_M * HB_K];
    const uint cb = tgq.y;
    if (tgq.x >= ((device const uint *) (A + a.ntiles_off))[0]) return;
    device const uint * tl = (device const uint *) (A + a.tiles_off) + tgq.x * 4;
    const uint e = tl[0], as0 = tl[1], cnt = tl[2], ts0 = sg * 16;
    const bool on = ts0 < cnt;
    const int nt = on ? min(16, (int) (cnt - ts0)) : 0;
    const uint K = a.K, wt = WT ? WT : a.wtype;
    const bool situ = WT ? SITU != 0 : a.situ != 0;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(HB_K, HB_M));
    auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[1], dextents<int32_t, 2>(HB_K, HB_M));
    auto tX = tensor((device half *) (A + a.xh_off) + (ulong) (as0 + (on ? ts0 : 0)) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
    SGOP(mm);
    auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
    const bool wact = tid < 128;
    const uint widx = tid * 16, rr = widx / HB_K, hp = (widx % HB_K) / 16;
    const uint wrow = situ ? ((rr < 32) ? cb * 32 + rr : FF + cb * 32 + (rr - 32)) : cb * HB_M + rr;
    device const uchar * wr = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) wrow * a.row_bytes;
    WHead wh; half4 wv[4];
    if (wact) { wstage(wr, wt, 0, hp, wh, wv); for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[0] + widx))[i] = wv[i]; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    uint buf = 0;
    for (uint k0 = 0; k0 < K; k0 += HB_K) {
        const bool more = k0 + HB_K < K;
        if (more && wact) wstage(wr, wt, k0 + HB_K, hp, wh, wv);
        if (on) { auto sx = tX.slice(k0, 0); if (buf == 0) mm.run(sx, tA0, cT); else mm.run(sx, tA1, cT); }
        if (more && wact) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[buf ^ 1] + widx))[i] = wv[i];
        threadgroup_barrier(mem_flags::mem_threadgroup);
        buf ^= 1;
    }
    if (!on) return;
    if (wt == 200) { const float g = gscale_at(W, a.gs_lo, a.gs_hi, e); for (short i = 0; i < cT.get_capacity(); ++i) if (cT.is_valid_element(i)) cT[i] *= g; }
    if (!situ) {
        device half * yd = (device half *) (A + a.out_off);
        for (short q = 0; q < 8; ++q) {
            const auto ix = cT.get_multidimensional_index(4 * q);
            const uint r = ix[0], t = ts0 + ix[1];
            if (t < cnt) *(device half4 *) (yd + (ulong) (as0 + t) * a.ldo + cb * HB_M + r) = half4(float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]));
        }
        return;
    }
    device half * act = (device half *) (A + a.out_off);
    for (short q = 0; q < 4; ++q) {
        const auto ix = cT.get_multidimensional_index(4 * q);          // gate rows r..r+3; quad q+4 holds the matching up rows
        const uint r = ix[0], t = ts0 + ix[1];
        if (t < cnt) {
            const float4 gt = float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]);
            const float4 up = float4(cT[4 * q + 16], cT[4 * q + 17], cT[4 * q + 18], cT[4 * q + 19]);
            const float4 su = a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up;
            const float4 o = (A[a.aw_off + as0 + t] * a.beta) * tanh(gt / a.beta) / (1.0f + exp(-gt)) * su;
            *(device half4 *) (act + (ulong) (as0 + t) * FF + cb * 32 + r) = half4(o);
        }
    }
}
#define MOE_SG(NSG, name, WT, SITU) template [[host_name(name)]] kernel void k_moe_sg<NSG, WT, SITU>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort);
MOE_SG(8, "k_moe_sg8", 0, 0) MOE_SG(4, "k_moe_sg4", 0, 0)
// Engine::moe_sg_kernel picks these by name: k_moe_sg<NSG>_<gu|dn>_<type>
#define MOE_SG_T(WT, ty) MOE_SG(8, "k_moe_sg8_gu_" ty, WT, 1) MOE_SG(4, "k_moe_sg4_gu_" ty, WT, 1) \
                         MOE_SG(8, "k_moe_sg8_dn_" ty, WT, 0) MOE_SG(4, "k_moe_sg4_dn_" ty, WT, 0)
MOE_SG_T(12, "q4k") MOE_SG_T(8, "q8_0") MOE_SG_T(6, "q5_0") MOE_SG_T(200, "nv4") MOE_SG_T(201, "mx8")

// ---- Coalesced `16 rows x 128 k` tensor-core decode kernels (`k_moe_dec_sg` & `k_gemm_dec_sg`) + `k_gemm_bf16_dec`.
// 1. In `k_moe_sg4` (`64 rows x 32 k`), only 2 threads stage each weight row (`16B` per thread, strided by `1.3..2.8 KB`
//    across 16 disjoint cache lines per simdgroup, stalling on 72 barriers for K=2304).
// 2. Here each tile is `DEC_M = 16` rows x `DEC_K = 128` k in a ring of `2 * NSG / 4` tiles (`dec_wring`: sg4 8 KiB, sg8 16 KiB)
//    : 8 consecutive threads (`sub = tid % 8`) stage 128 contiguous weights (`64..136` contiguous bytes) of
//    the SAME weight row in one coalesced burst with zero cross-step duplicate nibble/qh reads and 4x fewer barriers
//    (K=2304: 18 barriers in sg4, 9 in sg8, whose 256 threads stage two k-steps each), while M5 `matmul2d(16, 16, 128)` tensor cores execute at full throughput
//    across 1..128 tokens.
// 3. `k_gemm_bf16_dec` runs small BF16 projections (`router` 128 rows, `ctrl_down` 256 rows) in coalesced register
//    batches (`3..6.6x` faster than tensor-tile staging) with `#pragma clang fp contract(off) reassociate(off)` so
//    prefill and decode produce bit-identical results across all batch sizes.
#define DEC_M 16
#define DEC_K 128
#define DEC_NR 2

#define DEC_SGOP(mm) mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(16, DEC_M, DEC_K, false, true, false, \
    mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), execution_simdgroup> mm

inline uint4 load_u16_aligned_16b(device const uchar * p) {
    device const packed_ushort4 * u = (device const packed_ushort4 *) p;
    const ushort4 a = ushort4(u[0]), b = ushort4(u[1]);
    return uint4(
        uint(a.x) | (uint(a.y) << 16),
        uint(a.z) | (uint(a.w) << 16),
        uint(b.x) | (uint(b.y) << 16),
        uint(b.z) | (uint(b.w) << 16)
    );
}

inline void wstage_16x128(device const uchar * wr, uint wtype, uint k0, uint sub, bool fresh, thread WHead & h, thread half4 * w) {
    if (wtype == 12) {
        device const block_q4_K * b = (device const block_q4_K *) wr + k0 / 256;
        const uint half_sb = (k0 % 256) / 128;
        if (half_sb == 0 || fresh) {
            h.d = b->d; h.m = b->dmin;
            const uint3 sc3 = *(device const packed_uint3 *) b->scales;
            h.s0 = sc3.x; h.s1 = sc3.y; h.s2 = sc3.z;
        }
        const uint j = half_sb * 4 + sub / 2, hp = sub & 1;
        uint sc, mn;
        if (j < 4) { sc = (h.s0 >> (8 * j)) & 63; mn = (h.s1 >> (8 * j)) & 63; }
        else {
            const uint hi = (h.s2 >> (8 * (j - 4))) & 0xFF;
            sc = (hi & 0xF) | (((h.s0 >> (8 * (j - 4) + 6)) & 3) << 4);
            mn = (hi >> 4)  | (((h.s1 >> (8 * (j - 4) + 6)) & 3) << 4);
        }
        const float df = h.d * float(sc), mf = h.m * float(mn);
        const uint4 v = (*(device const uint4 *) (b->qs + (j / 2) * 32 + hp * 16) >> ((j & 1) * 4)) & 0x0F0F0F0Fu;
        w[0] = half4(fma(float4(as_type<uchar4>(v.x)), df, -mf));
        w[1] = half4(fma(float4(as_type<uchar4>(v.y)), df, -mf));
        w[2] = half4(fma(float4(as_type<uchar4>(v.z)), df, -mf));
        w[3] = half4(fma(float4(as_type<uchar4>(v.w)), df, -mf));
        return;
    }
    if (wtype == 14) {
        device const block_q6_K * b = (device const block_q6_K *) wr + k0 / 256;
        const uint n = (k0 % 256) / 128, g = sub / 2, hp = sub & 1, l0 = hp * 16;
        const float d = float(b->d) * float(b->scales[8 * n + hp + 2 * g]);
        const uint4 ql_v = load_u16_aligned_16b(b->ql + 64 * n + (g & 1) * 32 + l0);
        const uint4 qh_v = load_u16_aligned_16b(b->qh + 32 * n + l0);
        const uint s4 = (g >> 1) * 4, s2 = 2 * g;
        for (int i = 0; i < 4; i++) {
            const uint u6 = ((ql_v[i] >> s4) & 0x0F0F0F0Fu) | (((qh_v[i] >> s2) & 0x03030303u) << 4);
            w[i] = half4(d * float4(int4(as_type<uchar4>(u6)) - int4(32)));
        }
        return;
    }
    if (wtype == 6) {
        device const block_q5_0 * b = (device const block_q5_0 *) wr + (k0 / 32 + sub / 2);
        const half d = b->d;
        const uint hp = sub & 1;
        const uint4 v = load_u16_aligned_16b(b->qs);
        const uint hb = ((device const ushort *) b->qh)[hp];
        const uint sh = hp * 4;
        for (int i = 0; i < 4; i++) {
            const uint n = (v[i] >> sh) & 0x0F0F0F0Fu;
            const uint h5 = (((hb >> (4 * i)) & 0xFu) * 0x00204081u) & 0x01010101u;
            w[i] = half4(as_type<char4>(n | ((0x01010101u - h5) * 0xF0u))) * d;
        }
        return;
    }
    if (wtype == 8) {
        device const block_q8_0 * b = (device const block_q8_0 *) wr + (k0 / 32 + sub / 2);
        const half d = b->d;
        device const packed_char4 * q = (device const packed_char4 *) (b->qs + (sub & 1) * 16);
        for (int i = 0; i < 4; i++) w[i] = half4(char4(q[i])) * d;
        return;
    }
    if (wtype == 30) {
        device const packed_ushort4 * q = (device const packed_ushort4 *) (wr + (k0 + sub * 16) * 2);
        for (int i = 0; i < 4; i++) w[i] = half4(as_type<float4>(uint4(ushort4(q[i])) << 16));
        return;
    }
    deq16(wr, wtype, k0 + sub * 16, (thread half *) w);
}

// Weight ring of the decode tiles: every thread stages. Thread tid loads 16 weights of row rr for k-step tid / 128 of
// each group of KG = NSG / 4 k-steps (sg4: 1 step per barrier, sg8: 2 steps per barrier on all 256 threads) into a ring
// of 2 * KG tiles, double-buffered by group. The matmuls run k-step by k-step in the same order as one-step staging, so
// the accumulation is bit-identical. With KG >= 2 every staging call reloads its Q4_K header (fresh), so no header
// stays live across iterations; sg4 keeps carrying it from the first half of a superblock to the second.
// If the 16 KiB sg8 ring costs occupancy on M5, two 8 KiB fallbacks: a 3-tile ring with the staged weights carried in
// registers across one barrier, or KG = 1 with 16 threads per row x 8 weights per thread (half4 wv[2]) (from Emma
// Gemini's cold review).
template <int NSG, typename MM, typename TX, typename CT>
inline void dec_wring(threadgroup half * sa, device const uchar * wr, uint wtype, uint K, bool on, ushort tid,
                      thread MM & mm, thread TX & tX, thread CT & cT) {
    constexpr uint KG = NSG / 4;
    const uint kg = tid / 128, sub = tid % 8, widx = ((tid % 128) / 8) * DEC_K + sub * 16;
    const bool fresh = KG >= 2;
    WHead wh; half4 wv[4];
    if (kg * DEC_K < K) {
        wstage_16x128(wr, wtype, kg * DEC_K, sub, fresh, wh, wv);
        for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + kg * DEC_M * DEC_K + widx))[i] = wv[i];
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    uint g = 0;
    for (uint k0 = 0; k0 < K; k0 += KG * DEC_K) {
        const uint kn = k0 + (KG + kg) * DEC_K;
        const bool more = kn < K;
        if (more) {
            if constexpr (KG >= 2) { WHead h; wstage_16x128(wr, wtype, kn, sub, true, h, wv); }
            else wstage_16x128(wr, wtype, kn, sub, fresh, wh, wv);
        }
        if (on) {
            for (uint j = 0; j < KG && k0 + j * DEC_K < K; j++) {
                auto tA = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa + (g * KG + j) * DEC_M * DEC_K, dextents<int32_t, 2>(DEC_K, DEC_M));
                auto sx = tX.slice(k0 + j * DEC_K, 0);
                mm.run(sx, tA, cT);
            }
        }
        if (more) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + ((g ^ 1) * KG + kg) * DEC_M * DEC_K + widx))[i] = wv[i];
        threadgroup_barrier(mem_flags::mem_threadgroup);
        g ^= 1;
    }
}

template <uint WTYPE>
inline void wstage_spec_16x128(device const uchar * wr, uint rt_wtype, uint k0, uint sub, bool fresh, thread WHead & h, thread half4 * w) {
    if constexpr (WTYPE != 0) {
        wstage_16x128(wr, WTYPE, k0, sub, fresh, h, w);
    } else {
        wstage_16x128(wr, rt_wtype, k0, sub, fresh, h, w);
    }
}

// 8 KiB double-buffered sg4 ring with hoisted tensor_inline views and stateless WHead (compile-time WTYPE when != 0).
template <uint WTYPE, typename MM, typename TX, typename CT>
inline void dec_wring_sg4_spec(threadgroup half * sa, device const uchar * wr, uint rt_wtype, uint K, bool on, ushort tid,
                               thread MM & mm, thread TX & tX, thread CT & cT) {
    const uint sub = uint(tid) & 7u, widx = (uint(tid) & 127u) * 16u;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(DEC_K, DEC_M));
    auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa + DEC_M * DEC_K, dextents<int32_t, 2>(DEC_K, DEC_M));
    half4 wv[4];
    { WHead h0 = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, 0, sub, true, h0, wv); }
    for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + widx))[i] = wv[i];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    uint buf = 0;
    for (uint k0 = 0; k0 < K; k0 += DEC_K) {
        const bool more = k0 + DEC_K < K;
        if (more) { WHead hn = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, k0 + DEC_K, sub, true, hn, wv); }
        if (on) {
            auto sx = tX.slice(k0, 0);
            if (buf == 0) mm.run(sx, tA0, cT); else mm.run(sx, tA1, cT);
        }
        if (more) for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + (buf ^ 1u) * DEC_M * DEC_K + widx))[i] = wv[i];
        threadgroup_barrier(mem_flags::mem_threadgroup);
        buf ^= 1u;
    }
}

// 4 KiB single-tile sg4 ring (`sa[1][DEC_M * DEC_K]` = 4,096 B, matching `4 * 256` floats of `my_out`):
// prefetches next k-step's dequantized weights into registers `wv[4]` across `mm.run` while doubling
// threadgroup-memory residency ceiling from 4 TGs/core (512 threads) to 8 TGs/core (1,024 threads).
template <uint WTYPE, typename MM, typename TX, typename CT>
inline void dec_wring_4k(threadgroup half * sa, device const uchar * wr, uint rt_wtype, uint K, bool on, ushort tid,
                         thread MM & mm, thread TX & tX, thread CT & cT) {
    const uint sub = uint(tid) & 7u, widx = (uint(tid) & 127u) * 16u;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(DEC_K, DEC_M));
    half4 wv[4];
    { WHead h0 = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, 0, sub, true, h0, wv); }
    for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + widx))[i] = wv[i];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint k0 = 0; k0 < K; k0 += DEC_K) {
        const bool more = k0 + DEC_K < K;
        if (more) { WHead hn = {}; wstage_spec_16x128<WTYPE>(wr, rt_wtype, k0 + DEC_K, sub, true, hn, wv); }
        if (on) {
            auto sx = tX.slice(k0, 0);
            mm.run(sx, tA0, cT);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (more) {
            for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa + widx))[i] = wv[i];
            threadgroup_barrier(mem_flags::mem_threadgroup);
        }
    }
}

// RING4K (`INK_DEC_FIXED_COST`, the `_4k` names, sg4 only): one 4 KiB tile (eight threadgroups per core) and a segment
// lookup for every wtype, so a uniform multi-segment dispatch can use the specialised kernel; k-step order matches the
// 8 KiB ring, so the bits do too. Without it: the 8 KiB double-buffered ring, specialised kernels single-segment only.
template <int NSG, uint WTYPE = 0, bool RING4K = false>
kernel void k_gemm_dec_sg(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                          constant GemmHArgs & args [[buffer(5)]], uint2 tgq [[threadgroup_position_in_grid]],
                          ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]],
                          ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup half sa[((NSG == 4 && RING4K) ? 1 : 2 * (NSG / 4))][DEC_M * DEC_K];
    uint si = 0;
    if constexpr (WTYPE == 0 || RING4K) {
        while (si + 1 < args.nseg && tgq.y >= args.seg[si + 1].tile_start) si++;
    }
    constant HSeg & S = args.seg[si];
    const uint r0 = (tgq.y - S.tile_start) * DEC_M, t0 = (tgq.x * NSG + sg) * 16, K = S.K, T = args.T;
    const bool on = t0 < T;
    const int nt = on ? min(16, (int) (T - t0)) : 0;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(DEC_K, DEC_M));
    auto tX = tensor((device half *) (A + S.xh_off) + (ulong) (on ? t0 : 0) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
    DEC_SGOP(mm);
    auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
    const uint rr = (tid % 128) / 8;
    device const uchar * wr = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo) + (ulong) min(r0 + rr, S.nrows - 1) * S.row_bytes;
    if constexpr (NSG == 4 && RING4K) dec_wring_4k<WTYPE>(sa[0], wr, S.wtype, K, on, tid, mm, tX, cT);
    else if constexpr (NSG == 4 && WTYPE != 0) dec_wring_sg4_spec<WTYPE>(sa[0], wr, S.wtype, K, on, tid, mm, tX, cT);
    else dec_wring<NSG>(sa[0], wr, S.wtype, K, on, tid, mm, tX, cT);
    if (!on) return;
    if (!S.hout) {
        auto tC = tensor(A + S.out_off + (ulong) t0 * S.ldo + r0, dextents<int32_t, 2>(min(DEC_M, (int) (S.nrows - r0)), nt), array<int, 2>({1, (int) S.ldo}));
        cT.store(tC);
        return;
    }
    threadgroup float * my_out = ((threadgroup float *) sa) + uint(sg) * 256;
    auto tOut = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(my_out, dextents<int32_t, 2>(DEC_M, 16));
    cT.store(tOut);
    simdgroup_barrier(mem_flags::mem_threadgroup);
    device half * yo = (device half *) (A + S.out_off);
    const uint r4 = (lane % 4) * 4;
    for (uint pass = 0; pass < 2; ++pass) {
        const uint t = (lane / 4) + pass * 8;
        if (t < uint(nt) && r0 + r4 < S.nrows) {
            const float4 v = *(threadgroup const float4 *) (my_out + t * DEC_M + r4);
            *(device half4 *) (yo + (ulong) (t0 + t) * S.ldo + r0 + r4) = half4(v);
        }
    }
}
template [[host_name("k_gemm_dec_sg4")]]      kernel void k_gemm_dec_sg<4, 0>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q4k")]]  kernel void k_gemm_dec_sg<4, 12>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q6k")]]  kernel void k_gemm_dec_sg<4, 14>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q8_0")]] kernel void k_gemm_dec_sg<4, 8>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_bf16")]] kernel void k_gemm_dec_sg<4, 30>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_4k")]]      kernel void k_gemm_dec_sg<4, 0, true>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q4k_4k")]]  kernel void k_gemm_dec_sg<4, 12, true>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q6k_4k")]]  kernel void k_gemm_dec_sg<4, 14, true>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_q8_0_4k")]] kernel void k_gemm_dec_sg<4, 8, true>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg4_bf16_4k")]] kernel void k_gemm_dec_sg<4, 30, true>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_gemm_dec_sg8")]]      kernel void k_gemm_dec_sg<8, 0>(device const uchar *, device const uchar *, device float *, constant GemmHArgs &, uint2, ushort, ushort, ushort);

// Grid `(cb_blocks, ntiles, 1)`: row-blocks `cb = tgq.x` of one expert run contiguously before advancing to the next
// expert `tile_idx = tgq.y`, streaming sequential expert pages and keeping `xh[as0..as0+cnt]` hot in cache.
template <int NSG, bool ONE_BUF = false, uint WTYPE = 0, int SITU_MODE = -1>
kernel void k_moe_dec_sg(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmHArgs & a [[buffer(5)]],
                         uint2 tgq [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                         ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    constexpr uint NTILES_SA = ONE_BUF ? 1 : (2 * (NSG / 4));
    threadgroup half sa[NTILES_SA][DEC_M * DEC_K];
    const uint cb = tgq.x, tile_idx = tgq.y;
    if (tile_idx >= ((device const uint *) (A + a.ntiles_off))[0]) return;
    device const uint * tl = (device const uint *) (A + a.tiles_off) + tile_idx * 4;
    const uint e = tl[0], as0 = tl[1], cnt = tl[2], ts0 = sg * 16;
    const bool on = ts0 < cnt;
    const int nt = on ? min(16, (int) (cnt - ts0)) : 0;
    const uint K = a.K;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(DEC_K, DEC_M));
    auto tX = tensor((device half *) (A + a.xh_off) + (ulong) (as0 + (on ? ts0 : 0)) * K, dextents<int32_t, 2>((int) K, nt), array<int, 2>({1, (int) K}));
    DEC_SGOP(mm);
    auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
    const uint rr = (tid % 128) / 8;
    const bool is_situ = (SITU_MODE >= 0) ? (SITU_MODE != 0) : (a.situ != 0);
    const uint wrow = is_situ ? ((rr < 8) ? cb * 8 + rr : FF + cb * 8 + (rr - 8)) : cb * DEC_M + rr;
    device const uchar * wr = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes + (ulong) wrow * a.row_bytes;
    if constexpr (ONE_BUF) {
        dec_wring_4k<WTYPE>(sa[0], wr, a.wtype, K, on, tid, mm, tX, cT);
    } else if constexpr (NSG == 4 && WTYPE != 0) {
        dec_wring_sg4_spec<WTYPE>(sa[0], wr, a.wtype, K, on, tid, mm, tX, cT);
    } else {
        dec_wring<NSG>(sa[0], wr, a.wtype, K, on, tid, mm, tX, cT);
    }
    if (!on) return;
    const float gsc = (WTYPE == 0 && a.wtype == 200) ? gscale_at(W, a.gs_lo, a.gs_hi, e) : 1.0f;
    threadgroup float * my_out = ((threadgroup float *) sa) + uint(sg) * 256;
    auto tOut = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(my_out, dextents<int32_t, 2>(DEC_M, 16));
    cT.store(tOut);
    simdgroup_barrier(mem_flags::mem_threadgroup);
    if (!is_situ) {
        device half * yd = (device half *) (A + a.out_off);
        const uint r4 = (lane % 4) * 4;
        for (uint pass = 0; pass < 2; ++pass) {
            const uint t = (lane / 4) + pass * 8;
            if (t < uint(nt)) {
                const float4 v = *(threadgroup const float4 *) (my_out + t * DEC_M + r4) * gsc;
                *(device half4 *) (yd + (ulong) (as0 + ts0 + t) * a.ldo + cb * DEC_M + r4) = half4(v);
            }
        }
        return;
    }
    device half * act = (device half *) (A + a.out_off);
    const uint t = lane / 2, r4 = (lane & 1) * 4;
    if (t < uint(nt)) {
        const float4 gt = *(threadgroup const float4 *) (my_out + t * DEC_M + r4) * gsc;
        const float4 up = *(threadgroup const float4 *) (my_out + t * DEC_M + 8 + r4) * gsc;
        const float4 su = a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up;
        const float4 o = (A[a.aw_off + as0 + ts0 + t] * a.beta) * tanh(gt / a.beta) / (1.0f + exp(-gt)) * su;
        *(device half4 *) (act + (ulong) (as0 + ts0 + t) * FF + cb * 8 + r4) = half4(o);
    }
}
template [[host_name("k_moe_dec_sg8")]]            kernel void k_moe_dec_sg<8, false, 0,  -1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4")]]            kernel void k_moe_dec_sg<4, false, 0,  -1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k")]]         kernel void k_moe_dec_sg<4, true,  0,  -1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q4k")]]  kernel void k_moe_dec_sg<4, true,  12,  1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q5_0")]] kernel void k_moe_dec_sg<4, true,  6,   1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q8_0")]] kernel void k_moe_dec_sg<4, true,  8,   1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_gu_q6k")]]  kernel void k_moe_dec_sg<4, true,  14,  1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q4k")]]  kernel void k_moe_dec_sg<4, true,  12,  0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q5_0")]] kernel void k_moe_dec_sg<4, true,  6,   0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q8_0")]] kernel void k_moe_dec_sg<4, true,  8,   0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);
template [[host_name("k_moe_dec_sg4_4k_dn_q6k")]]  kernel void k_moe_dec_sg<4, true,  14,  0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort, ushort);

// ---- Register-fed MoE decode (`k_moe_dec_rg*`): each simdgroup computes one 16-row x K block of one expert tile on its
// own, dequantizing its share of every `16 rows x 128 k` weight step straight into the matmul's right-input cooperative
// tensor. No threadgroup staging and no barriers: a lane loads only the bytes of the 64 weights it owns (two rows x 32 k;
// for Q4_K and Q5_0 both nibbles of every byte it loads), the next step's raw bytes are in flight across the current
// step's dequant and matmuls, and occupancy is set by registers alone. Up to 32 tokens share one read of the weights
// (two 16-token accumulators); tiles of 33..64 tokens make a second pass for tokens 32..63. Each accumulator runs the
// same `matmul2d(16, 16, 128)` over the same k steps, in the same order, on the same dequantized halves as
// `k_moe_dec_sg4*`, and the epilogue is the same code, so the output is bit-identical
// (`decode_sg4_4k_and_specialized_kernels_match_generic_bit_for_bit`).
// Right-input layout of `matmul2d(16, 16, 128, false, true)` at simdgroup scope on M5 (read on an M5 Pro with
// `get_multidimensional_index`; any other layout fails the parity test): lane L holds rows r0 = ((L >> 1) & 3) | ((L >> 4) << 2) and
// r0 + 8 at k = kb + 16 m + i, kb = (L & 1) * 4 + ((L >> 3) & 1) * 8, m = 0..7, i = 0..3; element m * 8 + s * 4 + i is
// row r0 + 8 s. For gate/up, row r0 of the block is gate row cb * 8 + r0 and row r0 + 8 the matching up row.
struct RgRaw { uint q[2][8]; half d[2][4]; };

// Raw bytes of one k step for the lane's two rows. Q4_K: q[s][0..3] the qs words at kb, kb + 16, kb + 32, kb + 48 of
// the step's 64 qs bytes, q[s][4] d|dmin, q[s][5..7] the 12 scale bytes. Q8_0 (4 blocks of 32 per step): q[s][2p] and
// q[s][2p + 1] block p's qs bytes kb..kb+3 and kb+16..kb+19, d[s][p] its scale. Q5_0: q[s][2p] block p's qs bytes
// kb..kb+3 (low nibbles: weights kb+i, high: 16+kb+i), q[s][2p + 1] its qh word, d[s][p] its scale.
template <uint WTYPE>
inline void rg_load(device const uchar * w0, device const uchar * w1, uint k0, uint kb, thread RgRaw & r) {
    for (uint s = 0; s < 2; s++) {
        device const uchar * wr = s ? w1 : w0;
        if constexpr (WTYPE == 12) {
            device const block_q4_K * b = (device const block_q4_K *) wr + k0 / 256;
            device const uint * q = (device const uint *) (b->qs + ((k0 % 256) / 128) * 64 + kb);
            r.q[s][0] = q[0]; r.q[s][1] = q[4]; r.q[s][2] = q[8]; r.q[s][3] = q[12];
            device const uint * hd = (device const uint *) b;
            r.q[s][4] = hd[0]; r.q[s][5] = hd[1]; r.q[s][6] = hd[2]; r.q[s][7] = hd[3];
        } else if constexpr (WTYPE == 8) {
            for (uint p = 0; p < 4; p++) {
                device const block_q8_0 * b = (device const block_q8_0 *) wr + k0 / 32 + p;
                device const ushort * q = (device const ushort *) (b->qs + kb);
                r.q[s][2 * p] = uint(q[0]) | (uint(q[1]) << 16);
                r.q[s][2 * p + 1] = uint(q[8]) | (uint(q[9]) << 16);
                r.d[s][p] = b->d;
            }
        } else {
            static_assert(WTYPE == 6, "k_moe_dec_rg: Q4_K, Q8_0 or Q5_0");
            for (uint p = 0; p < 4; p++) {
                device const block_q5_0 * b = (device const block_q5_0 *) wr + k0 / 32 + p;
                device const ushort * q = (device const ushort *) (b->qs + kb);
                device const ushort * qh = (device const ushort *) b->qh;
                r.q[s][2 * p] = uint(q[0]) | (uint(q[1]) << 16);
                r.q[s][2 * p + 1] = uint(qh[0]) | (uint(qh[1]) << 16);
                r.d[s][p] = b->d;
            }
        }
    }
}

// Dequantize the raw step into the right-input cooperative tensor, with `wstage_16x128`'s arithmetic per weight.
template <uint WTYPE, typename RT>
inline void rg_deq(thread const RgRaw & r, uint k0, uint kb, thread RT & rT) {
    for (uint s = 0; s < 2; s++) {
        for (uint p = 0; p < 4; p++) {
            for (uint u = 0; u < 2; u++) {
                half4 w;
                if constexpr (WTYPE == 12) {
                    const uint j = ((k0 % 256) / 128) * 4 + p, s0 = r.q[s][5], s1 = r.q[s][6], s2 = r.q[s][7];
                    uint sc, mn;
                    if (j < 4) { sc = (s0 >> (8 * j)) & 63; mn = (s1 >> (8 * j)) & 63; }
                    else {
                        const uint hi = (s2 >> (8 * (j - 4))) & 0xFF;
                        sc = (hi & 0xF) | (((s0 >> (8 * (j - 4) + 6)) & 3) << 4);
                        mn = (hi >> 4)  | (((s1 >> (8 * (j - 4) + 6)) & 3) << 4);
                    }
                    const half2 dm = as_type<half2>(r.q[s][4]);
                    const float df = float(dm.x) * float(sc), mf = float(dm.y) * float(mn);
                    // sub-block j = 4h + p: qs group 2h + p / 2, nibble p & 1; m = 2p + u reads kb + 16 u
                    const uint v = (r.q[s][(p / 2) * 2 + u] >> ((p & 1) * 4)) & 0x0F0F0F0Fu;
                    w = half4(fma(float4(as_type<uchar4>(v)), df, -mf));
                } else if constexpr (WTYPE == 8) {
                    w = half4(as_type<char4>(r.q[s][2 * p + u])) * r.d[s][p];
                } else {
                    // weights 16u + kb + i: nibble u of qs byte kb + i, fifth bit qh bit 16u + kb + i
                    const uint n = (r.q[s][2 * p] >> (u * 4)) & 0x0F0F0F0Fu;
                    const uint h5 = (((r.q[s][2 * p + 1] >> (u * 16 + kb)) & 0xFu) * 0x00204081u) & 0x01010101u;
                    w = half4(as_type<char4>(n | ((0x01010101u - h5) * 0xF0u))) * r.d[s][p];
                }
                const uint e = (2 * p + u) * 8 + s * 4;
                rT[e] = w.x; rT[e + 1] = w.y; rT[e + 2] = w.z; rT[e + 3] = w.w;
            }
        }
    }
}

template <int NSG, uint WTYPE, int SITU>
kernel void k_moe_dec_rg(device const uchar * W [[buffer(0)]], device float * A [[buffer(2)]], constant MoeGemmHArgs & a [[buffer(5)]],
                         uint2 tgq [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
                         ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup float outs[NSG][DEC_M * 16];
    const uint cb = tgq.x * NSG + sg, tile_idx = tgq.y;
    if (tile_idx >= ((device const uint *) (A + a.ntiles_off))[0]) return;
    device const uint * tl = (device const uint *) (A + a.tiles_off) + tile_idx * 4;
    const uint e = tl[0], as0 = tl[1], cnt = tl[2], K = a.K;
    const uint r0 = ((lane >> 1) & 3) | ((lane >> 4) << 2), kb = (lane & 1) * 4 + ((lane >> 3) & 1) * 8;
    const uint w0row = SITU ? cb * 8 + r0 : cb * DEC_M + r0, w1row = SITU ? FF + cb * 8 + r0 : cb * DEC_M + r0 + 8;
    device const uchar * we = W + (ulong(a.w_hi) << 32 | a.w_lo) + (ulong) e * a.expert_bytes;
    device const uchar * w0 = we + (ulong) w0row * a.row_bytes;
    device const uchar * w1 = we + (ulong) w1row * a.row_bytes;
    threadgroup float * my_out = outs[sg];
    device half * xh = (device half *) (A + a.xh_off);
    for (uint g0 = 0; g0 < cnt; g0 += 32) {
        const int nt0 = min(16, (int) (cnt - g0)), nt1 = max(0, min(16, (int) (cnt - g0 - 16)));
        auto tX0 = tensor(xh + (ulong) (as0 + g0) * K, dextents<int32_t, 2>((int) K, nt0), array<int, 2>({1, (int) K}));
        auto tX1 = tensor(xh + (ulong) (as0 + g0 + (nt1 ? 16 : 0)) * K, dextents<int32_t, 2>((int) K, nt1 ? nt1 : 1), array<int, 2>({1, (int) K}));
        DEC_SGOP(mm);
        auto rT = mm.template get_right_input_cooperative_tensor<half, half, float>();
        auto cT0 = mm.template get_destination_cooperative_tensor<decltype(tX0), decltype(rT), float>();
        auto cT1 = mm.template get_destination_cooperative_tensor<decltype(tX1), decltype(rT), float>();
        RgRaw raw;
        rg_load<WTYPE>(w0, w1, 0, kb, raw);
        for (uint k0 = 0; k0 < K; k0 += DEC_K) {
            rg_deq<WTYPE>(raw, k0, kb, rT);
            if (k0 + DEC_K < K) rg_load<WTYPE>(w0, w1, k0 + DEC_K, kb, raw);
            auto sx0 = tX0.slice(k0, 0);
            mm.run(sx0, rT, cT0);
            if (nt1) { auto sx1 = tX1.slice(k0, 0); mm.run(sx1, rT, cT1); }
        }
        for (uint q = 0; q < 2; q++) {
            const int nt = q ? nt1 : nt0;
            if (nt == 0) break;
            const uint ts0 = g0 + q * 16;
            auto tOut = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(my_out, dextents<int32_t, 2>(DEC_M, 16));
            if (q) cT1.store(tOut); else cT0.store(tOut);
            simdgroup_barrier(mem_flags::mem_threadgroup);
            if (!SITU) {
                device half * yd = (device half *) (A + a.out_off);
                const uint r4 = (lane % 4) * 4;
                for (uint pass = 0; pass < 2; ++pass) {
                    const uint t = (lane / 4) + pass * 8;
                    if (t < uint(nt)) {
                        const float4 v = *(threadgroup const float4 *) (my_out + t * DEC_M + r4);
                        *(device half4 *) (yd + (ulong) (as0 + ts0 + t) * a.ldo + cb * DEC_M + r4) = half4(v);
                    }
                }
            } else {
                device half * act = (device half *) (A + a.out_off);
                const uint t = lane / 2, r4 = (lane & 1) * 4;
                if (t < uint(nt)) {
                    const float4 gt = *(threadgroup const float4 *) (my_out + t * DEC_M + r4);
                    const float4 up = *(threadgroup const float4 *) (my_out + t * DEC_M + 8 + r4);
                    const float4 su = a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up;
                    const float4 o = (A[a.aw_off + as0 + ts0 + t] * a.beta) * tanh(gt / a.beta) / (1.0f + exp(-gt)) * su;
                    *(device half4 *) (act + (ulong) (as0 + ts0 + t) * FF + cb * 8 + r4) = half4(o);
                }
            }
            simdgroup_barrier(mem_flags::mem_threadgroup);
        }
    }
}
#define MOE_RG(NSG, ty, WT) \
    template [[host_name("k_moe_dec_rg" #NSG "_gu_" ty)]] kernel void k_moe_dec_rg<NSG, WT, 1>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort); \
    template [[host_name("k_moe_dec_rg" #NSG "_dn_" ty)]] kernel void k_moe_dec_rg<NSG, WT, 0>(device const uchar *, device float *, constant MoeGemmHArgs &, uint2, ushort, ushort);
MOE_RG(1, "q4k", 12) MOE_RG(1, "q8_0", 8) MOE_RG(1, "q5_0", 6)
MOE_RG(2, "q4k", 12) MOE_RG(2, "q8_0", 8) MOE_RG(2, "q5_0", 6)
MOE_RG(4, "q4k", 12) MOE_RG(4, "q8_0", 8) MOE_RG(4, "q5_0", 6)

#pragma clang fp contract(off) reassociate(off)
template <int M>
inline void bf16_dec_batch(device const uchar * const * wp, constant HSeg & S, device float * A,
                           device const half * xbase, uint t0, uint r0, ushort lane) {
    float sumf[M][DEC_NR];
    #pragma unroll
    for (int m = 0; m < M; ++m) { sumf[m][0] = 0.0f; sumf[m][1] = 0.0f; }
    for (int i = int(lane) * 8; i < int(S.K); i += 256) {
        half4 xal[M], xbl[M];
        #pragma unroll
        for (int m = 0; m < M; ++m) {
            device const half * xm = xbase + (ulong) (t0 + uint(m)) * S.K + i;
            xal[m] = *(device const half4 *) xm;
            xbl[m] = *(device const half4 *) (xm + 4);
        }
        #pragma unroll
        for (int r = 0; r < DEC_NR; ++r) {
            const ushort4 a = *(device const ushort4 *) (wp[r] + 2 * i);
            const ushort4 b = *(device const ushort4 *) (wp[r] + 2 * i + 8);
            const float4 wa = float4(bf16f(a.x), bf16f(a.y), bf16f(a.z), bf16f(a.w));
            const float4 wb = float4(bf16f(b.x), bf16f(b.y), bf16f(b.z), bf16f(b.w));
            #pragma unroll
            for (int m = 0; m < M; ++m) {
                const float4 xa = float4(xal[m]), xb = float4(xbl[m]);
                const float p0 = (xa.x * wa.x + xa.y * wa.y) + (xa.z * wa.z + xa.w * wa.w);
                const float p1 = (xb.x * wb.x + xb.y * wb.y) + (xb.z * wb.z + xb.w * wb.w);
                sumf[m][r] += p0 + p1;
            }
        }
    }
    #pragma unroll
    for (int m = 0; m < M; ++m) {
        const float y0 = simd_sum(sumf[m][0]);
        const float y1 = simd_sum(sumf[m][1]);
        if (lane == 0) {
            const uint t = t0 + uint(m);
            if (S.hout) {
                device half * yo = (device half *) (A + S.out_off) + (ulong) t * S.ldo + r0;
                if (r0 + 1 < S.nrows) *(device half2 *) yo = half2(half(y0), half(y1));
                else if (r0 < S.nrows) yo[0] = half(y0);
            } else {
                device float * yo = A + S.out_off + (ulong) t * S.ldo + r0;
                if (r0 + 1 < S.nrows) *(device float2 *) yo = float2(y0, y1);
                else if (r0 < S.nrows) yo[0] = y0;
            }
        }
    }
}

kernel void k_gemm_bf16_dec(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                            constant GemmHArgs & args [[buffer(5)]], uint2 tgq [[threadgroup_position_in_grid]],
                            ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    uint si = 0;
    while (si + 1 < args.nseg && tgq.y >= args.seg[si + 1].tile_start) si++;
    constant HSeg & S = args.seg[si];
    const uint r0 = (tgq.y - S.tile_start) * (4 * DEC_NR) + uint(sg) * DEC_NR;
    if (r0 >= S.nrows) return;
    const uint t_base = tgq.x * 16;
    if (t_base >= args.T) return;
    const uint nt = min(16u, args.T - t_base);
    device const uchar * wbase = (S.wsrc ? PB : W) + (ulong(S.w_hi) << 32 | S.w_lo);
    device const uchar * wp[DEC_NR] = {
        wbase + (ulong) r0 * S.row_bytes,
        wbase + (ulong) min(r0 + 1, S.nrows - 1) * S.row_bytes
    };
    device const half * xbase = (device const half *) (A + S.xh_off);
    uint u0 = 0;
    for (; u0 + 4 <= nt; u0 += 4) bf16_dec_batch<4>(wp, S, A, xbase, t_base + u0, r0, lane);
    if (u0 + 2 <= nt) { bf16_dec_batch<2>(wp, S, A, xbase, t_base + u0, r0, lane); u0 += 2; }
    if (u0 < nt) bf16_dec_batch<1>(wp, S, A, xbase, t_base + u0, r0, lane);
}
#pragma clang fp contract(fast) reassociate(on)

// ---- loop controllers, gain/forget GEMM with the apply fused into the epilogue (fp16 path).
// TG = (128-token tile, job, 32-channel block): rows = 32 gain + 32 forget rows of the block, K = 64 (the controller state g, half).
// Every thread owns matching gain and forget accumulators, so raw = u - tanh(F.g)*u + tanh(G.g)*m is formed in registers and
// written once; the gain / forget pre-activations never touch memory. grid (T/128, njobs * E/32), 256 threads.
struct CtrlGfJob { uint gain_w, forget_w, gh_off, u_off, m_off, raw_off, pad0, pad1; };
struct CtrlGfArgs { uint T, njobs, pad0, pad1; CtrlGfJob job[4]; };
kernel void k_ctrl_gf(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant CtrlGfArgs & a [[buffer(5)]],
                      uint2 tgq [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
    threadgroup half sa[2][HB_M * HB_K];
    constant CtrlGfJob & J = a.job[tgq.y / (E / 32)];
    const uint cb = tgq.y % (E / 32), t0 = (tgq.x * 8 + sg) * 16;
    const bool on = t0 < a.T;
    const int nt = on ? min(16, (int) (a.T - t0)) : 0;
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[0], dextents<int32_t, 2>(HB_K, HB_M));
    auto tA1 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa[1], dextents<int32_t, 2>(HB_K, HB_M));
    auto tX = tensor((device half *) (A + J.gh_off) + (ulong) (on ? t0 : 0) * 64, dextents<int32_t, 2>(64, nt), array<int, 2>({1, 64}));
    SGOP(mm);
    auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
    const uint widx = tid * 16, rr = widx / HB_K, wkk = widx % HB_K;
    device const uchar * wrow = PB + (rr < 32 ? J.gain_w : J.forget_w) + (cb * 32 + (rr & 31)) * 128;
    if (tid < 128) {
        half wv[16];
        deq16(wrow, 30, wkk, wv);
        for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[0] + widx))[i] = ((thread half4 *) wv)[i];
        deq16(wrow, 30, 32 + wkk, wv);
        for (int i = 0; i < 4; i++) ((threadgroup half4 *) (sa[1] + widx))[i] = ((thread half4 *) wv)[i];
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (!on) return;
    { auto sx = tX.slice(0, 0); mm.run(sx, tA0, cT); }
    { auto sx = tX.slice(32, 0); mm.run(sx, tA1, cT); }
    for (short q = 0; q < 4; ++q) {
        const auto ix = cT.get_multidimensional_index(4 * q);
        const uint r = ix[0], t = t0 + ix[1];
        if (t < a.T) {
            const uint o = t * E + cb * 32 + r;
            const float4 gn = float4(cT[4 * q], cT[4 * q + 1], cT[4 * q + 2], cT[4 * q + 3]);
            const float4 fg = float4(cT[4 * q + 16], cT[4 * q + 17], cT[4 * q + 18], cT[4 * q + 19]);
            const float4 u = *(device const float4 *) (A + J.u_off + o), m = *(device const float4 *) (A + J.m_off + o);
            *(device float4 *) (A + J.raw_off + o) = u - tanh(fg) * u + tanh(gn) * m;
        }
    }
}
// accumulator layout probe for the kernels above: out[tid * 64 + i] = (row << 16 | token) of element i, out[tid * 64 + 63] = capacity
kernel void k_layout_sg(device float * A [[buffer(2)]], constant uint & out_off [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup half sa[HB_M * HB_K];
    auto tA0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(HB_K, HB_M));
    auto tX = tensor((device half *) A, dextents<int32_t, 2>(HB_K, 16), array<int, 2>({1, HB_K}));
    SGOP(mm);
    auto cT = mm.template get_destination_cooperative_tensor<decltype(tX), decltype(tA0), float>();
    device int * o = (device int *) (A + out_off) + tid * 64;
    for (short i = 0; i < cT.get_capacity() && i < 63; ++i) {
        if (cT.is_valid_element(i)) { const auto ix = cT.get_multidimensional_index(i); o[i] = (ix[0] << 16) | ix[1]; } else o[i] = -1;
    }
    o[63] = cT.get_capacity();
}
#endif // NO_MPP

// =============================================================================================
// Layer 3 block-addressed prefill K/V write and causal attention kernels.
// Identical arithmetic to `k_kvprep_b`, `k_attn_b`, `k_attn_bt`, `k_attn_h`, replacing
// contiguous cache addressing with 64-bit per-lane block-table lookups (`BT[pos >> 6]`).
// `a.k_base` carries the pass index within the pool kind (0..40 window, 0..8 full).

#pragma clang fp contract(off) reassociate(off)
kernel void k_kvprep_b_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                           device uchar * KV0 [[buffer(3)]], device float * CS [[buffer(4)]],
                           constant KvPrepArgs & a [[buffer(5)]], device const ulong * BT [[buffer(8)]],
                           device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
                           uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                           ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup float red[4][8];
    const uint t = tgp.x, g = tgp.y, pos = a.p0 + t;
    const bool is_full = (a.is_full & 1u) != 0u;
    const float tau = is_full ? 1.0f + a.log_alpha * log(max(1.0f, float(pos + 1) / a.log_floor)) : 1.0f;
    device const float * qclip = (device const float *) (PB + a.qclip_w);
    float q[3];
    for (int h = 0; h < 3; h++) {
        const uint H = g * 3 + h, qi = t * (NH * HD) + H * HD + tid;
        q[h] = ((a.qhalf & 2) ? float(((device const half *) (A + a.q_off))[qi]) : A[a.q_off + qi]) * qclip[H * HD + tid];
    }
    const uint c = g * HD + tid;
    float kv[2];
    const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
    for (int which = 0; which < 2; which++) {
        const uint xo = which == 0 ? a.k_off : a.v_off;
        device const float * hh = CS + a.cs_off + (which * NKV * HD + c) * 3;
        device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
        float x[4];
        for (int j = 0; j < 4; j++) { const int tt = int(t) - 3 + j; x[j] = tt >= 0 ? A[xo + tt * (NKV * HD) + c] : hh[3 + tt]; }
        float acc = w[0] * x[0] + w[1] * x[1] + w[2] * x[2] + w[3] * x[3];
        const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
        if (dyn >= 0) { device const float * tp = A + dyn + t * 32 + g * 4; acc += tp[0] * x[3] + tp[1] * x[2] + tp[2] * x[1] + tp[3] * x[0]; }
        kv[which] = (x[3] + acc) * scl;
    }
    float r = 0;
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        r = A[a.r_off + t * (NH * NREL) + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
    }
    float rn = r * r;
    rn += simd_shuffle_xor(rn, 1); rn += simd_shuffle_xor(rn, 2); rn += simd_shuffle_xor(rn, 4); rn += simd_shuffle_xor(rn, 8);
    {
        const float s0 = simd_sum(q[0] * q[0]), s1 = simd_sum(q[1] * q[1]), s2 = simd_sum(q[2] * q[2]);
        const float s3 = simd_sum(kv[0] * kv[0]), s4 = simd_sum(kv[1] * kv[1]);
        const float s5 = simd_max(fabs(kv[0])), s6 = simd_max(fabs(kv[1]));
        if (lane == 0) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; red[sg][5] = s5; red[sg][6] = s6; }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    float tot[5];
    for (int i = 0; i < 5; i++) tot[i] = red[0][i] + red[1][i] + red[2][i] + red[3][i];
#ifdef KV4
    threadgroup float wht_sh[128];
    const uint slot = a.slot_idx;
    const float sk_rad = kv4_rademacher(slot * 2u, g, tid);
    const float sv_rad = kv4_rademacher(slot * 2u + 1u, g, tid);
    const float mu_r = kv4_finite_or_zero(float(((device const half *) (PB + KV4_DC_OFF))[(slot * NKV + g) * HD + tid]));
    for (int h = 0; h < 3; h++) {
        const uint H = g * 3 + h;
        const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
        const float qr = wht128_tg(sk_rad * (q[h] * f), tid, sg, lane, wht_sh);
        const float qstored = (a.qhalf & 1) ? float(half(qr)) : qr;
        if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + H * HD + tid] = half(qr);
        else A[a.qp_off + t * (NH * HD) + H * HD + tid] = qr;
        const float dc_b = kv4_finite_or_zero(kv4_reduce128(qstored * mu_r, sg, lane, wht_sh));
        if (tid == 0) A[a.sink_off + t * NH + H] -= dc_b;
    }
#else
    for (int h = 0; h < 3; h++) {
        const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
        if (a.qhalf & 1) ((device half *) (A + a.qp_off))[t * (NH * HD) + (g * 3 + h) * HD + tid] = half(q[h] * f);
        else A[a.qp_off + t * (NH * HD) + (g * 3 + h) * HD + tid] = q[h] * f;
    }
#endif
    if (tid < 48) A[a.rp_off + t * (NH * NREL) + (g * 3 + tid / 16) * NREL + tid % 16] = r * clamp(REL_CLIP / (sqrt(rn) + 1e-6f), 0.0f, 1.0f) * tau;
    const float kf = clamp(QK_CLIP / (sqrt(tot[3]) + 1e-6f), 0.0f, 1.0f), vf = rsqrt(tot[4] / HD + 1e-6f);
    const float k = kv[0] * kf, v = kv[1] * vf;
    const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
    const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    device kv_t * kp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * KV_ROW_STEP;
    device kv_t * vp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * KV_ROW_STEP;
#ifdef KV4
    const float k_rot = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
    const float v_rot = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
    (void) kv4_pack_row(k_rot, tid, sg, lane, wht_sh, kp, true);
    (void) kv4_pack_row(v_rot, tid, sg, lane, wht_sh, vp, true);
#elif defined(KV8)
    const uint ck = kv_code(max(max(red[0][5], red[1][5]), max(red[2][5], red[3][5])) * kf);
    const uint cv = kv_code(max(max(red[0][6], red[1][6]), max(red[2][6], red[3][6])) * vf);
    kp[tid] = (kv_t) (int) kv_quant(k, kv_scale(ck), ck, tid);
    vp[tid] = (kv_t) (int) kv_quant(v, kv_scale(cv), cv, tid);
#else
    kp[tid] = half(k);
    vp[tid] = half(v);
#endif
}
#pragma clang fp contract(fast) reassociate(on)

kernel void k_attn_b_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                         device uchar * KV0 [[buffer(3)]], constant AttnBArgs & a [[buffer(5)]],
                         device const ulong * BT [[buffer(8)]],
                         device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
                         uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
    threadgroup half qs[AQT * 3][HD];
    threadgroup half ks[32][HD];
    threadgroup half vs[32][HD];
    threadgroup float ss[AQT * 3][33];
    threadgroup float rs[AQT * 3][NREL];
    threadgroup float sk[AQT * 3];
    const uint g = tgp.y, t0 = tgp.x * AQT;
    const uint nq = min((uint) AQT, a.T - t0);
    const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    for (uint i = tid; i < AQT * 3 * HD; i += 128) {
        const uint row = i / HD, d = i % HD, tt = row / 3, h = row % 3;
        qs[row][d] = tt < nq ? half(A[a.qp_off + (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + d]) : half(0);
    }
    if (tid < AQT * 3 * 4) {
        const uint row = tid / 4, part = tid % 4, tt = row / 3, h = row % 3;
        for (int i = 0; i < 4; i++) rs[row][part * 4 + i] = tt < nq ? A[a.rp_off + (t0 + tt) * (NH * NREL) + (g * 3 + h) * NREL + part * 4 + i] : 0.0f;
    }
    if (tid < AQT * 3) { const uint tt = tid / 3, h = tid % 3; sk[tid] = tt < nq ? A[a.sink_off + (t0 + tt) * NH + g * 3 + h] : 0.0f; }
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint plast = a.p0 + t0 + nq - 1;
    const uint pfirst = a.p0 + t0;
    const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
    const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
    const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) & ~31u) : 0u;
    const uint kstart = ((a.window > 0 && pfirst + 1 > a.window) ? (pfirst + 1 - a.window) : 0u) & ~31u;
    float o[AQT * 3];
    for (int r = 0; r < AQT * 3; r++) o[r] = 0;
    float m[AQT * 3], l[AQT * 3];
    for (int r = 0; r < AQT * 3; r++) { m[r] = 0.0f; l[r] = 1.0f; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 32u && recent_kstart > 64u) ? recent_kstart : (kc + 32u)) {
        const uint nk = min(32u, plast + 1 - kc);
        for (uint i = tid; i < 32 * HD / 4; i += 128) {
            const uint j = i / (HD / 4), d4 = i % (HD / 4);
            const uint p = kc + min(j, nk - 1);
            device const kv_t * krow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, koff) + (p & KV_BLK_MASK) * KV_ROW_STEP;
            device const kv_t * vrow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, voff) + (p & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
            ((threadgroup half4 *) ks[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) krow->qs)[d4]) * float(krow->sc));
            ((threadgroup half4 *) vs[j])[d4] = half4(kv4_u16_to_f4(((device const ushort *) vrow->qs)[d4]) * float(vrow->sc));
#elif defined(KV8)
            ((threadgroup half4 *) ks[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (krow + d4 * 4))) * kv_vscale(krow));
            ((threadgroup half4 *) vs[j])[d4] = half4(float4(char4(*(device const packed_char4 *) (vrow + d4 * 4))) * kv_vscale(vrow));
#else
            ((threadgroup half4 *) ks[j])[d4] = *(device const half4 *) (krow + d4 * 4);
            ((threadgroup half4 *) vs[j])[d4] = *(device const half4 *) (vrow + d4 * 4);
#endif
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (uint i = tid; i < AQT * 3 * 32; i += 128) {
            const uint row = i / 32, j = i % 32, tt = row / 3;
            const uint qp = a.p0 + t0 + tt, kp = kc + j;
            float s = -INFINITY;
            if (j < nk && tt < nq && kp <= qp && (a.window == 0 || qp - kp < a.window) && (!pruned || kp < 64u || qp - kp < recent_win)) {
                float acc = 0;
                for (int d4 = 0; d4 < HD / 4; d4++)
                    acc += dot(float4(((threadgroup const half4 *) qs[row])[d4]), float4(((threadgroup const half4 *) ks[j])[d4]));
                const uint dist = qp - kp;
                if (dist < EXT) for (int r = 0; r < NREL; r++) acc += rs[row][r] * relb[dist * NREL + r];
                s = acc - sk[row];
            }
            ss[row][j] = s;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int r = 0; r < AQT * 3; r++) {
            const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
            const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
            if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
            float mx = m[r];
            for (uint j = 0; j < jend; j++) mx = max(mx, ss[r][j]);
            const float f = exp(m[r] - mx);
            l[r] *= f; o[r] *= f; m[r] = mx;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (uint i = tid; i < AQT * 3 * 32; i += 128) { const uint row = i / 32, j = i % 32; ss[row][j] = j < nk ? exp(ss[row][j] - m[row]) : 0.0f; }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (int r = 0; r < AQT * 3; r++) {
            const uint tt = uint(r) / 3u, qp = a.p0 + t0 + tt;
            const uint jend = (tt < nq && kc <= qp) ? min(32u, qp - kc + 1u) : 0u;
            if (jend == 0u || (a.window > 0 && qp >= kc + jend - 1u + a.window)) continue;
            float acc = 0, ls = 0;
            for (uint j = 0; j < jend; j++) { const float p = ss[r][j]; ls += p; acc += p * float(vs[j][tid]); }
            l[r] += ls; o[r] += acc;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    for (int r = 0; r < AQT * 3; r++) {
        const uint tt = r / 3, h = r % 3;
        if (tt < nq) {
            const uint i = (t0 + tt) * (NH * HD) + (g * 3 + h) * HD + tid;
            A[a.out_off + i] = o[r] / l[r] * sigm(A[a.gate_off + i]);
        }
    }
}

#ifndef NO_MPP
kernel void k_attn_bt_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                          device uchar * KV0 [[buffer(3)]], constant AttnBArgs & a [[buffer(5)]],
                          device const ulong * BT [[buffer(8)]],
                          device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
                          uint2 tgp [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], ushort sgitg [[simdgroup_index_in_threadgroup]]) {
    const uint h = tgp.y, g = h / 3, t0 = tgp.x * FQ;
    const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
#ifdef KV4
    device kv_t * kptr0 = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, 0, koff);
    (void) PB; (void) A; (void) t0; (void) voff; (void) kptr0; (void) tiisg; (void) sgitg;
#else
    threadgroup float region0[FQ * HD];
    threadgroup half sp[FQ * FCK];
    threadgroup float sr[FQ];
    threadgroup float rsh[FQ][NREL];
    threadgroup float sk[FQ];
    threadgroup half * sq = (threadgroup half *) region0;
    threadgroup float * ss = region0 + FQ * HD / 2;
    const ushort tid = sgitg * 32 + tiisg;
    const uint nq = min((uint) FQ, a.T - t0);
    for (uint i = tid; i < FQ * HD / 4; i += FNSG * 32) {
        const uint row = i / (HD / 4), d4 = i % (HD / 4);
        float4 q = 0;
        if (row < nq) q = *(device const float4 *) (A + a.qp_off + (t0 + row) * (NH * HD) + h * HD + d4 * 4);
        ((threadgroup half4 *) sq)[i] = half4(q);
    }
    for (uint i = tid; i < FQ * NREL; i += FNSG * 32) {
        const uint row = i / NREL, r = i % NREL;
        rsh[row][r] = row < nq ? A[a.rp_off + (t0 + row) * (NH * NREL) + h * NREL + r] : 0.0f;
    }
    if (tid < FQ) sk[tid] = tid < nq ? A[a.sink_off + (t0 + tid) * NH + h] : 0.0f;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    auto tq = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sq, dextents<int32_t, 2>(HD, FQ));
    auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(FCK, FQ));
    auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(FCK, FQ));
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, FCK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
                              execution_simdgroups<FNSG>> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(FQ, HD, FCK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
                              execution_simdgroups<FNSG>> mm_pv;
    auto tv0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
    auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
    for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] = 0.0f;

    constexpr short NQR = FQ / FNSG;
    float M[NQR], S[NQR];
    for (short jj = 0; jj < NQR; jj++) { M[jj] = 0.0f; S[jj] = 2980.9579870417283f; }
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
    const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
    const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
    const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / FCK * FCK) : 0u;
    uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
    kstart = kstart / FCK * FCK;
    for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > FCK) ? recent_kstart : (kc + FCK)) {
        const uint blk = kc >> 6;
        device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
        device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff);
        auto tk = tensor(kptr, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
        mm_qk.run(tq, tk, ts);
        threadgroup_barrier(mem_flags::mem_threadgroup);
#ifdef KV8
        float ksc[FCK / 32], vsc[FCK / 32];
        for (short ii = 0; ii < FCK / 32; ii++) { ksc[ii] = kv_vscale(kptr + (ii * 32 + tiisg) * HD); vsc[ii] = kv_vscale(vptr + (ii * 32 + tiisg) * HD); }
#endif
        for (short jj = 0; jj < NQR; jj++) {
            const uint j = jj * FNSG + sgitg;
            const uint qp = a.p0 + t0 + j;
            float s[FCK / 32];
            float m = M[jj];
            for (short ii = 0; ii < FCK / 32; ii++) {
                const uint col = ii * 32 + tiisg, kp = kc + col;
                const bool valid = j < nq && kp <= qp && (a.window == 0 || qp - kp < a.window)
                    && (!pruned || kp < 64u || qp - kp < recent_win);
                float v = -INFINITY;
                if (valid) {
#ifdef KV8
                    v = ss[j * FCK + col] * ksc[ii] - sk[j];
#else
                    v = ss[j * FCK + col] - sk[j];
#endif
                    const uint dist = qp - kp;
                    if (dist < EXT) {
                        device const float4 * b4 = (device const float4 *) (relb + dist * NREL);
                        threadgroup const float4 * r4 = (threadgroup const float4 *) rsh[j];
                        v += dot(r4[0], b4[0]) + dot(r4[1], b4[1]) + dot(r4[2], b4[2]) + dot(r4[3], b4[3]);
                    }
                }
                s[ii] = v;
                m = max(m, v);
            }
            m = simd_max(m);
            const float ms = exp(M[jj] - m);
            M[jj] = m;
            float sum = 0;
            for (short ii = 0; ii < FCK / 32; ii++) {
                const half p = half(exp(s[ii] - m + 8.0f));
#ifdef KV8
                sp[j * FCK + ii * 32 + tiisg] = half(float(p) * vsc[ii]);
#else
                sp[j * FCK + ii * 32 + tiisg] = p;
#endif
                sum += float(p);
            }
            S[jj] = S[jj] * ms + simd_sum(sum);
            if (tiisg == 0) sr[j] = ms;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
        auto tv = tensor(vptr, dextents<int32_t, 2>(HD, FCK), array<int, 2>({1, HD}));
        mm_pv.run(tp, tv, co);
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    for (short jj = 0; jj < NQR; jj++) { const uint j = jj * FNSG + sgitg; if (tiisg == 0) sr[j] = 1.0f / S[jj]; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (short i = 0; i < co.get_capacity(); ++i) if (co.is_valid_element(i)) co[i] *= sr[co.get_multidimensional_index(i)[1]];
    auto to = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(region0, dextents<int32_t, 2>(HD, FQ));
    co.store(to);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint i = tid; i < FQ * HD; i += FNSG * 32) {
        const uint row = i / HD, d = i % HD;
        if (row < nq) {
            const uint o = (t0 + row) * (NH * HD) + h * HD + d;
            A[a.out_off + o] = region0[i] * sigm(A[a.gate_off + o]);
        }
    }
#endif
}

kernel void k_attn_h_blk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                         device uchar * KV0 [[buffer(3)]], constant AttnBArgs & a [[buffer(5)]],
                         device const ulong * BT [[buffer(8)]],
                         device uchar * KV1 [[buffer(10)]], device uchar * KV2 [[buffer(11)]], device uchar * KV3 [[buffer(12)]],
                         uint2 tgp [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) {
    const uint h = tgp.y, g = h / 3, t0 = tgp.x * AQ;
    const ulong koff = ulong(a.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
#ifdef KV4
    device kv_t * kptr0 = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, 0, koff);
    (void) PB; (void) A; (void) t0; (void) voff; (void) kptr0; (void) lane; (void) sg;
#else
    threadgroup float ss[AQ * AK];
    threadgroup float G[AQ * AG];
    threadgroup half sp[AQ * AK];
    threadgroup float sr[AQ];
    const uint nq = min((uint) AQ, a.T - t0);
    auto tq = tensor((device half *) (A + a.qp_off) + (ulong) t0 * (NH * HD) + h * HD, dextents<int32_t, 2>(HD, (int) nq), array<int, 2>({1, NH * HD}));
    auto tr = tensor(A + a.rp_off + t0 * (NH * NREL) + h * NREL, dextents<int32_t, 2>(NREL, (int) nq), array<int, 2>({1, NH * NREL}));
    auto ts = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss, dextents<int32_t, 2>(AK, AQ));
    auto tg = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(G, dextents<int32_t, 2>(AG, AQ));
    auto tp = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(sp, dextents<int32_t, 2>(AK, AQ));
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
                              execution_simdgroups<8>> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, AG, NREL, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
                              execution_simdgroups<8>> mm_g;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(AQ, HD, AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
                              execution_simdgroups<8>> mm_pv;
    auto tv0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
    auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
    for (short i = 0; i < 16; ++i) co[i] = 0.0f;
    ushort cd[4], cr[4];
    for (short q = 0; q < 4; ++q) { const auto ix = co.get_multidimensional_index(4 * q); cd[q] = ix[0]; cr[q] = ix[1]; }
    float M[4], S[4];
    for (short jj = 0; jj < 4; jj++) {
        const uint j = jj * 8 + sg;
        M[jj] = j < nq ? A[a.sink_off + (t0 + j) * NH + h] : 0.0f; S[jj] = 2980.9579870417283f;
    }
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint pfirst = a.p0 + t0, plast = a.p0 + t0 + nq - 1;
    const bool pruned = (a.window == 0u) && (a.pad2 > 0u) && (plast + 1u > a.pad2);
    const uint recent_win = pruned ? (a.pad2 - 64u) : 0u;
    const uint recent_kstart = (pruned && pfirst + 1u > recent_win) ? ((pfirst + 1u - recent_win) / AK * AK) : 0u;
    uint kstart = (a.window > 0 && pfirst + 1 > a.window) ? pfirst + 1 - a.window : 0;
    kstart = kstart / AK * AK;
    for (uint kc = kstart; kc <= plast; kc = (pruned && kc == 0u && recent_kstart > AK) ? recent_kstart : (kc + AK)) {
        const uint blk = kc >> 6;
        device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
        device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff);
        auto tk = tensor(kptr, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
        { auto cs = mm_qk.template get_destination_cooperative_tensor<decltype(tq), decltype(tk), float>(); mm_qk.run(tq, tk, cs); cs.store(ts); }
        const int D0 = int(pfirst) - int(kc);
        const int dlo = max(D0 - (AK - 1), 0);
        const bool bias = dlo < EXT;
        if (bias) {
            auto tb = tensor((device float *) relb + dlo * NREL, dextents<int32_t, 2>(NREL, AG), array<int, 2>({1, NREL}));
            auto cg = mm_g.template get_destination_cooperative_tensor<decltype(tr), decltype(tb), float>(); mm_g.run(tr, tb, cg); cg.store(tg);
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const bool fast = !pruned && nq == AQ && D0 >= AK - 1 && (a.window == 0 || D0 + AQ - 1 < (int) a.window) && (!bias || D0 + AQ - 1 < EXT);
        const int gofs = D0 - dlo - int(lane);
#ifdef KV8
        const float ks0 = kv_vscale(kptr + lane * HD), ks1 = kv_vscale(kptr + (32 + lane) * HD);
        const float vs0 = kv_vscale(vptr + lane * HD), vs1 = kv_vscale(vptr + (32 + lane) * HD);
#endif
        for (short jj = 0; jj < 4; jj++) {
            const uint j = jj * 8 + sg;
#ifdef KV8
            float s0 = ss[j * AK + lane] * ks0, s1 = ss[j * AK + 32 + lane] * ks1;
#else
            float s0 = ss[j * AK + lane], s1 = ss[j * AK + 32 + lane];
#endif
            if (fast) {
                if (bias) { threadgroup const float * gp = G + j * AG + j + gofs; s0 += gp[0]; s1 += gp[-32]; }
            } else {
                const int d0 = D0 + int(j) - int(lane), d1 = d0 - 32;
                if (bias && d0 < EXT) s0 += G[j * AG + clamp(d0 - dlo, 0, AG - 1)];
                if (bias && d1 < EXT) s1 += G[j * AG + clamp(d1 - dlo, 0, AG - 1)];
                if (!(j < nq && d0 >= 0 && (a.window == 0 || d0 < (int) a.window) && (!pruned || (kc + lane < 64u) || d0 < (int) recent_win))) s0 = -INFINITY;
                if (!(j < nq && d1 >= 0 && (a.window == 0 || d1 < (int) a.window) && (!pruned || (kc + 32u + lane < 64u) || d1 < (int) recent_win))) s1 = -INFINITY;
            }
            const float m = simd_max(max(M[jj], max(s0, s1)));
            const float ms = exp(M[jj] - m);
            M[jj] = m;
            const half p0 = half(exp(s0 - m + 8.0f)), p1 = half(exp(s1 - m + 8.0f));
#ifdef KV8
            sp[j * AK + lane] = half(float(p0) * vs0);
            sp[j * AK + 32 + lane] = half(float(p1) * vs1);
#else
            sp[j * AK + lane] = p0;
            sp[j * AK + 32 + lane] = p1;
#endif
            S[jj] = S[jj] * ms + simd_sum(float(p0) + float(p1));
            if (lane == 0) sr[j] = ms;
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        {
            const float r0 = sr[cr[0]], r1 = sr[cr[1]], r2 = sr[cr[2]], r3 = sr[cr[3]];
            co[0] *= r0; co[1] *= r0; co[2] *= r0; co[3] *= r0;
            co[4] *= r1; co[5] *= r1; co[6] *= r1; co[7] *= r1;
            co[8] *= r2; co[9] *= r2; co[10] *= r2; co[11] *= r2;
            co[12] *= r3; co[13] *= r3; co[14] *= r3; co[15] *= r3;
        }
        auto tv = tensor(vptr, dextents<int32_t, 2>(HD, AK), array<int, 2>({1, HD}));
        mm_pv.run(tp, tv, co);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (short jj = 0; jj < 4; jj++) { if (lane == 0) sr[jj * 8 + sg] = 1.0f / S[jj]; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device half * out = (device half *) (A + a.out_off);
    for (short q = 0; q < 4; ++q) {
        const uint row = cr[q];
        if (row < nq) {
            const uint o = (t0 + row) * (NH * HD) + h * HD + cd[q];
            const float4 gt = a.ghalf ? float4(*(device const half4 *) ((device const half *) (A + a.gate_off) + o)) : *(device const float4 *) (A + a.gate_off + o);
            const float4 v = float4(co[4 * q], co[4 * q + 1], co[4 * q + 2], co[4 * q + 3]) * sr[row] / (1.0f + exp(-gt));
            *(device half4 *) (out + o) = half4(v);
        }
    }
#endif
}

#pragma clang fp contract(off) reassociate(off)
// -------------------------------------------------------------------------------------------------
// Fixed-split GQA-3 tensor-core (`matmul2d`) attention (`emma/tc-prefill-attn`).
//
// Each threadgroup serves one KV head `g` (`0..NKV`), sharing every K and V sub-tile (`TC_ATT_AK = 32`)
// across all 3 GQA query heads (`h = g * 3 + sg`, `sg in 0..2`) and up to `TC_ATT_ROWS = 16` query rows
// (`48` queries per K/V read). Because `matmul2d(16, 32, 128)` and `matmul2d(16, 128, 32)` are 0-ULP
// row-count- and slot-invariant on M5 under `MTLMathMode::Safe`, running the identical `32`-key sub-tile
// fixed-split loop in Layer 2 prefill (`k_attn_tc_fixed_b`), Layer 3 paged prefill (`k_attn_tc_fixed_blk`),
// Layer 2 decode (`k_attn_tc_dec`), Layer 3 solo decode (`k_attn_tc_dec_solo`), Layer 3 grouped decode
// (`k_attn_tc_grp_dec`), and sparse decode (`k_attn_tc_sparse_dec`) keeps `crosspath` (FP16 and KV4),
// `binv`, and `blockedinv` 0-ULP bit-exact.
//
// Softmax weights P stay in float through the `P x V` matmul2d (`float P x half V`, nq- and slot-invariant on M5)
// in every kernel below (`sp_h` is a float tile despite its name), so `l` and `O` sum the same unrounded weights.
//
// KV8 (`--kv8`): `k_attn_tc_fixed_blk` and `k_attn_tc_fixed_b` feed the stored `int8` rows straight into `matmul2d`
// (`S_int = Q x K_int^T` in `half x int8 -> float` and `O += P' x V_int` in `float x int8 -> float`), with zero
// threadgroup staging and zero `threadgroup_barrier`s: K's per-row `kv_vscale` multiplies `S_int` before relative
// bias/sink, and V's per-row `kv_vscale` multiplies `w_p` into `P'` while `l` sums unscaled `w_p`.
// The decode kernels (`INK_TC_ATTN_DEC`) take KV8 too: `k_attn_tc_dec_solo` and `k_attn_tc_grp_dec` read the int8 rows
// the same way (0 ULP from `k_attn_tc_fixed_blk` on sealed rows; the solo kernel runs the 3 GQA heads as the rows
// of one 8-row tile); in a dry step the solo kernel's last tile stops
// short of the current row and folds its `kv_cur` K/V in by hand. `k_attn_tc_dec` and `k_attn_tc_sparse_dec`, which
// stage every tile in threadgroup memory as FP16 does, stage KV8 rows as `int8 x scale` in fp16 (`tc_kv8_deq4`).
// All three cache modes (`FP16`, `KV8`, `KV4`) share `tc_interior_bounds` (`#define TC_KV8_NO_INTERIOR` compiles it
// out for 0-ULP equivalence tests).
//
// Grid of `k_attn_tc_fixed_blk` / `k_attn_tc_fixed_b` (`tc_attn_dispatch_grid` in `engine.rs`), per cache format:
// FP16 and KV8 run (query row block `x`, KV head `y`, split column `z`): row blocks are the fastest axis so the row
// blocks that read the same K/V split of a head are dispatched together and share it through the cache instead of
// re-reading it from DRAM (1.08-1.09x on M5 at 20K-60K under KV8). KV4 keeps the split-major grid (split column
// `x`, KV head `y`, row block `z`): it stages and dequantizes its K/V in threadgroup memory, and the row-major grid
// measured 2-2.4% slower there. Threadgroups never communicate: each writes its own partial slots and
// `k_attn_fixed_combine` (a later dispatch) folds them in slot order, so the order the grid runs in cannot change a
// bit. `#define TC_ATT_GRID_SPLIT_X` puts FP16 and KV8 back on the split-major grid for the 0-ULP before/after test.
//
// Outside `KV4`, the score tile S and the weight tile P share one `float [16][32]` tile per simdgroup (6.7 KB of
// threadgroup memory instead of 12.9 KB): lane `j` reads S[r][j] and then writes P[r][j] to the same word, no
// other lane touches that word between the `cS.store` and the `P x V` matmul, and the next tile's `cS.store`
// follows the `P x V` matmul's barrier. S is stored with only the `nr` live rows so P's zeroed tail rows stay
// zero. `KV4` keeps S in its union with the staged K/V tile, which the V stage overwrites before `P x V`.
// `#define TC_ATT_SEPARATE_SP` restores the separate S tile for the 0-ULP before/after test.
//
// Ported from GPL-3.0-or-later sources, with thanks:
// - direct `int8` tensor-op operands with post-matmul K/V row scales: `Eriskii/erisinky` `k_attn_h` under `KV8`,
//   read in `chadlyb/erisinky` at `dd1bc5a` (`src/prefill.metal`), and `rowan/wip-kv8-tc` (`e16ac87`);
// - exact interior-tile fast path: `orual/inkspren` at `44eceee` (`crates/inkspren-gpu/src/kernels/tensor_attention.hip`,
//   `tile_interior`) and `chadlyb/erisinky` `IDEAS.md`.

#define TC_ATT_ROWS 16u
#define TC_ATT_AK   32u
// KV8 `k_attn_tc_grp_dec` tile height: its `count <= DEC_GRP_MAX` (8) lanes of one head fit the smallest M
#ifdef KV8
#define TC_GRP_ROWS 8u
#else
#define TC_GRP_ROWS TC_ATT_ROWS
#endif
// KV8 `k_attn_tc_dec_solo` tile height: its 3 live rows (the GQA heads) in the smallest `matmul2d` M (8, `M must be a
// multiple of 8 or 16`)
#define TC_DEC_ROWS 8u
#define TC_INV_EXP8 0.00033546262790251185f

// Disjoint-lifetime shared tile when staging KV (`KV4` or `dry`/ring decode):
// `kv4` (8 KiB) holds 32 x 128 half K or V; `ss` (6 KiB) holds 3 x 16 x 32 float Q*K^T scores.
union TcKvScore {
    half4 kv4[TC_ATT_AK * (HD / 4)];
    float ss[3][TC_ATT_ROWS * TC_ATT_AK];
};

inline float tc_relbias_dot(device const float4 * rq, device const float * relb, uint dist) {
    device const float4 * bb = (device const float4 *) (relb + dist * NREL);
    return (dot(rq[0], bb[0]) + dot(rq[1], bb[1])) + (dot(rq[2], bb[2]) + dot(rq[3], bb[3]));
}

inline float tc_relbias_dot4(const float4 rq0, const float4 rq1, const float4 rq2, const float4 rq3,
                             device const float * relb, uint dist) {
    device const float4 * bb = (device const float4 *) (relb + dist * NREL);
    return (dot(rq0, bb[0]) + dot(rq1, bb[1])) + (dot(rq2, bb[2]) + dot(rq3, bb[3]));
}

// Keys `[k_lo, p_hi)` visible to every query row of the threadgroup when all `nr` rows are live and `gap_end == 0`.
struct TcInterior { uint k_lo, p_hi; };

inline TcInterior tc_interior_bounds(thread const bool * live_r, thread const uint * p_lo_r, thread const uint * p_hi_r,
                                     uint nr, uint gap_end) {
    TcInterior t = { ~0u, 0u };
#ifndef TC_KV8_NO_INTERIOR
    if (gap_end == 0u) {
        bool all_live = true;
        uint lo = 0u, hi = ~0u;
        for (uint r = 0u; r < nr; ++r) {
            all_live = all_live && live_r[r];
            lo = max(lo, p_lo_r[r]);
            hi = min(hi, p_hi_r[r]);
        }
        if (all_live) { t.k_lo = lo; t.p_hi = hi; }
    }
#else
    (void) live_r; (void) p_lo_r; (void) p_hi_r; (void) nr; (void) gap_end;
#endif
    return t;
}

// Online softmax of one 32-key tile, one row at a time (`tc_softmax_row`), then the row bookkeeping for all rows at
// once (`tc_softmax_finish`). Every lane of row `r` computes the same `m_new` (a `simd_max`) and `w_sum` (a
// `simd_sum`), so the rescale factor `alpha = exp(m_old - m_new)` and the update of `l` are row-uniform: lane `r`
// keeps row `r`'s `m_new` and `w_sum` in a register and works out row `r`'s `alpha`, `l` and `m` after the row loop,
// one `exp` per lane per tile instead of one per row (17 instead of 32 `exp` per lane per tile). The same
// operations run on the same operands in the same order, so every bit is the one the per-row form wrote.
// `tc_softmax_finish` also says, uniformly across the simdgroup, whether any live row's running max moved (else
// every `alpha` is exactly 1 and the `O *= alpha` pass would multiply every element by 1) and whether any row still
// has no visible key (else the zeroing pass after `P x V` changes nothing); the kernels skip a pass that would leave
// every bit as it is. Rows `nr..16` are never written out. `#define TC_ATT_EAGER_SOFTMAX` restores the per-row form
// with both passes always run, for the 0-ULP before/after test; `#define TC_ATT_ALWAYS_PASSES` keeps the row-parallel
// bookkeeping but runs both passes, so the microbenchmark can price the two changes apart.
//
// Two reorderings of the float math, KV8 only, each behind its own define (off by default after the M5
// KV8 KL gate; `INK_TC_EXP2=1` and `INK_TC_LAZY_RESCALE=1`, read in `model.rs`, put them in under --kv8):
// - `TC_ATT_EXP2`: scores in log2 units, `log2(e)` folded into K's per-row `kv_vscale` (one multiply per key per
//   tile, which the score multiply already pays), the sink and the relative bias, so `exp` becomes `exp2`. The
//   running max is written out in natural units (`m * ln 2`), so `k_attn_fixed_combine` is unchanged.
// - `TC_ATT_LAZY_RESCALE` (FlashAttention-4's conditional rescale): a row's reference max moves only when the tile
//   max passes it by more than `TC_LAZY_TAU` (8, in the units of the scores: `e^8` or `2^8`), so most tiles keep
//   every `alpha` at exactly 1 and skip the `O *= alpha` pass. Weights stay below `e^(8 + TC_LAZY_TAU)`; the
//   partials carry the reference max they were summed against, so the combine is exact in that max.
#if (defined(TC_ATT_EXP2) || defined(TC_ATT_LAZY_RESCALE)) && !defined(KV8)
#error "TC_ATT_EXP2 and TC_ATT_LAZY_RESCALE are KV8-only"
#endif
#ifdef TC_ATT_EXP2
#define TC_SCORE_UNITS(x) ((x) * M_LOG2E_F)
#define TC_EXP(x) exp2(x)
#define TC_EXP_OFFSET 11.541560327111707f
#define TC_M_OUT(m) ((m) * M_LN2_F)
#else
#define TC_SCORE_UNITS(x) (x)
#define TC_EXP(x) exp(x)
#define TC_EXP_OFFSET 8.0f
#define TC_M_OUT(m) (m)
#endif
#define TC_LAZY_TAU 8.0f

struct TcRowAcc { float m_new; float w_sum; };

inline void tc_softmax_row(float sc, bool valid, float vs, uint r, ushort lane, threadgroup float * sp_sg,
                           threadgroup float * m_sg, threadgroup float * l_sg, threadgroup float * alpha_sg,
                           thread TcRowAcc & acc) {
    #pragma clang fp contract(off) reassociate(off)
    const float m_old = m_sg[r];
#ifdef TC_ATT_LAZY_RESCALE
    const float m_cand = max(m_old, simd_max(sc));
    const float m_new = (m_old == -INFINITY || m_cand > m_old + TC_LAZY_TAU) ? m_cand : m_old;
#else
    const float m_new = max(m_old, simd_max(sc));
#endif
    const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : TC_EXP(sc - m_new + TC_EXP_OFFSET);
    sp_sg[r * TC_ATT_AK + lane] = w_p * vs;
    const float w_sum = simd_sum(w_p);
#ifdef TC_ATT_EAGER_SOFTMAX
    (void) acc;
    const float alpha = (m_old == -INFINITY) ? 0.0f : TC_EXP(m_old - m_new);
    if (lane == 0u) {
        m_sg[r] = m_new;
        l_sg[r] = l_sg[r] * alpha + w_sum;
        alpha_sg[r] = alpha;
    }
#else
    (void) l_sg; (void) alpha_sg;
    if (uint(lane) == r) { acc.m_new = m_new; acc.w_sum = w_sum; }
#endif
}

// After every row of the tile went through `tc_softmax_row`: bit 0 set when some row's `alpha` is not exactly 1
// (run `O *= alpha`), bit 1 when some row still has no visible key (zero its `O` after `P x V`). Uniform per simdgroup.
inline uint tc_softmax_finish(thread const TcRowAcc & acc, uint nr, ushort lane, threadgroup float * m_sg,
                              threadgroup float * l_sg, threadgroup float * alpha_sg) {
    #pragma clang fp contract(off) reassociate(off)
#ifdef TC_ATT_EAGER_SOFTMAX
    (void) acc; (void) nr; (void) lane; (void) m_sg; (void) l_sg; (void) alpha_sg;
    return 3u;
#else
    simdgroup_barrier(mem_flags::mem_threadgroup);
    bool rescale = false, unseen = false;
    if (uint(lane) < nr) {
        const float m_old = m_sg[lane];
        const float alpha = (m_old == -INFINITY) ? 0.0f : TC_EXP(m_old - acc.m_new);
        m_sg[lane] = acc.m_new;
        l_sg[lane] = l_sg[lane] * alpha + acc.w_sum;
        alpha_sg[lane] = alpha;
        unseen = acc.m_new == -INFINITY;
        rescale = !unseen && alpha != 1.0f;
    }
#ifdef TC_ATT_ALWAYS_PASSES
    (void) rescale; (void) unseen;
    return 3u;
#else
    return (simd_any(rescale) ? 1u : 0u) | (simd_any(unseen) ? 2u : 0u);
#endif
#endif
}

#ifdef KV8
inline void tc_kv8_scores(device const float * A, device const float * relb, constant PreparedAttnArgs & p,
                          device const kv_t * kptr, device const kv_t * vptr,
                          threadgroup float * ss_sg, threadgroup float * sp_sg,
                          threadgroup float * m_sg, threadgroup float * l_sg, threadgroup float * alpha_sg,
                          thread const bool * live_r, thread const uint * p_lo_r, thread const uint * p_hi_r,
                          thread const float * sink_r, const TcInterior interior_tg,
                          uint row0, uint nr, uint h, uint kc, uint nk, uint gap_end, bool any_bias, uint sel_rows,
                          ushort lane, thread TcRowAcc & acc) {
    #pragma clang fp contract(off) reassociate(off)
    const bool in_tile = lane < nk;
    const float ks = in_tile ? TC_SCORE_UNITS(kv_vscale(kptr + uint(lane) * HD)) : 0.0f;
    const float vs = in_tile ? kv_vscale(vptr + uint(lane) * HD) : 0.0f;
    const uint kp = kc + lane;
    if (sel_rows == ~0u && !any_bias && nk == TC_ATT_AK && kc >= interior_tg.k_lo && kc + TC_ATT_AK <= interior_tg.p_hi) {
        for (uint r = 0u; r < nr; ++r) {
            const float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;
            tc_softmax_row(raw_qk - sink_r[r], true, vs, r, lane, sp_sg, m_sg, l_sg, alpha_sg, acc);
        }
        return;
    }
    for (uint r = 0u; r < nr; ++r) {
        const uint pos = p.pos0 + row0 + r;
        const bool valid = live_r[r] && in_tile && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])
            && (gap_end == 0u || kp < 64u || kp >= gap_end) && ((sel_rows >> r) & 1u) != 0u;
        float sc = -INFINITY;
        if (valid) {
            float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;
            if (any_bias && (pos - kp) < EXT) {
                device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
                raw_qk += TC_SCORE_UNITS(tc_relbias_dot(rq, relb, pos - kp));
            }
            sc = raw_qk - sink_r[r];
        }
        tc_softmax_row(sc, valid, vs, r, lane, sp_sg, m_sg, l_sg, alpha_sg, acc);
    }
}
#endif

#ifdef KV8
// One staged K or V quad of a KV8 row as fp16 with the row's scale folded in. `int8 x kv_scale` carries at most
// 11 significant bits (7 + 4), so the product is exact in fp16 whenever it lands in fp16's normal range.
inline half4 tc_kv8_deq4(device const kv_t * row, uint col4) {
    return half4(float4(char4(*(device const packed_char4 *) (row + col4 * 4u))) * kv_vscale(row));
}
#endif

kernel void k_attn_tc_fixed_blk(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device uchar * KV0 [[buffer(3)]],
    constant PreparedAttnArgs & p [[buffer(5)]],
    device const ulong * BT [[buffer(8)]],
    device uchar * KV1 [[buffer(10)]],
    device uchar * KV2 [[buffer(11)]],
    device uchar * KV3 [[buffer(12)]],
    device const uint * SEL [[buffer(14)]],
    uint3 tg [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]],
    ushort sg [[simdgroup_index_in_threadgroup]],
    ushort lane [[thread_index_in_simdgroup]]
) {
#ifndef KV4
    (void) tid;
#endif
#if defined(TC_ATT_GRID_SPLIT_X) || defined(KV4)
    const uint sx = tg.x, row0 = tg.z * p.tg_rows;
#else
    const uint sx = tg.z, row0 = tg.x * p.tg_rows;
#endif
    const uint g = tg.y;
    if (row0 >= p.nrows || sg >= 3u) return;
    const uint nr = min(p.tg_rows, p.nrows - row0);

    uint p_lo_r[TC_ATT_ROWS], p_hi_r[TC_ATT_ROWS], local_sp_r[TC_ATT_ROWS];
    bool live_r[TC_ATT_ROWS];
    uint split_start = 0u, gap_end = 0u;
    uint k_min_tg = ~0u, p_max_tg = 0u;

    if (p.window == 0u && p.full_budget > 0u) {
        for (uint r = 1u; r < TC_ATT_ROWS; ++r) { live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u; }
        const uint pos = p.pos0 + row0, p_hi = pos + 1u;
        if (p_hi > p.full_budget) {
            const uint recent_start = p_hi - (p.full_budget - 64u);
            const uint rlo = recent_start / p.kps;
            const uint sp_hi = pos / p.kps;
            const uint count = (rlo == 0u) ? (sp_hi + 1u) : (1u + (sp_hi - rlo + 1u));
            if (sx >= count) return;
            const uint abs_sp = (rlo == 0u || sx == 0u) ? sx : (rlo + sx - 1u);
            split_start = abs_sp * p.kps;
            p_lo_r[0] = (abs_sp > 0u) ? recent_start : 0u;
            p_hi_r[0] = (abs_sp == 0u && rlo > 0u) ? min(p_hi, 64u) : min(p_hi, split_start + p.kps);
            if (abs_sp == 0u && rlo == 0u) gap_end = recent_start;
            local_sp_r[0] = sx;
            live_r[0] = split_start < p_hi_r[0];
        } else {
            split_start = sx * p.kps;
            if (split_start >= p_hi) return;
            p_lo_r[0] = 0u;
            p_hi_r[0] = min(p_hi, split_start + p.kps);
            local_sp_r[0] = sx;
            live_r[0] = true;
        }
        if (live_r[0]) { k_min_tg = p_lo_r[0]; p_max_tg = p_hi_r[0]; }
    } else {
        const uint p_hi_0 = p.pos0 + row0 + 1u;
        const uint p_lo_0 = (p.window != 0u && p_hi_0 > p.window) ? (p_hi_0 - p.window) : 0u;
        const uint abs_sp = (p_lo_0 / p.kps) + sx;
        split_start = abs_sp * p.kps;
        const uint split_lim = split_start + p.kps;
        for (uint r = 0u; r < TC_ATT_ROWS; ++r) {
            if (r < nr) {
                const uint pos = p.pos0 + row0 + r, p_hi = pos + 1u;
                const uint plo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
                const uint sp_base = plo / p.kps;
                const bool lv = (abs_sp >= sp_base) && (split_start < p_hi);
                live_r[r] = lv;
                p_lo_r[r] = plo;
                p_hi_r[r] = min(p_hi, split_lim);
                local_sp_r[r] = abs_sp - sp_base;
                if (lv) {
                    k_min_tg = min(k_min_tg, plo);
                    p_max_tg = max(p_max_tg, p_hi_r[r]);
                }
            } else {
                live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u;
            }
        }
    }
    if (p_max_tg == 0u) return;
    const TcInterior interior_tg = tc_interior_bounds(live_r, p_lo_r, p_hi_r, nr, gap_end);

    // Sparse prefill (`sel_words != 0`): the threadgroup's rows lie in at most two 64-row query blocks `qb_a` (rows
    // `[0, r_split)`) and `qb_b`, each with its own key-block mask for KV head `g`. A 32-key tile (always inside one
    // 64-key block) that neither block selected is skipped whole, which leaves `m`, `l` and `O` exactly as they were;
    // a tile only one of the two selected takes the per-row path with the other block's rows masked out.
    // `NO_SPARSE_PF` compiles the sparse path out (the kernel before it, for the 0-ULP off-path test).
#ifdef NO_SPARSE_PF
    const uint sel_words = 0u;
#else
    const uint sel_words = p.sel_words;
#endif
    device const uint * sel_a = SEL;
    device const uint * sel_b = SEL;
    uint r_split = nr;
    if (sel_words != 0u) {
        const uint pa = p.pos0 + row0, qb_a = pa >> 6, qb_b = (pa + nr - 1u) >> 6;
        sel_a = SEL + ulong((qb_a - p.sel_qb0) * NKV + g) * p.sel_words;
        sel_b = SEL + ulong((qb_b - p.sel_qb0) * NKV + g) * p.sel_words;
        if (qb_b != qb_a) r_split = (qb_b << 6) - pa;
    }
    const uint rows_a = (r_split >= 32u) ? ~0u : ((1u << r_split) - 1u);

    const ulong koff = ulong(p.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    const uint h = g * 3u + uint(sg);
    device const float * relb = (device const float *) (PB + p.relbias_w);

#ifdef KV4
    threadgroup TcKvScore u_ks;
    threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
    threadgroup float * ss_sg = u_ks.ss[sg];
#elif defined(TC_ATT_SEPARATE_SP)
    threadgroup float ss[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float * ss_sg = ss[sg];
#endif
    threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
#if !defined(KV4) && !defined(TC_ATT_SEPARATE_SP)
    threadgroup float * ss_sg = sp_h[sg];
#endif
    threadgroup float m_row[3][TC_ATT_ROWS];
    threadgroup float l_row[3][TC_ATT_ROWS];
    threadgroup float alpha_row[3][TC_ATT_ROWS];

    if (lane < TC_ATT_ROWS) {
        m_row[sg][lane] = -INFINITY;
        l_row[sg][lane] = 0.0f;
        alpha_row[sg][lane] = 0.0f;
    }
    if (nr < TC_ATT_ROWS) {
        for (uint r = nr; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
    }
    simdgroup_barrier(mem_flags::mem_threadgroup);

    auto tQ = tensor((device half *) (A + p.q_off) + ulong(row0) * (NH * HD) + h * HD,
                     dextents<int32_t, 2>(HD, (int) nr), array<int, 2>({1, NH * HD}));
#if defined(KV4) || defined(TC_ATT_SEPARATE_SP)
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
#else
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));
#endif
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

#ifdef KV4
    auto tV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#elif defined(KV8)
    auto tV0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#else
    auto tV0 = tensor((device half *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#endif
    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tV0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;

    float sink_r[TC_ATT_ROWS];
    for (uint r = 0u; r < nr; ++r) sink_r[r] = TC_SCORE_UNITS(A[p.sink_off + (row0 + r) * NH + h]);

    for (uint kc = split_start; kc < p_max_tg; kc += TC_ATT_AK) {
        if (kc + TC_ATT_AK <= k_min_tg) continue;
        if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
        uint sel_rows = ~0u;
        if (sel_words != 0u) {
            const uint kb = kc >> 6;
            const bool in_a = ((sel_a[kb >> 5] >> (kb & 31u)) & 1u) != 0u;
            const bool in_b = ((sel_b[kb >> 5] >> (kb & 31u)) & 1u) != 0u;
            if (!in_a && !in_b) continue;
            if (in_a != in_b) sel_rows = in_a ? rows_a : ~rows_a;
        }
        const uint nk = min((uint) TC_ATT_AK, p_max_tg - kc);

#ifdef KV4
        device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
            if (ok) {
                device const kv_t * krow = kblk + kr;
                const ushort u = ((device const ushort *) krow->qs)[col4];
                u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
        device kv_t * kblk_base = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff);
        if (kblk_base == nullptr) continue;
        device kv_t * kptr = kblk_base + (kc & KV_BLK_MASK) * HD;
        device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD;
        auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#else
        device half * kblk_base = (device half *) kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff);
        if (kblk_base == nullptr) continue;
        device half * kptr = kblk_base + (kc & KV_BLK_MASK) * HD;
        auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#endif

        const bool any_bias = (int(p.pos0 + row0) - int(kc + nk - 1u)) < int(EXT);
        TcRowAcc acc = { -INFINITY, 0.0f };
#ifdef KV8
        tc_kv8_scores(A, relb, p, kptr, vptr, ss_sg, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg],
                      live_r, p_lo_r, p_hi_r, sink_r, interior_tg, row0, nr, h, kc, nk, gap_end, any_bias, sel_rows, lane, acc);
#else
        const bool tile_interior = (sel_rows == ~0u) && (nk == TC_ATT_AK) && (kc >= interior_tg.k_lo)
            && (kc + TC_ATT_AK <= interior_tg.p_hi);
        if (tile_interior && !any_bias) {
            for (uint r = 0u; r < nr; ++r) {
                const float sc = ss_sg[r * TC_ATT_AK + lane] - sink_r[r];
                tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
            }
        } else if (tile_interior) {
            const uint kp = kc + lane;
            for (uint r = 0u; r < nr; ++r) {
                const uint pos = p.pos0 + row0 + r;
                float raw_qk = ss_sg[r * TC_ATT_AK + lane];
                if ((pos - kp) < EXT) {
                    device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
                    raw_qk += tc_relbias_dot(rq, relb, pos - kp);
                }
                const float sc = raw_qk - sink_r[r];
                tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
            }
        } else {
            for (uint r = 0u; r < nr; ++r) {
                const uint pos = p.pos0 + row0 + r;
                const uint kp = kc + lane;
                const bool valid = live_r[r] && (lane < nk) && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])
                    && (gap_end == 0u || kp < 64u || kp >= gap_end) && ((sel_rows >> r) & 1u) != 0u;
                float sc = -INFINITY;
                if (valid) {
                    float raw_qk = ss_sg[r * TC_ATT_AK + lane];
                    if (any_bias && (pos - kp) < EXT) {
                        device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
                        raw_qk += tc_relbias_dot(rq, relb, pos - kp);
                    }
                    sc = raw_qk - sink_r[r];
                }
                tc_softmax_row(sc, valid, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
            }
        }
#endif
        const uint passes = tc_softmax_finish(acc, nr, lane, m_row[sg], l_row[sg], alpha_row[sg]);
        simdgroup_barrier(mem_flags::mem_threadgroup);

        if (passes & 1u) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                const float a_s = alpha_row[sg][ix[1]];
                cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
            }
        }
#ifdef KV4
        threadgroup_barrier(mem_flags::mem_threadgroup);
        device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
            if (ok) {
                device const kv_t * vrow = vblk + kr;
                const ushort u = ((device const ushort *) vrow->qs)[col4];
                u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        threadgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
        auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#else
        device half * vptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
        auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
        if (passes & 2u) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                if (m_row[sg][ix[1]] == -INFINITY) cO[i] = 0.0f;
            }
        }
    }

    for (uint r = 0u; r < nr; ++r) {
        if (live_r[r] && lane == 0u) {
            const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
            device float * P = A + part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2);
            P[0] = TC_M_OUT(m_row[sg][r]);
            P[1] = (l_row[sg][r] * TC_INV_EXP8) + 0.0f;
        }
    }
    for (short i = 0; i < cO.get_capacity(); ++i) {
        const auto ix = cO.get_multidimensional_index(i);
        const uint r = uint(ix[1]), d = uint(ix[0]);
        if (r < nr && live_r[r]) {
            const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
            A[part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2) + 2 + d] = (cO[i] * TC_INV_EXP8) + 0.0f;
        }
    }
}

kernel void k_attn_tc_fixed_b(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device kv_t * KV [[buffer(3)]],
    constant PreparedAttnArgs & p [[buffer(5)]],
    uint3 tg [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]],
    ushort sg [[simdgroup_index_in_threadgroup]],
    ushort lane [[thread_index_in_simdgroup]]
) {
#ifndef KV4
    (void) tid;
#endif
#if defined(TC_ATT_GRID_SPLIT_X) || defined(KV4)
    const uint sx = tg.x, row0 = tg.z * p.tg_rows;
#else
    const uint sx = tg.z, row0 = tg.x * p.tg_rows;
#endif
    const uint g = tg.y;
    if (row0 >= p.nrows || sg >= 3u) return;
    const uint nr = min(p.tg_rows, p.nrows - row0);

    uint p_lo_r[TC_ATT_ROWS], p_hi_r[TC_ATT_ROWS], local_sp_r[TC_ATT_ROWS];
    bool live_r[TC_ATT_ROWS];
    uint split_start = 0u, gap_end = 0u;
    uint k_min_tg = ~0u, p_max_tg = 0u;

    if (p.window == 0u && p.full_budget > 0u) {
        for (uint r = 1u; r < TC_ATT_ROWS; ++r) { live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u; }
        const uint pos = p.pos0 + row0, p_hi = pos + 1u;
        if (p_hi > p.full_budget) {
            const uint recent_start = p_hi - (p.full_budget - 64u);
            const uint rlo = recent_start / p.kps;
            const uint sp_hi = pos / p.kps;
            const uint count = (rlo == 0u) ? (sp_hi + 1u) : (1u + (sp_hi - rlo + 1u));
            if (sx >= count) return;
            const uint abs_sp = (rlo == 0u || sx == 0u) ? sx : (rlo + sx - 1u);
            split_start = abs_sp * p.kps;
            p_lo_r[0] = (abs_sp > 0u) ? recent_start : 0u;
            p_hi_r[0] = (abs_sp == 0u && rlo > 0u) ? min(p_hi, 64u) : min(p_hi, split_start + p.kps);
            if (abs_sp == 0u && rlo == 0u) gap_end = recent_start;
            local_sp_r[0] = sx;
            live_r[0] = split_start < p_hi_r[0];
        } else {
            split_start = sx * p.kps;
            if (split_start >= p_hi) return;
            p_lo_r[0] = 0u;
            p_hi_r[0] = min(p_hi, split_start + p.kps);
            local_sp_r[0] = sx;
            live_r[0] = true;
        }
        if (live_r[0]) { k_min_tg = p_lo_r[0]; p_max_tg = p_hi_r[0]; }
    } else {
        const uint p_hi_0 = p.pos0 + row0 + 1u;
        const uint p_lo_0 = (p.window != 0u && p_hi_0 > p.window) ? (p_hi_0 - p.window) : 0u;
        const uint abs_sp = (p_lo_0 / p.kps) + sx;
        split_start = abs_sp * p.kps;
        const uint split_lim = split_start + p.kps;
        for (uint r = 0u; r < TC_ATT_ROWS; ++r) {
            if (r < nr) {
                const uint pos = p.pos0 + row0 + r, p_hi = pos + 1u;
                const uint plo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
                const uint sp_base = plo / p.kps;
                const bool lv = (abs_sp >= sp_base) && (split_start < p_hi);
                live_r[r] = lv;
                p_lo_r[r] = plo;
                p_hi_r[r] = min(p_hi, split_lim);
                local_sp_r[r] = abs_sp - sp_base;
                if (lv) {
                    k_min_tg = min(k_min_tg, plo);
                    p_max_tg = max(p_max_tg, p_hi_r[r]);
                }
            } else {
                live_r[r] = false; p_lo_r[r] = 0u; p_hi_r[r] = 0u; local_sp_r[r] = 0u;
            }
        }
    }
    if (p_max_tg == 0u) return;
    const TcInterior interior_tg = tc_interior_bounds(live_r, p_lo_r, p_hi_r, nr, gap_end);

    const uint h = g * 3u + uint(sg);
    device const float * relb = (device const float *) (PB + p.relbias_w);

#ifdef KV4
    threadgroup TcKvScore u_ks;
    threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
    threadgroup float * ss_sg = u_ks.ss[sg];
#elif defined(TC_ATT_SEPARATE_SP)
    threadgroup float ss[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float * ss_sg = ss[sg];
#endif
    threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
#if !defined(KV4) && !defined(TC_ATT_SEPARATE_SP)
    threadgroup float * ss_sg = sp_h[sg];
#endif
    threadgroup float m_row[3][TC_ATT_ROWS];
    threadgroup float l_row[3][TC_ATT_ROWS];
    threadgroup float alpha_row[3][TC_ATT_ROWS];

    if (lane < TC_ATT_ROWS) {
        m_row[sg][lane] = -INFINITY;
        l_row[sg][lane] = 0.0f;
        alpha_row[sg][lane] = 0.0f;
    }
    if (nr < TC_ATT_ROWS) {
        for (uint r = nr; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
    }
    simdgroup_barrier(mem_flags::mem_threadgroup);

    auto tQ = tensor((device half *) (A + p.q_off) + ulong(row0) * (NH * HD) + h * HD,
                     dextents<int32_t, 2>(HD, (int) nr), array<int, 2>({1, NH * HD}));
#if defined(KV4) || defined(TC_ATT_SEPARATE_SP)
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
#else
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));
#endif
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, (int) nr), array<int, 2>({1, TC_ATT_AK}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

#ifdef KV4
    auto tV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#elif defined(KV8)
    auto tV0 = tensor(KV, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#else
    auto tV0 = tensor((device half *) KV, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#endif
    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tV0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;

    float sink_r[TC_ATT_ROWS];
    for (uint r = 0u; r < nr; ++r) sink_r[r] = TC_SCORE_UNITS(A[p.sink_off + (row0 + r) * NH + h]);

    for (uint kc = split_start; kc < p_max_tg; kc += TC_ATT_AK) {
        if (kc + TC_ATT_AK <= k_min_tg) continue;
        if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
        const uint nk = min((uint) TC_ATT_AK, p_max_tg - kc);
        const uint k_idx0 = uint(int(kc) - p.idx0);

#ifdef KV4
        device const kv_t * kblk = KV + p.k_base + ulong(g) * ulong(p.cap) + ulong(k_idx0);
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
            if (ok) {
                device const kv_t * krow = kblk + kr;
                const ushort u = ((device const ushort *) krow->qs)[col4];
                u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
        device kv_t * kptr = KV + p.k_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD;
        device kv_t * vptr = KV + p.v_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD;
        auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#else
        device half * kptr = (device half *) (KV + p.k_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD);
        auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#endif

        const bool any_bias = (int(p.pos0 + row0) - int(kc + nk - 1u)) < int(EXT);
        TcRowAcc acc = { -INFINITY, 0.0f };
#ifdef KV8
        tc_kv8_scores(A, relb, p, kptr, vptr, ss_sg, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg],
                      live_r, p_lo_r, p_hi_r, sink_r, interior_tg, row0, nr, h, kc, nk, gap_end, any_bias, ~0u, lane, acc);
#else
        const bool tile_interior = (nk == TC_ATT_AK) && (kc >= interior_tg.k_lo) && (kc + TC_ATT_AK <= interior_tg.p_hi);
        if (tile_interior && !any_bias) {
            for (uint r = 0u; r < nr; ++r) {
                const float sc = ss_sg[r * TC_ATT_AK + lane] - sink_r[r];
                tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
            }
        } else if (tile_interior) {
            const uint kp = kc + lane;
            for (uint r = 0u; r < nr; ++r) {
                const uint pos = p.pos0 + row0 + r;
                float raw_qk = ss_sg[r * TC_ATT_AK + lane];
                if ((pos - kp) < EXT) {
                    device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
                    raw_qk += tc_relbias_dot(rq, relb, pos - kp);
                }
                const float sc = raw_qk - sink_r[r];
                tc_softmax_row(sc, true, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
            }
        } else {
            for (uint r = 0u; r < nr; ++r) {
                const uint pos = p.pos0 + row0 + r;
                const uint kp = kc + lane;
                const bool valid = live_r[r] && (lane < nk) && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])
                    && (gap_end == 0u || kp < 64u || kp >= gap_end);
                float sc = -INFINITY;
                if (valid) {
                    float raw_qk = ss_sg[r * TC_ATT_AK + lane];
                    if (any_bias && (pos - kp) < EXT) {
                        device const float4 * rq = (device const float4 *) (A + p.r_off + ((row0 + r) * NH + h) * NREL);
                        raw_qk += tc_relbias_dot(rq, relb, pos - kp);
                    }
                    sc = raw_qk - sink_r[r];
                }
                tc_softmax_row(sc, valid, 1.0f, r, lane, sp_h[sg], m_row[sg], l_row[sg], alpha_row[sg], acc);
            }
        }
#endif
        const uint passes = tc_softmax_finish(acc, nr, lane, m_row[sg], l_row[sg], alpha_row[sg]);
        simdgroup_barrier(mem_flags::mem_threadgroup);

        if (passes & 1u) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                const float a_s = alpha_row[sg][ix[1]];
                cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
            }
        }
#ifdef KV4
        threadgroup_barrier(mem_flags::mem_threadgroup);
        device const kv_t * vblk = KV + p.v_base + ulong(g) * ulong(p.cap) + ulong(k_idx0);
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const bool ok = (kr < nk) && !(gap_end > 0u && (kc + kr) >= 64u && (kc + kr) < gap_end);
            if (ok) {
                device const kv_t * vrow = vblk + kr;
                const ushort u = ((device const ushort *) vrow->qs)[col4];
                u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        threadgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
        auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#else
        device half * vptr = (device half *) (KV + p.v_base + (ulong(g) * ulong(p.cap) + ulong(k_idx0)) * HD);
        auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
        if (passes & 2u) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                if (m_row[sg][ix[1]] == -INFINITY) cO[i] = 0.0f;
            }
        }
    }

    for (uint r = 0u; r < nr; ++r) {
        if (live_r[r] && lane == 0u) {
            const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
            device float * P = A + part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2);
            P[0] = TC_M_OUT(m_row[sg][r]);
            P[1] = (l_row[sg][r] * TC_INV_EXP8) + 0.0f;
        }
    }
    for (short i = 0; i < cO.get_capacity(); ++i) {
        const auto ix = cO.get_multidimensional_index(i);
        const uint r = uint(ix[1]), d = uint(ix[0]);
        if (r < nr && live_r[r]) {
            const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
            A[part_off + (h * p.nsplit + local_sp_r[r]) * (HD + 2) + 2 + d] = (cO[i] * TC_INV_EXP8) + 0.0f;
        }
    }
}

// Layer 2 `encode_decode` split-K attention using the exact same `matmul2d` fixed-split arithmetic (128 threads = 4 SGs).
kernel void k_attn_tc_dec(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device kv_t * KV [[buffer(3)]],
    device float * CS [[buffer(4)]],
    constant AttnArgs & a [[buffer(5)]],
    device atomic_uint * CTR [[buffer(7)]],
    uint2 tgp [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]],
    ushort sg [[simdgroup_index_in_threadgroup]],
    ushort lane [[thread_index_in_simdgroup]]
) {
    (void) CTR;
    threadgroup float  red[4][8];
    threadgroup half4  q_sh4[3][TC_ATT_ROWS * (HD / 4)];
    threadgroup float4 rs_sh4[3][NREL / 4];
    threadgroup half4  cur_k4[HD / 4];
    threadgroup half4  cur_v4[HD / 4];
    threadgroup TcKvScore u_ks;
    threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float  m_row[3];
    threadgroup float  l_row[3];
    threadgroup float  alpha_row[3];
    threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;

    const uint sp = tgp.x, g = tgp.y;
    const uint p_lo = a.first_pos;
    const uint p_hi = a.first_pos + a.nkeys;
    const uint split_start = ((a.pad & 4u) != 0u) ? (p_lo + sp * a.kps) : ((p_lo / a.kps + sp) * a.kps);
    const uint split_end = split_start + a.kps;
    const uint p1 = min(p_hi, split_end);
    const bool owns = (p1 == p_hi) && a.noown == 0;
    const bool dry = (a.pad & 2u) != 0u;
    const bool half_io = (a.pad & 8u) != 0u;
    const float tau = half_io
        ? (a.ring ? 1.0f : (1.0f + a.log_alpha * log(max(1.0f, float(a.pos + 1u) / a.log_floor))))
        : a.tau;
    device const float * qclip = (device const float *) (PB + a.qclip_w);

    float q[3];
    for (int h = 0; h < 3; h++) {
        const uint H = g * 3u + uint(h);
        const float qraw = half_io ? float(((device const half *) (A + a.q_off))[H * HD + tid]) : A[a.q_off + H * HD + tid];
        q[h] = qraw * qclip[H * HD + tid];
    }
    float kx = 0.0f, vx = 0.0f;
    if (owns) {
        const uint c = g * HD + tid;
        const float scl = a.kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
        for (int which = 0; which < 2; which++) {
            const uint ch = uint(which) * (NKV * HD) + c;
            device const float * w = (device const float *) (PB + (which == 0 ? a.kconv_w : a.vconv_w)) + c * 4;
            device float * hh = CS + a.cs_off + ch * 3;
            const float x = A[(which == 0 ? a.k_off : a.v_off) + c], h0 = hh[0], h1 = hh[1], h2 = hh[2];
            float acc = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * x;
            const int dyn = which == 0 ? a.kdyn_off : a.vdyn_off;
            if (dyn >= 0) { device const float * t = A + dyn + g * 4; acc += t[0] * x + t[1] * h2 + t[2] * h1 + t[3] * h0; }
            if (!dry) { hh[0] = h1; hh[1] = h2; hh[2] = x; }
            if (which == 0) kx = (x + acc) * scl; else vx = (x + acc) * scl;
        }
    }
    float r_val = 0.0f;
    if (tid < 48u) {
        const uint h = tid / 16u, i = tid % 16u, H = g * 3u + h;
        r_val = A[a.r_off + H * NREL + i] * ((device const float *) (PB + a.relclip_w))[H * NREL + i];
    }
    float rn = r_val * r_val;
    rn += simd_shuffle_xor(rn, 1); rn += simd_shuffle_xor(rn, 2); rn += simd_shuffle_xor(rn, 4); rn += simd_shuffle_xor(rn, 8);
    {
        const float s0 = simd_sum(q[0] * q[0]), s1 = simd_sum(q[1] * q[1]), s2 = simd_sum(q[2] * q[2]);
        const float s3 = simd_sum(kx * kx), s4 = simd_sum(vx * vx);
        if (lane == 0u) { red[sg][0] = s0; red[sg][1] = s1; red[sg][2] = s2; red[sg][3] = s3; red[sg][4] = s4; }
#ifdef KV8
        const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
        if (lane == 0u) { red[sg][5] = s5; red[sg][6] = s6; }
#endif
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    float tot[5];
    for (int i = 0; i < 5; i++) tot[i] = red[0][i] + red[1][i] + red[2][i] + red[3][i];

#ifdef KV4
    threadgroup float wht_sh[128];
    const uint slot = (a.pad >> 8) & 0xFFu;
    const float sk_rad = kv4_rademacher(slot * 2u, g, tid);
    const float sv_rad = kv4_rademacher(slot * 2u + 1u, g, tid);
    const float mu_r = kv4_finite_or_zero(float(((device const half *) (PB + KV4_DC_OFF))[(slot * NKV + g) * HD + tid]));
    float dc_bias[3];
    for (int h = 0; h < 3; h++) {
        const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
        const float qr = wht128_tg(sk_rad * (q[h] * f), tid, sg, lane, wht_sh);
        const half qh = half(qr);
        ((threadgroup half *) q_sh4[h])[tid] = qh;
        dc_bias[h] = kv4_finite_or_zero(kv4_reduce128(float(qh) * mu_r, sg, lane, wht_sh));
    }
#else
    for (int h = 0; h < 3; h++) {
        const float f = clamp(QK_CLIP / (sqrt(tot[h]) + 1e-6f), 0.0f, 1.0f) * tau * 0.08838834764831845f;
        ((threadgroup half *) q_sh4[h])[tid] = half(q[h] * f);
    }
#endif
    if (tid < 48u) ((threadgroup float *) rs_sh4[tid / 16u])[tid % 16u] = r_val * clamp(REL_CLIP / (sqrt(rn) + 1e-6f), 0.0f, 1.0f) * tau;
    if (owns) {
        const float kf = clamp(QK_CLIP / (sqrt(tot[3]) + 1e-6f), 0.0f, 1.0f), vf = rsqrt(tot[4] / HD + 1e-6f);
        const float k = kx * kf, v = vx * vf;
        const uint idx = KVIDX(a.pos);
#ifdef KV4
        const float k_rot = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
        const float v_rot = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
        const float k_deq = kv4_pack_row(k_rot, tid, sg, lane, wht_sh, KV + a.k_base + KVROW(g, idx), !dry);
        const float v_deq = kv4_pack_row(v_rot, tid, sg, lane, wht_sh, KV + a.v_base + KVROW(g, idx), !dry);
        ((threadgroup half *) cur_k4)[tid] = half(k_deq);
        ((threadgroup half *) cur_v4)[tid] = half(v_deq);
#elif defined(KV8)
        // the same codes as `k_attn` / `k_kvprep_dec`; attention reads the row back as `int8 x scale`
        const uint ck = kv_code(max(max(red[0][5], red[1][5]), max(red[2][5], red[3][5])) * kf);
        const uint cv = kv_code(max(max(red[0][6], red[1][6]), max(red[2][6], red[3][6])) * vf);
        const float sk = kv_scale(ck), sv = kv_scale(cv);
        const float qk = kv_quant(k, sk, ck, tid), qv = kv_quant(v, sv, cv, tid);
        ((threadgroup half *) cur_k4)[tid] = half(qk * sk);
        ((threadgroup half *) cur_v4)[tid] = half(qv * sv);
        if (!dry) {
            KV[a.k_base + KVROW(g, idx) + tid] = (kv_t) (int) qk;
            KV[a.v_base + KVROW(g, idx) + tid] = (kv_t) (int) qv;
        }
#else
        ((threadgroup half *) cur_k4)[tid] = half(k);
        ((threadgroup half *) cur_v4)[tid] = half(v);
        if (!dry) {
            KV[a.k_base + KVROW(g, idx) + tid] = half(k);
            KV[a.v_base + KVROW(g, idx) + tid] = half(v);
        }
#endif
    }
    float sink_h[3];
#ifdef KV4
    for (int h = 0; h < 3; h++) sink_h[h] = A[a.sink_off + g * 3u + uint(h)] - dc_bias[h];
#else
    for (int h = 0; h < 3; h++) sink_h[h] = A[a.sink_off + g * 3u + uint(h)];
#endif
    if (sg < 3u) {
        if (lane == 0u) {
            m_row[sg] = -INFINITY;
            l_row[sg] = 0.0f;
            alpha_row[sg] = 0.0f;
        }
        for (uint r = 1u; r < TC_ATT_ROWS; ++r) {
            sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
            q_sh4[sg][r * (HD / 4) + lane] = half4(0.0h);
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint sg_clamped = min(uint(sg), 2u);
    auto tQ = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>((threadgroup half *) q_sh4[sg_clamped], dextents<int32_t, 2>(HD, 1), array<int, 2>({1, HD}));
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(u_ks.ss[sg_clamped], dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg_clamped], dextents<int32_t, 2>(TC_ATT_AK, 1), array<int, 2>({1, TC_ATT_AK}));
    auto tKV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tKV0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;

    const float4 rq0 = rs_sh4[sg_clamped][0];
    const float4 rq1 = rs_sh4[sg_clamped][1];
    const float4 rq2 = rs_sh4[sg_clamped][2];
    const float4 rq3 = rs_sh4[sg_clamped][3];

    for (uint kc = split_start; kc < p1; kc += TC_ATT_AK) {
        if (kc + TC_ATT_AK <= p_lo) continue;
        const uint nk = min((uint) TC_ATT_AK, p1 - kc);

        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 128u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const uint kp = kc + kr;
            if (kr < nk) {
                if (owns && kp == a.pos) {
                    u_ks.kv4[idx] = cur_k4[col4];
                } else {
                    const uint kidx = KVIDX(kp);
#ifdef KV4
                    device const kv4_row * krow = KV + a.k_base + KVROW(g, kidx);
                    const ushort u = ((device const ushort *) krow->qs)[col4];
                    u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
#elif defined(KV8)
                    u_ks.kv4[idx] = tc_kv8_deq4(KV + a.k_base + KVROW(g, kidx), col4);
#else
                    u_ks.kv4[idx] = *(device const half4 *) (KV + a.k_base + KVROW(g, kidx) + col4 * 4u);
#endif
                }
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);

        auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        if (sg < 3u) mm_qk.run(tQ, tK, cS);
        threadgroup_barrier(mem_flags::mem_threadgroup);

        if (sg < 3u) {
            cS.store(tS);
            simdgroup_barrier(mem_flags::mem_threadgroup);

            const uint kp = kc + lane;
            const bool valid = (lane < nk) && (kp >= p_lo) && (kp < p1);
            float sc = -INFINITY;
            if (valid) {
                float raw_qk = u_ks.ss[sg][lane];
                if ((a.pos - kp) < EXT) {
                    raw_qk += tc_relbias_dot4(rq0, rq1, rq2, rq3, relb, a.pos - kp);
                }
                sc = raw_qk - sink_h[sg];
            }
            const float m_old = m_row[sg];
            const float m_new = max(m_old, simd_max(sc));
            const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
            const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
            sp_h[sg][lane] = w_p;
            const float w_sum = simd_sum(w_p);
            if (lane == 0u) {
                m_row[sg] = m_new;
                l_row[sg] = l_row[sg] * alpha + w_sum;
                alpha_row[sg] = alpha;
            }
            simdgroup_barrier(mem_flags::mem_threadgroup);

            const float a_s = alpha_row[sg];
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                if (ix[1] == 0) cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);

        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 128u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const uint kp = kc + kr;
            if (kr < nk) {
                if (owns && kp == a.pos) {
                    u_ks.kv4[idx] = cur_v4[col4];
                } else {
                    const uint kidx = KVIDX(kp);
#ifdef KV4
                    device const kv4_row * vrow = KV + a.v_base + KVROW(g, kidx);
                    const ushort u = ((device const ushort *) vrow->qs)[col4];
                    u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
#elif defined(KV8)
                    u_ks.kv4[idx] = tc_kv8_deq4(KV + a.v_base + KVROW(g, kidx), col4);
#else
                    u_ks.kv4[idx] = *(device const half4 *) (KV + a.v_base + KVROW(g, kidx) + col4 * 4u);
#endif
                }
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);

        if (sg < 3u) {
            auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            mm_pv.run(tP, tV, cO);
            if (m_row[sg] == -INFINITY) {
                for (short i = 0; i < cO.get_capacity(); ++i) {
                    const auto ix = cO.get_multidimensional_index(i);
                    if (ix[1] == 0) cO[i] = 0.0f;
                }
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }

    if (sg < 3u) {
        const uint H = g * 3u + uint(sg);
        device float * P = A + a.part_off + (H * a.nsplit + a.sp0 + sp) * (HD + 2);
        if (lane == 0u) {
            P[0] = m_row[sg];
            P[1] = (l_row[sg] * TC_INV_EXP8) + 0.0f;
        }
        for (short i = 0; i < cO.get_capacity(); ++i) {
            const auto ix = cO.get_multidimensional_index(i);
            if (ix[1] == 0) P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
        }
    }
}

// High-occupancy singleton (`count == 1`) Layer 3 paged decode attention (96 threads = 3 SGs, 9.04 KiB FP16 / 11.04 KiB KV4;
// KV8: 32 threads = 1 SG serving all 3 heads, `tc_dec_solo_threads` in `engine.rs`).
// Reads `tQ` directly from device `A` (zero `q_sh` overhead), giving 3 TGs/core in FP16 and 2 TGs/core in KV4 at 1..64 lanes.
kernel void k_attn_tc_dec_solo(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device uchar * KV0 [[buffer(3)]],
    constant AttnGrpDecArgs & a [[buffer(5)]],
    device const ulong * BT_ALL [[buffer(8)]],
    device uchar * KV1 [[buffer(10)]],
    device uchar * KV2 [[buffer(11)]],
    device uchar * KV3 [[buffer(12)]],
    uint2 tgp [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]],
    ushort sg [[simdgroup_index_in_threadgroup]],
    ushort lane [[thread_index_in_simdgroup]]
) {
#ifdef KV8
    // KV8: one simdgroup per (split, KV head) (32 threads, 768 B of threadgroup memory). The 3 GQA query heads are
    // the 3 live rows of ONE `matmul2d(8, 32, 128)` (Q x K_int^T) and ONE `matmul2d(8, 128, 32)` (P' x V_int) per
    // 32-key tile, so each K/V tile is read once (not once per head by 3 simdgroups) and the tensor op computes 8 rows
    // per tile instead of 3 x 16. The 1-row-per-simdgroup version was compute-bound in the padded rows: 2.5x slower
    // than `k_attn_dec_solo` at 24 lanes. `matmul2d` is 0-ULP row-count- and slot-invariant on M5 (8 or 16 rows),
    // and every per-row step below (K scale, bias, sink, online softmax, `P' = w_p x vs`, the dry step's `kv_cur`
    // fold) is the per-head arithmetic in the same order, so the partials stay 0 ULP from `k_attn_tc_fixed_blk` on
    // sealed rows (`tc_attn_cross_kernel_0ulp_m5`).
    if (sg != 0u) return;
    (void) tid;
    const uint gi = tgp.x, g = tgp.y;
    const bool is_swa = (a.swa & 1u) != 0u;
    const bool dry = (a.swa & 2u) != 0u;
    device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
    const uint abs_sp = grp.abs_sp;
    const uint split_start = abs_sp * a.kps;
    const uint split_end = split_start + a.kps;
    const uint si0 = uint(grp.span_idx[0]);
    device const DecodeSpanDesc & d0 = ((device const DecodeSpanDesc *) (A + a.desc_off))[si0];

    const uint pos = d0.pos;
    const uint frs = is_swa ? 0u : d0.full_recent_start;
    const uint frlo = frs / a.kps;
    const uint p_lo = is_swa ? d0.swa_first_pos : ((frs > 0u && abs_sp > 0u) ? frs : 0u);
    const uint p_hi = (!is_swa && frs > 0u && abs_sp == 0u && frlo > 0u)
        ? min(pos + 1u, 64u)
        : min(pos + 1u, split_end);
    if (split_start >= p_hi) return;
    const uint gap_end = (!is_swa && frs > 0u && abs_sp == 0u && frlo == 0u) ? frs : 0u;

    device const ulong * BT = BT_ALL + (is_swa ? d0.bt_win_base : d0.bt_full_base);
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    const uint h0 = g * 3u;
    device const float * relb = (device const float *) (PB + a.relbias_w);
    device const float4 * rq0 = (device const float4 *) (A + a.rp_off + (si0 * NH + h0 + 0u) * NREL);
    device const float4 * rq1 = (device const float4 *) (A + a.rp_off + (si0 * NH + h0 + 1u) * NREL);
    device const float4 * rq2 = (device const float4 *) (A + a.rp_off + (si0 * NH + h0 + 2u) * NREL);
    const float sink0 = A[a.sink_off + si0 * NH + h0 + 0u];
    const float sink1 = A[a.sink_off + si0 * NH + h0 + 1u];
    const float sink2 = A[a.sink_off + si0 * NH + h0 + 2u];

    // S (scores) and P (weights), 3 live rows each; P's rows past 3 are never read (`tP` has 3 rows)
    threadgroup float s_sh[3 * TC_ATT_AK];
    threadgroup float p_sh[3 * TC_ATT_AK];

    device half * qp = (device half *) (A + a.qp_off) + (si0 * NH + h0) * HD;
    auto tQ = tensor(qp, dextents<int32_t, 2>(HD, 3), array<int, 2>({1, HD}));
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(s_sh, dextents<int32_t, 2>(TC_ATT_AK, 3), array<int, 2>({1, TC_ATT_AK}));
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(p_sh, dextents<int32_t, 2>(TC_ATT_AK, 3), array<int, 2>({1, TC_ATT_AK}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_DEC_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_DEC_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

    auto tDev0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tDev0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
    const uint kc_off = a.kv_cur_off + si0 * (2u * NKV * HD) + g * HD;
    const uint vc_off = kc_off + NKV * HD;
    // q . k of the current row in a dry step, whose K/V live only in the `kv_cur` buffer (dequantized floats)
    float cq0 = 0.0f, cq1 = 0.0f, cq2 = 0.0f;
    if (dry) {
        const float4 kf = *(device const float4 *) (A + kc_off + uint(lane) * 4u);
        cq0 = simd_sum(dot(float4(((device const half4 *) (qp + 0u * HD))[lane]), kf));
        cq1 = simd_sum(dot(float4(((device const half4 *) (qp + 1u * HD))[lane]), kf));
        cq2 = simd_sum(dot(float4(((device const half4 *) (qp + 2u * HD))[lane]), kf));
    }
    float m0 = -INFINITY, m1 = -INFINITY, m2 = -INFINITY;
    float l0 = 0.0f, l1 = 0.0f, l2 = 0.0f;

    for (uint kc = split_start; kc < p_hi; kc += TC_ATT_AK) {
        if (kc + TC_ATT_AK <= p_lo) continue;
        if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
        const uint nk = min((uint) TC_ATT_AK, p_hi - kc);
        device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD;
        device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD;
        // `p_hi <= pos + 1`: in a dry step the current row is the tile's last, and the matmuls stop short of its slot
        const bool cur_tile = dry && kc <= pos && pos < kc + nk;
        const bool cur_lane = cur_tile && (kc + lane == pos);
        const uint nk_mat = cur_tile ? (nk - 1u) : nk;
        const float ks = (lane < nk_mat) ? kv_vscale(kptr + uint(lane) * HD) : 1.0f;
        const float vs = (lane < nk_mat) ? kv_vscale(vptr + uint(lane) * HD) : 0.0f;
        if (nk_mat > 0u) {
            auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk_mat), array<int, 2>({1, HD}));
            auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
            mm_qk.run(tQ, tK, cS);
            cS.store(tS);
            simdgroup_barrier(mem_flags::mem_threadgroup);
        }

        const uint kp = kc + lane;
        const bool valid = (lane < nk) && (kp >= p_lo) && (kp < p_hi) && (gap_end == 0u || kp < 64u || kp >= gap_end);
        const bool near = valid && (pos - kp) < EXT;
        float sc0 = -INFINITY, sc1 = -INFINITY, sc2 = -INFINITY;
        if (valid) {
            float r0 = cur_lane ? cq0 : (s_sh[0u * TC_ATT_AK + lane] * ks);
            float r1 = cur_lane ? cq1 : (s_sh[1u * TC_ATT_AK + lane] * ks);
            float r2 = cur_lane ? cq2 : (s_sh[2u * TC_ATT_AK + lane] * ks);
            if (near) {
                r0 += tc_relbias_dot(rq0, relb, pos - kp);
                r1 += tc_relbias_dot(rq1, relb, pos - kp);
                r2 += tc_relbias_dot(rq2, relb, pos - kp);
            }
            sc0 = r0 - sink0;
            sc1 = r1 - sink1;
            sc2 = r2 - sink2;
        }
        const float n0 = max(m0, simd_max(sc0)), n1 = max(m1, simd_max(sc1)), n2 = max(m2, simd_max(sc2));
        const float al0 = (m0 == -INFINITY) ? 0.0f : exp(m0 - n0);
        const float al1 = (m1 == -INFINITY) ? 0.0f : exp(m1 - n1);
        const float al2 = (m2 == -INFINITY) ? 0.0f : exp(m2 - n2);
        const float w0 = (n0 == -INFINITY || !valid) ? 0.0f : exp(sc0 - n0 + 8.0f);
        const float w1 = (n1 == -INFINITY || !valid) ? 0.0f : exp(sc1 - n1 + 8.0f);
        const float w2 = (n2 == -INFINITY || !valid) ? 0.0f : exp(sc2 - n2 + 8.0f);
        p_sh[0u * TC_ATT_AK + lane] = w0 * vs;
        p_sh[1u * TC_ATT_AK + lane] = w1 * vs;
        p_sh[2u * TC_ATT_AK + lane] = w2 * vs;
        const ushort cl = ushort(pos - kc);
        const float cw0 = cur_tile ? simd_shuffle(w0, cl) : 0.0f;
        const float cw1 = cur_tile ? simd_shuffle(w1, cl) : 0.0f;
        const float cw2 = cur_tile ? simd_shuffle(w2, cl) : 0.0f;
        l0 = l0 * al0 + simd_sum(w0);
        l1 = l1 * al1 + simd_sum(w1);
        l2 = l2 * al2 + simd_sum(w2);
        m0 = n0;
        m1 = n1;
        m2 = n2;
        simdgroup_barrier(mem_flags::mem_threadgroup);

        for (short i = 0; i < cO.get_capacity(); ++i) {
            const auto ix = cO.get_multidimensional_index(i);
            const int r = ix[1];
            if (r < 3) {
                const float a_s = (r == 0) ? al0 : ((r == 1) ? al1 : al2);
                cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
            }
        }
        if (nk_mat > 0u) {
            auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk_mat), array<int, 2>({1, HD}));
            mm_pv.run(tP, tV, cO);
            simdgroup_barrier(mem_flags::mem_threadgroup);
        }
        if (cur_tile) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                const int r = ix[1];
                if (r < 3) cO[i] += ((r == 0) ? cw0 : ((r == 1) ? cw1 : cw2)) * A[vc_off + uint(ix[0])];
            }
        }
        if (m0 == -INFINITY || m1 == -INFINITY || m2 == -INFINITY) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                const int r = ix[1];
                if (r < 3 && ((r == 0) ? m0 : ((r == 1) ? m1 : m2)) == -INFINITY) cO[i] = 0.0f;
            }
        }
    }

    const uint nsplit = is_swa ? d0.swa_nsplit : d0.full_nsplit;
    const uint local_sp = is_swa
        ? (abs_sp - (d0.swa_first_pos >> 6))
        : ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
    device float * P0 = A + d0.part_off + ((h0 + 0u) * nsplit + local_sp) * (HD + 2);
    device float * P1 = A + d0.part_off + ((h0 + 1u) * nsplit + local_sp) * (HD + 2);
    device float * P2 = A + d0.part_off + ((h0 + 2u) * nsplit + local_sp) * (HD + 2);
    if (lane == 0u) {
        P0[0] = m0;
        P0[1] = (l0 * TC_INV_EXP8) + 0.0f;
        P1[0] = m1;
        P1[1] = (l1 * TC_INV_EXP8) + 0.0f;
        P2[0] = m2;
        P2[1] = (l2 * TC_INV_EXP8) + 0.0f;
    }
    for (short i = 0; i < cO.get_capacity(); ++i) {
        const auto ix = cO.get_multidimensional_index(i);
        const int r = ix[1];
        if (r < 3) {
            device float * P = (r == 0) ? P0 : ((r == 1) ? P1 : P2);
            P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
        }
    }
#else
    if (sg >= 3u) return;
    const uint gi = tgp.x, g = tgp.y;
    const bool is_swa = (a.swa & 1u) != 0u;
    const bool dry = (a.swa & 2u) != 0u;
    device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
    const uint abs_sp = grp.abs_sp;
    const uint split_start = abs_sp * a.kps;
    const uint split_end = split_start + a.kps;
    const uint si0 = uint(grp.span_idx[0]);
    device const DecodeSpanDesc & d0 = ((device const DecodeSpanDesc *) (A + a.desc_off))[si0];

    const uint pos = d0.pos;
    const uint frs = is_swa ? 0u : d0.full_recent_start;
    const uint frlo = frs / a.kps;
    const uint p_lo = is_swa ? d0.swa_first_pos : ((frs > 0u && abs_sp > 0u) ? frs : 0u);
    const uint p_hi = (!is_swa && frs > 0u && abs_sp == 0u && frlo > 0u)
        ? min(pos + 1u, 64u)
        : min(pos + 1u, split_end);
    if (split_start >= p_hi) return;
    const uint gap_end = (!is_swa && frs > 0u && abs_sp == 0u && frlo == 0u) ? frs : 0u;

    device const ulong * BT = BT_ALL + (is_swa ? d0.bt_win_base : d0.bt_full_base);
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    const uint h = g * 3u + uint(sg);
    device const float * relb = (device const float *) (PB + a.relbias_w);
    device const float4 * rq = (device const float4 *) (A + a.rp_off + (si0 * NH + h) * NREL);
    const float sink_h = A[a.sink_off + si0 * NH + h];

    threadgroup TcKvScore u_ks;
    threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
    threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float m_row[3];
    threadgroup float l_row[3];
    threadgroup float alpha_row[3];

    if (lane == 0u) {
        m_row[sg] = -INFINITY;
        l_row[sg] = 0.0f;
        alpha_row[sg] = 0.0f;
    }
    for (uint r = 1u; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
    simdgroup_barrier(mem_flags::mem_threadgroup);

    auto tQ = tensor((device half *) (A + a.qp_off) + (si0 * NH + h) * HD, dextents<int32_t, 2>(HD, 1), array<int, 2>({1, NH * HD}));
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(u_ks.ss[sg], dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, 1), array<int, 2>({1, TC_ATT_AK}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

#ifdef KV4
    auto tKV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tKV0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
    const uint kc_off = a.kv_cur_off + si0 * (2u * NKV * HD) + g * HD;
    const uint vc_off = kc_off + NKV * HD;
#else
    auto tDev0 = tensor((device half *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tDev0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;
    const uint kc_off = a.kv_cur_off + si0 * (2u * NKV * HD) + g * HD;
    const uint vc_off = kc_off + NKV * HD;
    (void) tid;
#endif

    for (uint kc = split_start; kc < p_hi; kc += TC_ATT_AK) {
        if (kc + TC_ATT_AK <= p_lo) continue;
        if (gap_end > 0u && kc >= 64u && kc + TC_ATT_AK <= gap_end) continue;
        const uint nk = min((uint) TC_ATT_AK, p_hi - kc);

#ifdef KV4
        device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const uint kp = kc + kr;
            const bool ok = (kr < nk) && !(gap_end > 0u && kp >= 64u && kp < gap_end);
            if (ok) {
                if (dry && kp == pos) {
                    u_ks.kv4[idx] = half4(*(device const float4 *) (A + kc_off + col4 * 4u));
                } else {
                    device const kv_t * krow = kblk + kr;
                    const ushort u = ((device const ushort *) krow->qs)[col4];
                    u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
                }
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#else
        if (dry && kc <= pos && pos < kc + nk) {
            // the staged tile overwrites every simdgroup's score tile (`u_ks` is a union): wait until all of them have
            // read the previous tile's scores, which only a simdgroup barrier ordered
            threadgroup_barrier(mem_flags::mem_threadgroup);
            device const half4 * kblk4 = (device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD);
            for (uint idx = sg * 32u + lane; idx < TC_ATT_AK * 32u; idx += 96u) {
                const uint kr = idx >> 5, col4 = idx & 31u;
                const uint kp = kc + kr;
                if (kr < nk) {
                    u_ks.kv4[idx] = (kp == pos) ? half4(*(device const float4 *) (A + kc_off + col4 * 4u)) : kblk4[kr * 32u + col4];
                } else {
                    u_ks.kv4[idx] = half4(0.0h);
                }
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);
            auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
            mm_qk.run(tQ, tK, cS);
            threadgroup_barrier(mem_flags::mem_threadgroup);
            cS.store(tS);
            simdgroup_barrier(mem_flags::mem_threadgroup);
        } else {
            device half * kptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD);
            auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
            mm_qk.run(tQ, tK, cS);
            cS.store(tS);
            simdgroup_barrier(mem_flags::mem_threadgroup);
        }
#endif

        const uint kp = kc + lane;
        const bool valid = (lane < nk) && (kp >= p_lo) && (kp < p_hi) && (gap_end == 0u || kp < 64u || kp >= gap_end);
        float sc = -INFINITY;
        if (valid) {
            float raw_qk = u_ks.ss[sg][lane];
            if ((pos - kp) < EXT) {
                raw_qk += tc_relbias_dot(rq, relb, pos - kp);
            }
            sc = raw_qk - sink_h;
        }
        const float m_old = m_row[sg];
        const float m_new = max(m_old, simd_max(sc));
        const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
        const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
        sp_h[sg][lane] = w_p;
        const float w_sum = simd_sum(w_p);
        if (lane == 0u) {
            m_row[sg] = m_new;
            l_row[sg] = l_row[sg] * alpha + w_sum;
            alpha_row[sg] = alpha;
        }
        simdgroup_barrier(mem_flags::mem_threadgroup);

        const float a_s = alpha_row[sg];
        for (short i = 0; i < cO.get_capacity(); ++i) {
            const auto ix = cO.get_multidimensional_index(i);
            if (ix[1] == 0) cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
        }

#ifdef KV4
        threadgroup_barrier(mem_flags::mem_threadgroup);
        device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            const uint kp2 = kc + kr;
            const bool ok = (kr < nk) && !(gap_end > 0u && kp2 >= 64u && kp2 < gap_end);
            if (ok) {
                if (dry && kp2 == pos) {
                    u_ks.kv4[idx] = half4(*(device const float4 *) (A + vc_off + col4 * 4u));
                } else {
                    device const kv_t * vrow = vblk + kr;
                    const ushort u = ((device const ushort *) vrow->qs)[col4];
                    u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
                }
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        threadgroup_barrier(mem_flags::mem_threadgroup);
#else
        if (dry && kc <= pos && pos < kc + nk) {
            threadgroup_barrier(mem_flags::mem_threadgroup);
            device const half4 * vblk4 = (device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
            for (uint idx = sg * 32u + lane; idx < TC_ATT_AK * 32u; idx += 96u) {
                const uint kr = idx >> 5, col4 = idx & 31u;
                const uint kp2 = kc + kr;
                if (kr < nk) {
                    u_ks.kv4[idx] = (kp2 == pos) ? half4(*(device const float4 *) (A + vc_off + col4 * 4u)) : vblk4[kr * 32u + col4];
                } else {
                    u_ks.kv4[idx] = half4(0.0h);
                }
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);
            // Accumulate via temporary inline cooperative tensor matching tV_sh
            mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
                TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
                execution_simdgroup> mm_pv_sh;
            auto tV_sh = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            auto cO_sh = mm_pv_sh.get_destination_cooperative_tensor<decltype(tP), decltype(tV_sh), float>();
            for (short i = 0; i < cO_sh.get_capacity(); ++i) cO_sh[i] = cO[i];
            mm_pv_sh.run(tP, tV_sh, cO_sh);
            for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = cO_sh[i];
            threadgroup_barrier(mem_flags::mem_threadgroup);
        } else {
            device half * vptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
            auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            mm_pv.run(tP, tV, cO);
            simdgroup_barrier(mem_flags::mem_threadgroup);
        }
#endif
        if (m_row[sg] == -INFINITY) {
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                if (ix[1] == 0) cO[i] = 0.0f;
            }
        }
    }

    const uint nsplit = is_swa ? d0.swa_nsplit : d0.full_nsplit;
    const uint local_sp = is_swa
        ? (abs_sp - (d0.swa_first_pos >> 6))
        : ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
    device float * P = A + d0.part_off + (h * nsplit + local_sp) * (HD + 2);
    if (lane == 0u) {
        P[0] = m_row[sg];
        P[1] = (l_row[sg] * TC_INV_EXP8) + 0.0f;
    }
    for (short i = 0; i < cO.get_capacity(); ++i) {
        const auto ix = cO.get_multidimensional_index(i);
        if (ix[1] == 0) P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
    }
#endif
}

// Layer 3 multi-query shared-KV grouped (`count in 2..=8`) decode attention (96 threads = 3 SGs).
// Shared splits are sealed interior splits (`!dry`), so FP16 reads `tK`/`tV` directly from device `BT` with zero KV staging.
kernel void k_attn_tc_grp_dec(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device uchar * KV0 [[buffer(3)]],
    constant AttnGrpDecArgs & a [[buffer(5)]],
    device const ulong * BT_ALL [[buffer(8)]],
    device uchar * KV1 [[buffer(10)]],
    device uchar * KV2 [[buffer(11)]],
    device uchar * KV3 [[buffer(12)]],
    uint2 tgp [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]],
    ushort sg [[simdgroup_index_in_threadgroup]],
    ushort lane [[thread_index_in_simdgroup]]
) {
#ifndef KV4
    (void) tid;
#endif
    if (sg >= 3u) return;
    const uint gi = tgp.x, g = tgp.y;
    const bool is_swa = (a.swa & 1u) != 0u;
    device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
    const uint m = grp.count;
    if (m == 0u) return;
    const uint abs_sp = grp.abs_sp;
    const uint split_start = abs_sp * a.kps;
    const uint split_end = split_start + a.kps;
    device const DecodeSpanDesc * descs = (device const DecodeSpanDesc *) (A + a.desc_off);

    const uint si0 = uint(grp.span_idx[0]);
    device const DecodeSpanDesc & d0 = descs[si0];
    device const ulong * BT = BT_ALL + (is_swa ? d0.bt_win_base : d0.bt_full_base);
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    const uint h = g * 3u + uint(sg);
    device const float * relb = (device const float *) (PB + a.relbias_w);

    threadgroup half4 q_sh4[3][TC_ATT_ROWS * (HD / 4)];
#ifdef KV4
    threadgroup TcKvScore u_ks;
    threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
    threadgroup float * ss_sg = u_ks.ss[sg];
#else
    threadgroup float ss[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float * ss_sg = ss[sg];
#endif
    threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float m_row[3][TC_ATT_ROWS];
    threadgroup float l_row[3][TC_ATT_ROWS];
    threadgroup float alpha_row[3][TC_ATT_ROWS];

    uint pos_r[DEC_GRP_MAX], p_lo_r[DEC_GRP_MAX], p_hi_r[DEC_GRP_MAX];
    float sink_r[DEC_GRP_MAX];
    uint k_min_tg = ~0u, p_max_tg = 0u;

    for (uint r = 0u; r < m; ++r) {
        const uint si = uint(grp.span_idx[r]);
        device const DecodeSpanDesc & d = descs[si];
        const uint pos = d.pos;
        const uint frs = is_swa ? 0u : d.full_recent_start;
        const uint frlo = frs / a.kps;
        const uint plo = is_swa ? d.swa_first_pos : ((frs > 0u && abs_sp > 0u) ? frs : 0u);
        const uint phi = (!is_swa && frs > 0u && abs_sp == 0u && frlo > 0u)
            ? min(pos + 1u, 64u)
            : min(pos + 1u, split_end);
        pos_r[r] = pos;
        p_lo_r[r] = plo;
        p_hi_r[r] = phi;
        sink_r[r] = A[a.sink_off + si * NH + h];
        if (split_start < phi) {
            k_min_tg = min(k_min_tg, plo);
            p_max_tg = max(p_max_tg, phi);
        }
        device const half4 * qsrc = (device const half4 *) ((device const half *) (A + a.qp_off) + (si * NH + h) * HD);
        q_sh4[sg][r * (HD / 4) + lane] = qsrc[lane];
    }
    if (p_max_tg == 0u) return;

    if (lane < TC_ATT_ROWS) {
        m_row[sg][lane] = -INFINITY;
        l_row[sg][lane] = 0.0f;
        alpha_row[sg][lane] = 0.0f;
    }
    for (uint r = m; r < TC_ATT_ROWS; ++r) {
        sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
        q_sh4[sg][r * (HD / 4) + lane] = half4(0.0h);
    }
    simdgroup_barrier(mem_flags::mem_threadgroup);

    auto tQ = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>((threadgroup half *) q_sh4[sg], dextents<int32_t, 2>(HD, (int) m), array<int, 2>({1, HD}));
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(ss_sg, dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, (int) m), array<int, 2>({1, TC_ATT_AK}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_GRP_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_GRP_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

#ifdef KV4
    auto tV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#elif defined(KV8)
    auto tV0 = tensor((device kv_t *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#else
    auto tV0 = tensor((device half *) KV0, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));
#endif
    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tV0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;

    for (uint kc = split_start; kc < p_max_tg; kc += TC_ATT_AK) {
        if (kc + TC_ATT_AK <= k_min_tg) continue;
        const uint nk = min((uint) TC_ATT_AK, p_max_tg - kc);

#ifdef KV4
        device const kv_t * kblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            if (kr < nk) {
                device const kv_t * krow = kblk + kr;
                const ushort u = ((device const ushort *) krow->qs)[col4];
                u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
        // sealed interior splits: int8 rows straight into `matmul2d`, as `k_attn_tc_fixed_blk`
        device kv_t * kptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD;
        device kv_t * vptr = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD;
        auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
        const float ks = (lane < nk) ? kv_vscale(kptr + uint(lane) * HD) : 0.0f;
        const float vs = (lane < nk) ? kv_vscale(vptr + uint(lane) * HD) : 0.0f;
#else
        device half * kptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, koff) + (kc & KV_BLK_MASK) * HD);
        auto tK = tensor(kptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
        mm_qk.run(tQ, tK, cS);
        cS.store(tS);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#endif

        for (uint r = 0u; r < m; ++r) {
            const uint pos = pos_r[r];
            const uint kp = kc + lane;
            const bool valid = (lane < nk) && (kp >= p_lo_r[r]) && (kp < p_hi_r[r]);
            float sc = -INFINITY;
            if (valid) {
#ifdef KV8
                float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;
#else
                float raw_qk = ss_sg[r * TC_ATT_AK + lane];
#endif
                if ((pos - kp) < EXT) {
                    const uint si = uint(grp.span_idx[r]);
                    device const float4 * rq = (device const float4 *) (A + a.rp_off + (si * NH + h) * NREL);
                    raw_qk += tc_relbias_dot(rq, relb, pos - kp);
                }
                sc = raw_qk - sink_r[r];
            }
            const float m_old = m_row[sg][r];
            const float m_new = max(m_old, simd_max(sc));
            const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
            const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
#ifdef KV8
            sp_h[sg][r * TC_ATT_AK + lane] = w_p * vs;
#else
            sp_h[sg][r * TC_ATT_AK + lane] = w_p;
#endif
            const float w_sum = simd_sum(w_p);
            if (lane == 0u) {
                m_row[sg][r] = m_new;
                l_row[sg][r] = l_row[sg][r] * alpha + w_sum;
                alpha_row[sg][r] = alpha;
            }
        }
        simdgroup_barrier(mem_flags::mem_threadgroup);

        for (short i = 0; i < cO.get_capacity(); ++i) {
            const auto ix = cO.get_multidimensional_index(i);
            const float a_s = alpha_row[sg][ix[1]];
            cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
        }
#ifdef KV4
        threadgroup_barrier(mem_flags::mem_threadgroup);
        device const kv_t * vblk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * KV_ROW_STEP;
        for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
            const uint kr = idx >> 5, col4 = idx & 31u;
            if (kr < nk) {
                device const kv_t * vrow = vblk + kr;
                const ushort u = ((device const ushort *) vrow->qs)[col4];
                u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
            } else {
                u_ks.kv4[idx] = half4(0.0h);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        threadgroup_barrier(mem_flags::mem_threadgroup);
#elif defined(KV8)
        auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#else
        device half * vptr = (device half *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kc >> 6, voff) + (kc & KV_BLK_MASK) * HD);
        auto tV = tensor(vptr, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
        mm_pv.run(tP, tV, cO);
        simdgroup_barrier(mem_flags::mem_threadgroup);
#endif
        for (short i = 0; i < cO.get_capacity(); ++i) {
            const auto ix = cO.get_multidimensional_index(i);
            if (m_row[sg][ix[1]] == -INFINITY) cO[i] = 0.0f;
        }
    }

    for (uint r = 0u; r < m; ++r) {
        const uint si = uint(grp.span_idx[r]);
        device const DecodeSpanDesc & d = descs[si];
        const uint nsplit = is_swa ? d.swa_nsplit : d.full_nsplit;
        const uint frs = is_swa ? 0u : d.full_recent_start;
        const uint frlo = frs / a.kps;
        const uint local_sp = is_swa
            ? (abs_sp - (d.swa_first_pos >> 6))
            : ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
        if (lane == 0u) {
            device float * P = A + d.part_off + (h * nsplit + local_sp) * (HD + 2);
            P[0] = m_row[sg][r];
            P[1] = (l_row[sg][r] * TC_INV_EXP8) + 0.0f;
        }
    }
    for (short i = 0; i < cO.get_capacity(); ++i) {
        const auto ix = cO.get_multidimensional_index(i);
        const uint r = uint(ix[1]), d_col = uint(ix[0]);
        if (r < m) {
            const uint si = uint(grp.span_idx[r]);
            device const DecodeSpanDesc & d = descs[si];
            const uint nsplit = is_swa ? d.swa_nsplit : d.full_nsplit;
            const uint frs = is_swa ? 0u : d.full_recent_start;
            const uint frlo = frs / a.kps;
            const uint local_sp = is_swa
                ? (abs_sp - (d.swa_first_pos >> 6))
                : ((frs > 0u && abs_sp > 0u && frlo > 0u) ? (1u + abs_sp - frlo) : abs_sp);
            A[d.part_off + (h * nsplit + local_sp) * (HD + 2) + 2 + d_col] = (cO[i] * TC_INV_EXP8) + 0.0f;
        }
    }
}

// Sparse Top-K decode attention (`--sparse-topk` L2 & L3) using the identical `matmul2d` sub-tile math (96 threads = 3 SGs).
kernel void k_attn_tc_sparse_dec(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device uchar * KV0 [[buffer(3)]],
    constant AttnSparseDecArgs & a [[buffer(5)]],
    device const ulong * BT_ALL [[buffer(8)]],
    device uchar * KV1 [[buffer(10)]],
    device uchar * KV2 [[buffer(11)]],
    device uchar * KV3 [[buffer(12)]],
    device const uint * SPARSE_BUF [[buffer(14)]],
    uint3 tgp [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]],
    ushort sg [[simdgroup_index_in_threadgroup]],
    ushort lane [[thread_index_in_simdgroup]]
) {
    if (sg >= 3u) return;
    const uint sp = tgp.x, g = tgp.y, u_task = tgp.z;
    if (u_task >= a.n_tasks) return;
    device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
    if (sp >= task.nsplit) return;

    const bool cur_from_buf = ((task.flags & 2u) != 0u) || (a.pad0 != 0u);
    const uint h = g * 3u + uint(sg);

    threadgroup TcKvScore u_ks;
    threadgroup half * kv_sh = (threadgroup half *) u_ks.kv4;
    threadgroup float sp_h[3][TC_ATT_ROWS * TC_ATT_AK];
    threadgroup float m_row[3];
    threadgroup float l_row[3];
    threadgroup float alpha_row[3];

    device const float4 * rq = (device const float4 *) (A + task.rp_off + h * NREL);
    const float sink_h = A[task.sink_off + h];
    if (lane == 0u) {
        m_row[sg] = -INFINITY;
        l_row[sg] = 0.0f;
        alpha_row[sg] = 0.0f;
    }
    for (uint r = 1u; r < TC_ATT_ROWS; ++r) sp_h[sg][r * TC_ATT_AK + lane] = 0.0f;
    simdgroup_barrier(mem_flags::mem_threadgroup);

    device const uint * sel_blks = SPARSE_BUF + a.sel_u32_base
                                 + ulong(a.pass_idx) * ulong(a.pass_sel_stride)
                                 + ulong(task.sel_out_base)
                                 + ulong(g) * ulong(task.total_sel_blks);
    const uint sel_lo = sp * task.blks_per_split;
    const uint sel_hi = min(sel_lo + task.blks_per_split, task.total_sel_blks);

    device const ulong * BT = (a.is_paged != 0u) ? (BT_ALL + task.bt_full_base) : nullptr;
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    const ulong l2_plane_elems = ulong(NKV) * ulong(task.kv_cap) * ulong(KV_ROW_STEP);
    device const kv_t * l2_k_pass = ((device const kv_t *) KV0) + ulong(a.pass_idx) * 2ul * l2_plane_elems + ulong(g) * ulong(task.kv_cap) * ulong(KV_ROW_STEP);
    device const kv_t * l2_v_pass = l2_k_pass + l2_plane_elems;
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const uint pos = task.pos;
    const uint kc_off = task.kv_cur_off + g * HD;
    const uint vc_off = kc_off + NKV * HD;

    auto tQ = tensor((device half *) (A + task.qp_off) + h * HD, dextents<int32_t, 2>(HD, 1), array<int, 2>({1, NH * HD}));
    auto tS = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(u_ks.ss[sg], dextents<int32_t, 2>(TC_ATT_AK, TC_ATT_ROWS));
    auto tP = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sp_h[sg], dextents<int32_t, 2>(TC_ATT_AK, 1), array<int, 2>({1, TC_ATT_AK}));
    auto tKV0 = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, TC_ATT_AK), array<int, 2>({1, HD}));

    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, TC_ATT_AK, HD, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
        execution_simdgroup> mm_qk;
    mpp::tensor_ops::matmul2d<mpp::tensor_ops::matmul2d_descriptor(
        TC_ATT_ROWS, HD, TC_ATT_AK, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
        execution_simdgroup> mm_pv;

    auto cO = mm_pv.get_destination_cooperative_tensor<decltype(tP), decltype(tKV0), float>();
    for (short i = 0; i < cO.get_capacity(); ++i) cO[i] = 0.0f;

    for (uint bi_idx = sel_lo; bi_idx < sel_hi; ++bi_idx) {
        const uint blk = sel_blks[bi_idx];
        const uint blk_p0 = blk * KV_BLK;
        const uint p1 = min(pos + 1u, blk_p0 + KV_BLK);
        if (blk_p0 >= p1) continue;
        device const kv_t * k_blk = (a.is_paged != 0u)
            ? kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff)
            : (l2_k_pass + ulong(blk_p0) * ulong(KV_ROW_STEP));
        device const kv_t * v_blk = (a.is_paged != 0u)
            ? kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff)
            : (l2_v_pass + ulong(blk_p0) * ulong(KV_ROW_STEP));

        for (uint sub = 0u; sub < KV_BLK; sub += TC_ATT_AK) {
            const uint kc = blk_p0 + sub;
            if (kc >= p1) break;
            const uint nk = min((uint) TC_ATT_AK, p1 - kc);

            for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
                const uint kr = idx >> 5, col4 = idx & 31u;
                const uint kp = kc + kr;
                if (kr < nk) {
                    if (cur_from_buf && kp == pos) {
                        u_ks.kv4[idx] = half4(*(device const float4 *) (A + kc_off + col4 * 4u));
                    } else {
                        const uint ib = sub + kr;
#ifdef KV4
                        device const kv_t * krow = k_blk + ib;
                        const ushort u = ((device const ushort *) krow->qs)[col4];
                        u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(krow->sc));
#elif defined(KV8)
                        u_ks.kv4[idx] = tc_kv8_deq4(k_blk + ib * HD, col4);
#else
                        u_ks.kv4[idx] = *(device const half4 *) (k_blk + ib * HD + col4 * 4u);
#endif
                    }
                } else {
                    u_ks.kv4[idx] = half4(0.0h);
                }
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);

            auto tK = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            auto cS = mm_qk.get_destination_cooperative_tensor<decltype(tQ), decltype(tK), float>();
            mm_qk.run(tQ, tK, cS);
            threadgroup_barrier(mem_flags::mem_threadgroup);
            cS.store(tS);
            simdgroup_barrier(mem_flags::mem_threadgroup);

            const uint kp = kc + lane;
            const bool valid = lane < nk;
            float sc = -INFINITY;
            if (valid) {
                float raw_qk = u_ks.ss[sg][lane];
                if ((pos - kp) < EXT) {
                    raw_qk += tc_relbias_dot(rq, relb, pos - kp);
                }
                sc = raw_qk - sink_h;
            }
            const float m_old = m_row[sg];
            const float m_new = max(m_old, simd_max(sc));
            const float alpha = (m_old == -INFINITY) ? 0.0f : exp(m_old - m_new);
            const float w_p = (m_new == -INFINITY || !valid) ? 0.0f : exp(sc - m_new + 8.0f);
            sp_h[sg][lane] = w_p;
            const float w_sum = simd_sum(w_p);
            if (lane == 0u) {
                m_row[sg] = m_new;
                l_row[sg] = l_row[sg] * alpha + w_sum;
                alpha_row[sg] = alpha;
            }
            simdgroup_barrier(mem_flags::mem_threadgroup);

            const float a_s = alpha_row[sg];
            for (short i = 0; i < cO.get_capacity(); ++i) {
                const auto ix = cO.get_multidimensional_index(i);
                if (ix[1] == 0) cO[i] = (a_s == 0.0f) ? 0.0f : (cO[i] * a_s);
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);

            for (uint idx = tid; idx < TC_ATT_AK * 32u; idx += 96u) {
                const uint kr = idx >> 5, col4 = idx & 31u;
                const uint kp2 = kc + kr;
                if (kr < nk) {
                    if (cur_from_buf && kp2 == pos) {
                        u_ks.kv4[idx] = half4(*(device const float4 *) (A + vc_off + col4 * 4u));
                    } else {
                        const uint ib = sub + kr;
#ifdef KV4
                        device const kv_t * vrow = v_blk + ib;
                        const ushort u = ((device const ushort *) vrow->qs)[col4];
                        u_ks.kv4[idx] = half4(kv4_u16_to_f4(u) * float(vrow->sc));
#elif defined(KV8)
                        u_ks.kv4[idx] = tc_kv8_deq4(v_blk + ib * HD, col4);
#else
                        u_ks.kv4[idx] = *(device const half4 *) (v_blk + ib * HD + col4 * 4u);
#endif
                    }
                } else {
                    u_ks.kv4[idx] = half4(0.0h);
                }
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);

            auto tV = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>(kv_sh, dextents<int32_t, 2>(HD, (int) nk), array<int, 2>({1, HD}));
            mm_pv.run(tP, tV, cO);
            threadgroup_barrier(mem_flags::mem_threadgroup);

            if (m_row[sg] == -INFINITY) {
                for (short i = 0; i < cO.get_capacity(); ++i) {
                    const auto ix = cO.get_multidimensional_index(i);
                    if (ix[1] == 0) cO[i] = 0.0f;
                }
            }
        }
    }

    device float * P = A + task.part_off + (h * task.nsplit + sp) * (HD + 2);
    if (lane == 0u) {
        P[0] = m_row[sg];
        P[1] = (l_row[sg] * TC_INV_EXP8) + 0.0f;
    }
    for (short i = 0; i < cO.get_capacity(); ++i) {
        const auto ix = cO.get_multidimensional_index(i);
        if (ix[1] == 0) P[2 + uint(ix[0])] = (cO[i] * TC_INV_EXP8) + 0.0f;
    }
}
#endif // NO_MPP