inky-engine 3.0.1

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
// Inkling 2 Mini (inkling2_loop) fused Metal kernels.
// Buffers: 0 = W (mmapped GGUF, quantized weights), 1 = PB (small f32 params + bf16 matrices),
//          2 = A (f32 activation arena), 3 = KV (K/V cache), 4 = CS (f32 conv state), 5 = args.
#include <metal_stdlib>
#ifndef NO_MPP
#include <metal_tensor>
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
#endif
using namespace metal;

#define E      2304
#define NH     24
#define NKV    8
#define HD     128
#define NREL   16
#define EXT    1024
#define NEXP   128
#define TOPK   8
#define FF     1152
#define QK_CLIP 22.627416610717773f
#define REL_CLIP 8.0f

// ---- K/V cache element type.
// Default: fp16, the values the model computed. With KV8 (the opt-in "--kv8" cache, half the size, NOT exact): one signed
// byte per value, v[i] = q[i] * s per 128-value vector. The scale costs no space: s is one of 256 steps
// s(c) = (8 + (c & 7)) * 2^((c >> 3) - 20) (so every q * s is exact in fp16 and f32), and the 8 bits of c are the lowest bits of
// the vector's first 8 bytes (bit 7 - i in byte i) - those 8 values are rounded to the even or odd integers.
// Every reader, including the token's own step, uses the stored values, so batched and single-token paths agree.
#ifdef KV4
#if HD != 128
#error "KV4 WHT-128 66-byte row layout requires HD == 128"
#endif
#ifndef KV4_DC_OFF
#define KV4_DC_OFF 0u
#endif
struct kv4_row { uchar qs[64]; half sc; };
static_assert(sizeof(kv4_row) == 66, "kv4_row must be 66 bytes");
typedef kv4_row kv_t;
typedef ushort kvw_t;

constant float LM4_VAL[16] = {
    -2.7325896f, -2.0690172f, -1.6180464f, -1.2562312f,
    -0.9423405f, -0.6567591f, -0.3880483f, -0.1283950f,
     0.1283950f,  0.3880483f,  0.6567591f,  0.9423405f,
     1.2562312f,  1.6180464f,  2.0690172f,  2.7325896f
};
constant float LM4_THR[15] = {
    -2.4008034f, -1.8435318f, -1.4371388f, -1.0992858f, -0.7995498f,
    -0.5224037f, -0.2582217f,  0.0f,        0.2582217f,  0.5224037f,
     0.7995498f,  1.0992858f,  1.4371388f,  1.8435318f,  2.4008034f
};

inline float kv4_finite_or_zero(float x) {
    #pragma clang fp contract(off) reassociate(off)
    return (!isnan(x) && !isinf(x)) ? x : 0.0f;
}

inline uchar kv4_lm4_idx(float z) {
    #pragma clang fp contract(off) reassociate(off)
    if (isnan(z) || isinf(z)) return 8u;
    uint idx = (z >= LM4_THR[7]) ? 8u : 0u;
    if (z >= LM4_THR[idx + 3u]) idx += 4u;
    if (z >= LM4_THR[idx + 1u]) idx += 2u;
    if (z >= LM4_THR[idx])      idx += 1u;
    return uchar(idx);
}

inline float kv4_rademacher(uint slot2, uint g, ushort d) {
    #pragma clang fp contract(off) reassociate(off)
    const uint idx = (slot2 * 8u + g) * 128u + uint(d);
    uint h = idx ^ 0x9E3779B9u;
    h ^= h >> 16;
    h *= 0x21F0AAADu;
    h ^= h >> 15;
    h *= 0x735A2D97u;
    h ^= h >> 15;
    return (h >> 31) ? -1.0f : 1.0f;
}

inline float wht128_tg(float v, ushort tid, ushort sg, ushort lane, threadgroup float * sh128) {
    #pragma clang fp contract(off) reassociate(off)
    float t;
    t = simd_shuffle_xor(v, 1);  v = (lane & 1u)  ? (t - v) : (v + t);
    t = simd_shuffle_xor(v, 2);  v = (lane & 2u)  ? (t - v) : (v + t);
    t = simd_shuffle_xor(v, 4);  v = (lane & 4u)  ? (t - v) : (v + t);
    t = simd_shuffle_xor(v, 8);  v = (lane & 8u)  ? (t - v) : (v + t);
    t = simd_shuffle_xor(v, 16); v = (lane & 16u) ? (t - v) : (v + t);
    sh128[tid] = v;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const float a0 = sh128[0 * 32 + lane], a1 = sh128[1 * 32 + lane];
    const float a2 = sh128[2 * 32 + lane], a3 = sh128[3 * 32 + lane];
    const float s0 = a0 + a1, d0 = a0 - a1, s1 = a2 + a3, d1 = a2 - a3;
    const float r = (sg == 0) ? (s0 + s1) : ((sg == 1) ? (d0 + d1) : ((sg == 2) ? (s0 - s1) : (d0 - d1)));
    threadgroup_barrier(mem_flags::mem_threadgroup);
    return r * 0.08838834764831845f;
}

inline float kv4_pack_row_unscaled(float x_rot, ushort tid, ushort sg, ushort lane, threadgroup float * sh128,
                                   device kv4_row * dst, bool write_dst, thread float & out_sc) {
    #pragma clang fp contract(off) reassociate(off)
    const float sq = simd_sum(x_rot * x_rot);
    if (lane == 0) sh128[sg] = sq;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const float rms = sqrt((sh128[0] + sh128[1] + sh128[2] + sh128[3]) * (1.0f / 128.0f));
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const bool valid_rms = (!isnan(rms)) && (!isinf(rms)) && (rms > 0.0f);
    const half sc_h = valid_rms ? half(rms) : half(0.0h);
    const float sc = float(sc_h);
    const bool valid_sc = (!isnan(sc)) && (!isinf(sc)) && (sc > 0.0f);
    out_sc = valid_sc ? sc : 0.0f;
    uchar nib = 8u;
    float uval = 0.0f;
    if (valid_sc && !isnan(x_rot) && !isinf(x_rot)) {
        nib = kv4_lm4_idx(x_rot / sc);
        uval = LM4_VAL[nib];
    }
    const ushort n1 = simd_shuffle_xor(ushort(nib), 1);
    const ushort n2 = simd_shuffle_xor(ushort(nib), 2);
    const ushort n3 = simd_shuffle_xor(ushort(nib), 3);
    if (write_dst) {
        if ((lane & 3u) == 0u) {
            ((device ushort *) dst->qs)[tid >> 2] = ushort(nib) | (n1 << 4) | (n2 << 8) | (n3 << 12);
        }
        if (tid == 0) dst->sc = valid_sc ? sc_h : half(0.0h);
    }
    return uval;
}

inline float kv4_pack_row(float x_rot, ushort tid, ushort sg, ushort lane, threadgroup float * sh128,
                          device kv4_row * dst, bool write_dst) {
    #pragma clang fp contract(off) reassociate(off)
    float sc = 0.0f;
    const float uval = kv4_pack_row_unscaled(x_rot, tid, sg, lane, sh128, dst, write_dst, sc);
    return uval * sc;
}

inline float4 kv4_u16_to_f4(ushort u) {
    #pragma clang fp contract(off) reassociate(off)
    return float4(LM4_VAL[u & 0xFu], LM4_VAL[(u >> 4) & 0xFu], LM4_VAL[(u >> 8) & 0xFu], LM4_VAL[(u >> 12) & 0xFu]);
}

inline float kv4_reduce128(float v, ushort sg, ushort lane, threadgroup float * sh4) {
    const float s = simd_sum(v);
    if (lane == 0) sh4[sg] = s;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const float tot = sh4[0] + sh4[1] + sh4[2] + sh4[3];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    return tot;
}
#elif defined(KV8)
typedef int8_t kv_t;
typedef uint kvw_t;            // 4 consecutive cache elements, for copies
inline float kv_scale(uint c) { return float(8u + (c & 7u)) * as_type<float>(((c >> 3) + 107u) << 23); }
// smallest step that represents a vector whose largest magnitude is mx (126 steps: the first 8 values may only reach the even 126)
inline uint kv_code(float mx) {
    if (!(mx > 0.0f)) return 0u;
    const float t = mx / 126.0f;
    int ex = clamp((int) floor(log2(t)), -17, 14);
    int m = clamp((int) ceil(t * exp2((float) -ex) * 8.0f), 8, 16);
    if (m == 16) { m = 8; ex += 1; }
    uint c = (uint) min(((ex + 17) << 3) | (m - 8), 255);
    if (kv_scale(c) * 126.0f < mx && c < 255u) c += 1u;      // log2 / exp2 rounding must never make the largest value clip
    return c;
}
// the scale of the stored vector that starts at p
inline float kv_vscale(device const kv_t * p) {
    device const uint * w = (device const uint *) p;
    const uint hi = ((w[0] & 0x01010101u) * 0x08040201u) >> 24, lo = ((w[1] & 0x01010101u) * 0x08040201u) >> 24;
    return kv_scale(((hi & 15u) << 4) | (lo & 15u));
}
// element i of a vector with scale code c: the stored integer (as float) nearest to x / s
inline float kv_quant(float x, float s, uint c, ushort i) {
    const float y = x / s;
    if (i < 8) { const float b = float((c >> (7 - i)) & 1u); return clamp(2.0f * rint((y - b) * 0.5f) + b, -127.0f, 127.0f); }
    return clamp(rint(y), -127.0f, 127.0f);
}
#else
typedef half kv_t;
typedef half4 kvw_t;
#endif

struct block_q2_K { uchar scales[16]; uchar qs[64]; half d; half dmin; };
struct block_q3_K { uchar hmask[32]; uchar qs[64]; uchar scales[12]; half d; };
struct block_q4_K { half d; half dmin; uchar scales[12]; uchar qs[128]; };
struct block_q6_K { uchar ql[128]; uchar qh[64]; char scales[16]; half d; };
struct block_q8_0 { half d; char qs[32]; };
struct block_q5_0 { half d; uchar qh[4]; uchar qs[16]; };
struct block_q3_0 { half d; uchar qh[4]; uchar qs[8]; };

inline int q3k_scale(device const uchar * scales, uint is) {
    const uint j = is & 3u;
    const uint lo = (is < 8u) ? (scales[is] & 0xFu) : ((scales[is - 8u] >> 4) & 0xFu);
    const uint hi = (scales[8u + j] >> (2u * (is >> 2))) & 3u;
    return int(lo | (hi << 4)) - 32;
}

inline float bf16f(ushort u) { return as_type<float>(uint(u) << 16); }

// NV4 / MX8 element decoding without tables (chadlyb/erisinky): magnitude bits placed into a half give value * 2^-k,
// for normal and subnormal codes alike. FP4 E2M1 -> x 2^-14; FP8 E4M3 -> x 2^-8.
inline float fp4f(uint n) { return float(as_type<half>(ushort(((n & 8u) << 12) | ((n & 7u) << 9)))); }
inline float e4m3f(uint b) { return float(as_type<half>(ushort(((b & 0x80u) << 8) | ((b & 0x7Fu) << 7)))); }
inline float4 fp4f4(uchar4 q) { return float4(fp4f(q.x), fp4f(q.y), fp4f(q.z), fp4f(q.w)); }
inline float4 e4m3f4(uchar4 q) { return float4(e4m3f(q.x), e4m3f(q.y), e4m3f(q.z), e4m3f(q.w)); }
#define NV4_K 4194304.0f   // 2^22 = 2^14 (fp4) * 2^8 (e4m3 scale)
#define MX8_K 256.0f       // 2^8 (e4m3 value)
#define NV4_BAL 1
inline void fp4x8(uint q, thread float4 & lo, thread float4 & hi) {
    const uint4 w = uint4(as_type<uchar4>(q));
    lo = float4(as_type<half4>(ushort4(((w & 8u) << 12) | ((w & 7u) << 9))));
    hi = float4(as_type<half4>(ushort4(((w & 0x80u) << 8) | ((w & 0x70u) << 5))));
}
inline float2 e4m3f2(uint sc) {
    const uint t = (sc | (sc << 8)) & 0x00FF00FFu;
    return float2(as_type<half2>(((t & 0x00800080u) << 8) | ((t & 0x007F007Fu) << 7)));
}
inline void e4m3x8(device const ushort * p, thread float4 & a, thread float4 & b) {
    const uint4 w0 = uint4(as_type<uchar4>(uint(p[0]) | (uint(p[1]) << 16))), w1 = uint4(as_type<uchar4>(uint(p[2]) | (uint(p[3]) << 16)));
    a = float4(as_type<half4>(ushort4(((w0 & 0x80u) << 8) | ((w0 & 0x7Fu) << 7))));
    b = float4(as_type<half4>(ushort4(((w1 & 0x80u) << 8) | ((w1 & 0x7Fu) << 7))));
}
inline float gscale_at(device const uchar * W, uint lo, uint hi, int e) {
    return ((device const float *) (W + (ulong(hi) << 32 | lo)))[e];
}
inline float sigm(float x) { return 1.0f / (1.0f + exp(-x)); }

// sum over the whole threadgroup; every thread gets the result. sh must hold >= 32 floats.
inline float tg_sum(float v, threadgroup float * sh, ushort sg, ushort lane, ushort nsg) {
    v = simd_sum(v);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (lane == 0) sh[sg] = v;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    float r = lane < nsg ? sh[lane] : 0.0f;
    return simd_sum(r);
}
inline float tg_max(float v, threadgroup float * sh, ushort sg, ushort lane, ushort nsg) {
    v = simd_max(v);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (lane == 0) sh[sg] = v;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    float r = lane < nsg ? sh[lane] : -INFINITY;
    return simd_max(r);
}

// "last threadgroup done" detection: every TG bumps a device counter after its writes; the TG that observes
// count == total-1 is the last to arrive, and resets the counter. The counter and the device-scope fences order the
// arrivals, but they do not by themselves make other TGs' plain device stores visible: device memory is coherent only
// within a threadgroup unless the pointer is `coherent(device)`. Every value one TG stores and the last one reads must
// therefore go through a `coherent(device)` pointer on both sides. Plain pointers race: on the M3 Ultra the last TG of
// `k_ctrl_apply` read whole 32-channel blocks as their stale zeros and wrote them back over the fresh values, so
// single-stream decode logits differed from run to run (KL up to 30).
inline bool last_tg(device atomic_uint * ctr, uint total, ushort tid, threadgroup uint * flag) {
    threadgroup_barrier(mem_flags::mem_device);
    if (tid == 0) {
        atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
        const uint prev = atomic_fetch_add_explicit(ctr, 1u, memory_order_relaxed);
        *flag = (prev == total - 1) ? 1u : 0u;
        if (*flag) atomic_store_explicit(ctr, 0u, memory_order_relaxed);
        atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device);
    }
    threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup);
    return *flag != 0;
}

inline void scale_min_k4(int j, device const uchar * q, thread float & sc, thread float & m) {
    if (j < 4) { sc = q[j] & 63; m = q[j + 4] & 63; }
    else { sc = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); }
}

// ---------------------------------------------------------------------------------------------
// quantized row dot products against x in threadgroup memory. NR rows, row pointers w[r].
// all 32 lanes participate; returns per-lane partial sums in sumf[r] (caller simd_sums).

template <int NR>
inline void dot_q4k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const short ix = lane / 8, it = lane % 8, iq = it / 4, ir = it % 4;
    float yl[16], yh[16];
    for (int ib = ix; ib < nb; ib += 4) {
        device const float * y4 = x + ib * 256 + 64 * iq + 8 * ir;
        float4 sumy = 0.0f;
        for (short i = 0; i < 8; ++i) {
            yl[i + 0] = y4[i +   0]; sumy[0] += yl[i + 0];
            yl[i + 8] = y4[i +  32]; sumy[1] += yl[i + 8];
            yh[i + 0] = y4[i + 128]; sumy[2] += yh[i + 0];
            yh[i + 8] = y4[i + 160]; sumy[3] += yh[i + 8];
        }
        for (short row = 0; row < NR; ++row) {
            device const block_q4_K * b = (device const block_q4_K *) w[row] + ib;
            device const ushort * sc = (device const ushort *) b->scales + iq;
            device const ushort * q1 = (device const ushort *) b->qs + 16 * iq + 4 * ir;
            device const ushort * q2 = q1 + 32;
            ushort sc16[4];
            thread const uchar * sc8 = (thread const uchar *) sc16;
            sc16[0] = sc[0] & 0x3f3f;
            sc16[1] = sc[2] & 0x3f3f;
            sc16[2] = ((sc[4] >> 0) & 0x0f0f) | ((sc[0] & 0xc0c0) >> 2);
            sc16[3] = ((sc[4] >> 4) & 0x0f0f) | ((sc[2] & 0xc0c0) >> 2);
            float4 acc1 = 0.0f, acc2 = 0.0f;
            for (short i = 0; i < 4; ++i) {
                acc1[0] += yl[2 * i + 0] * (q1[i] & 0x000F);
                acc1[1] += yl[2 * i + 1] * (q1[i] & 0x0F00);
                acc1[2] += yl[2 * i + 8] * (q1[i] & 0x00F0);
                acc1[3] += yl[2 * i + 9] * (q1[i] & 0xF000);
                acc2[0] += yh[2 * i + 0] * (q2[i] & 0x000F);
                acc2[1] += yh[2 * i + 1] * (q2[i] & 0x0F00);
                acc2[2] += yh[2 * i + 8] * (q2[i] & 0x00F0);
                acc2[3] += yh[2 * i + 9] * (q2[i] & 0xF000);
            }
            sumf[row] += float(b->d) * ((acc1[0] + 1.f / 256.f * acc1[1]) * sc8[0] +
                                        (acc1[2] + 1.f / 256.f * acc1[3]) * sc8[1] * 1.f / 16.f +
                                        (acc2[0] + 1.f / 256.f * acc2[1]) * sc8[4] +
                                        (acc2[2] + 1.f / 256.f * acc2[3]) * sc8[5] * 1.f / 16.f) -
                         float(b->dmin) * (sumy[0] * sc8[2] + sumy[1] * sc8[3] + sumy[2] * sc8[6] + sumy[3] * sc8[7]);
        }
    }
}

template <int NR>
inline void dot_q6k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const short tid = lane / 2, ix = lane % 2, ip = tid / 8, il = tid % 8, l0 = 4 * il, is = 8 * ip + l0 / 16;
    const short y_offset = 128 * ip + l0, q_offset_l = 64 * ip + l0, q_offset_h = 32 * ip + l0;
    float yl[16];
    for (int i = ix; i < nb; i += 2) {
        device const float * y = x + i * 256 + y_offset;
        for (short l = 0; l < 4; ++l) {
            yl[4 * l + 0] = y[l + 0]; yl[4 * l + 1] = y[l + 32]; yl[4 * l + 2] = y[l + 64]; yl[4 * l + 3] = y[l + 96];
        }
        for (short row = 0; row < NR; ++row) {
            device const block_q6_K * b = (device const block_q6_K *) w[row] + i;
            device const uchar * q1 = b->ql + q_offset_l;
            device const uchar * q2 = q1 + 32;
            device const uchar * qh = b->qh + q_offset_h;
            device const char  * sc = b->scales + is;
            float4 sums = 0.0f;
            for (short l = 0; l < 4; ++l) {
                sums[0] += yl[4 * l + 0] * ((int8_t) ((q1[l] & 0xF) | ((qh[l] & 0x03) << 4)) - 32);
                sums[1] += yl[4 * l + 1] * ((int8_t) ((q2[l] & 0xF) | ((qh[l] & 0x0C) << 2)) - 32);
                sums[2] += yl[4 * l + 2] * ((int8_t) ((q1[l] >> 4)  | ((qh[l] & 0x30) << 0)) - 32);
                sums[3] += yl[4 * l + 3] * ((int8_t) ((q2[l] >> 4)  | ((qh[l] & 0xC0) >> 2)) - 32);
            }
            sumf[row] += float(b->d) * (sums[0] * sc[0] + sums[1] * sc[2] + sums[2] * sc[4] + sums[3] * sc[6]);
        }
    }
}

// 4 lanes per block (8 quants each), 8 blocks per simdgroup pass (chadlyb/erisinky)
template <int NR>
inline void dot_q8(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const short ix = lane / 4, il = lane % 4;
    for (int ib = ix; ib < nb; ib += 8) {
        device const float4 * x4 = (device const float4 *) (x + ib * 32 + il * 8);
        const float4 xa = x4[0], xb = x4[1];
        for (short row = 0; row < NR; ++row) {
            device const block_q8_0 * b = (device const block_q8_0 *) w[row] + ib;
            device const ushort * q = (device const ushort *) b->qs + il * 4;
            const char2 q0 = as_type<char2>(q[0]), q1 = as_type<char2>(q[1]), q2 = as_type<char2>(q[2]), q3 = as_type<char2>(q[3]);
            const float s = dot(xa, float4(q0.x, q0.y, q1.x, q1.y)) + dot(xb, float4(q2.x, q2.y, q3.x, q3.y));
            sumf[row] += s * float(b->d);
        }
    }
}

template <int NR>
inline void dot_nv4(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const short ix = lane / 4, il = lane % 4;
    for (int ib = ix; ib < nb; ib += 8) {
        device const float * xb = x + ib * 32 + il * 4;
        const float4 xl = *(device const float4 *) xb, xh = *(device const float4 *) (xb + 16);
        for (short row = 0; row < NR; ++row) {
            device const ushort * p = (device const ushort *) (w[row] + ib * 18);
            const float2 sc = e4m3f2(p[0]);
            float4 lo, hi; fp4x8(uint(p[1 + 2 * il]) | (uint(p[2 + 2 * il]) << 16), lo, hi);
            sumf[row] += sc.x * dot(xl, lo) + sc.y * dot(xh, hi);
        }
    }
}

template <int NR>
inline void dot_mx8(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const short ix = lane / 4, il = lane % 4;
    for (int ib = ix; ib < nb; ib += 8) {
        device const float4 * x4 = (device const float4 *) (x + ib * 32 + il * 8);
        const float4 xa = x4[0], xb = x4[1];
        for (short row = 0; row < NR; ++row) {
            device const ushort * p = (device const ushort *) (w[row] + ib * 34);
            float4 a, b; e4m3x8(p + 1 + 4 * il, a, b);
            sumf[row] += (dot(xa, a) + dot(xb, b)) * float(as_type<half>(p[0])) * MX8_K;
        }
    }
}

template <int NR>
inline void dot_q3k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const uint n = lane / 16u, l = lane % 16u;
    for (int ib = 0; ib < nb; ib++) {
        device const float * xb = x + ib * 256 + n * 128 + l;
        float xl[8];
        for (uint g = 0; g < 4u; g++) {
            xl[2u * g] = xb[32u * g];
            xl[2u * g + 1u] = xb[32u * g + 16u];
        }
        for (short row = 0; row < NR; ++row) {
            device const block_q3_K * b = (device const block_q3_K *) (w[row] + (ulong) ib * 110u);
            device const uchar * qp = b->qs + 32u * n;
            const uchar q0b = qp[l], q1b = qp[16u + l];
            const uchar h0b = b->hmask[l], h1b = b->hmask[16u + l];
            float acc = 0.0f;
            for (uint g = 0; g < 4u; g++) {
                const uint sh = 2u * g;
                const uchar m = uchar(1u << (4u * n + g));
                const int q0 = int((q0b >> sh) & 3u) - ((h0b & m) ? 0 : 4);
                const int q1 = int((q1b >> sh) & 3u) - ((h1b & m) ? 0 : 4);
                const int s0 = q3k_scale(b->scales, 8u * n + 2u * g);
                const int s1 = q3k_scale(b->scales, 8u * n + 2u * g + 1u);
                acc += xl[2u * g] * float(s0 * q0) + xl[2u * g + 1u] * float(s1 * q1);
            }
            sumf[row] += float(b->d) * acc;
        }
    }
}

template <int NR>
inline void dot_q2k(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const uint n = lane / 16u, l = lane % 16u;
    for (int ib = 0; ib < nb; ib++) {
        device const float * xb = x + ib * 256 + n * 128 + l;
        float xl[8];
        for (uint g = 0; g < 4u; g++) {
            xl[2u * g] = xb[32u * g];
            xl[2u * g + 1u] = xb[32u * g + 16u];
        }
        for (short row = 0; row < NR; ++row) {
            device const block_q2_K * b = (device const block_q2_K *) (w[row] + (ulong) ib * 84u);
            device const uchar * qp = b->qs + 32u * n;
            const uchar q0b = qp[l], q1b = qp[16u + l];
            const float d = float(b->d), dmin = float(b->dmin);
            float acc_d = 0.0f, acc_m = 0.0f;
            for (uint g = 0; g < 4u; g++) {
                const uint sh = 2u * g;
                const uchar sc0 = b->scales[8u * n + 2u * g];
                const uchar sc1 = b->scales[8u * n + 2u * g + 1u];
                const uint q0 = (q0b >> sh) & 3u;
                const uint q1 = (q1b >> sh) & 3u;
                acc_d += xl[2u * g] * float((sc0 & 0xFu) * q0) + xl[2u * g + 1u] * float((sc1 & 0xFu) * q1);
                acc_m += xl[2u * g] * float(sc0 >> 4) + xl[2u * g + 1u] * float(sc1 >> 4);
            }
            sumf[row] += d * acc_d - dmin * acc_m;
        }
    }
}

template <int NR>
inline void dot_q3_0(device const uchar * const * w, int nb, device const float * x, ushort lane, thread float * sumf) {
    const short ix = lane / 4, il = lane % 4;
    for (int ib = ix; ib < nb; ib += 8) {
        device const float * xb = x + ib * 32 + il * 8;
        float xv[8];
        for (int k = 0; k < 8; k++) xv[k] = xb[k];
        for (short row = 0; row < NR; ++row) {
            device const block_q3_0 * b = (device const block_q3_0 *) (w[row] + (ulong) ib * 14u);
            const uint qh = uint(b->qh[0]) | (uint(b->qh[1]) << 8) | (uint(b->qh[2]) << 16) | (uint(b->qh[3]) << 24);
            float s = 0.0f;
            for (int k = 0; k < 8; k++) {
                const uint j = uint(il * 8 + k);
                const uint q2 = (b->qs[j >> 2] >> ((j & 3u) * 2u)) & 3u;
                const uint hb = ((qh >> j) & 1u) << 2;
                s += xv[k] * float(int(q2 | hb) - 4);
            }
            sumf[row] += s * float(b->d);
        }
    }
}

template <int NR>
inline void dot_bf16(device const uchar * const * w, int K, device const float * x, ushort lane, thread float * sumf) {
    for (int i = lane * 8; i < K; i += 256) {
        const float4 xa = *(device const float4 *) (x + i), xb = *(device const float4 *) (x + i + 4);
        for (short row = 0; row < NR; ++row) {
            const ushort4 a = *(device const ushort4 *) (w[row] + 2 * i);
            const ushort4 b = *(device const ushort4 *) (w[row] + 2 * i + 8);
            sumf[row] += dot(xa, float4(bf16f(a.x), bf16f(a.y), bf16f(a.z), bf16f(a.w))) +
                         dot(xb, float4(bf16f(b.x), bf16f(b.y), bf16f(b.z), bf16f(b.w)));
        }
    }
}

// ---------------------------------------------------------------------------------------------
// embedding lookup (Q4_K row) + RMSNorm(token_embd_norm)

struct EmbedArgs { uint emb_lo, emb_hi, row_bytes, norm_off, out0, out1, tok_index; float eps; };

kernel void k_embed(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                    constant EmbedArgs & a [[buffer(5)]], device const int * toks [[buffer(6)]], uint tok [[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];
    const int t = toks[a.tok_index + tok];
    const ulong off = (ulong(a.emb_hi) << 32 | a.emb_lo) + (ulong) t * a.row_bytes;
    device const block_q4_K * row = (device const block_q4_K *) (W + off);
    float v[9];
    float ss = 0.0f;
    if (a.row_bytes == (E / 32) * 34) {     // Q8_0
        device const block_q8_0 * r8 = (device const block_q8_0 *) (W + off);
        for (int k = 0; k < 9; k++) { const int i = tid + k * 256; v[k] = float(r8[i / 32].d) * float(r8[i / 32].qs[i % 32]); ss += v[k] * v[k]; }
    } else
    for (int k = 0; k < 9; k++) {
        const int j = tid, pair = j / 64, l = j % 64;
        device const block_q4_K & b = row[k];
        const int sub = pair * 2 + (l >= 32 ? 1 : 0);
        const uchar q = b.qs[pair * 32 + (l & 31)];
        const int qv = l >= 32 ? (q >> 4) : (q & 0xF);
        float sc, m;
        scale_min_k4(sub, b.scales, sc, m);
        v[k] = float(b.d) * sc * qv - float(b.dmin) * m;
        ss += v[k] * v[k];
    }
    ss = tg_sum(ss, sh, sg, lane, 8);
    const float r = rsqrt(ss / E + a.eps);
    device const float * w = (device const float *) (PB + a.norm_off);
    for (int k = 0; k < 9; k++) {
        const int i = tid + k * 256;
        const float o = v[k] * r * w[i];
        A[a.out0 + tok * E + i] = o;
        A[a.out1 + tok * E + i] = o;
    }
}

// Per-span descriptor for 3D-batched Layer 3 decode dispatches (64 bytes, mirrors Rust `DecodeSpanDesc`).
struct DecodeSpanDesc {
    int   tok_id;
    uint  pos;
    uint  cs_base;
    uint  bt_full_base;
    uint  bt_win_base;
    uint  part_off;
    uint  swa_nkeys;
    uint  swa_first_pos;
    uint  swa_kps;
    uint  swa_nsplit;
    uint  full_nkeys;
    uint  full_kps;
    uint  full_nsplit;
    float full_tau;
    float swa_tau;
    uint  full_recent_start;
};

struct EmbedDecArgs { uint emb_lo, emb_hi, row_bytes, norm_off, out_off, desc_off; float eps; uint pad; };

kernel void k_embed_dec(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                        constant EmbedDecArgs & a [[buffer(5)]], uint si [[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];
    device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
    const int t = d.tok_id;
    const ulong off = (ulong(a.emb_hi) << 32 | a.emb_lo) + (ulong) t * a.row_bytes;
    device const block_q4_K * row = (device const block_q4_K *) (W + off);
    float v[9];
    float ss = 0.0f;
    if (a.row_bytes == (E / 32) * 34) {     // Q8_0
        device const block_q8_0 * r8 = (device const block_q8_0 *) (W + off);
        for (int k = 0; k < 9; k++) { const int i = tid + k * 256; v[k] = float(r8[i / 32].d) * float(r8[i / 32].qs[i % 32]); ss += v[k] * v[k]; }
    } else
    for (int k = 0; k < 9; k++) {
        const int j = tid, pair = j / 64, l = j % 64;
        device const block_q4_K & b = row[k];
        const int sub = pair * 2 + (l >= 32 ? 1 : 0);
        const uchar q = b.qs[pair * 32 + (l & 31)];
        const int qv = l >= 32 ? (q >> 4) : (q & 0xF);
        float sc, m;
        scale_min_k4(sub, b.scales, sc, m);
        v[k] = float(b.d) * sc * qv - float(b.dmin) * m;
        ss += v[k] * v[k];
    }
    ss = tg_sum(ss, sh, sg, lane, 8);
    const float r = rsqrt(ss / E + a.eps);
    device const float * w = (device const float *) (PB + a.norm_off);
    for (int k = 0; k < 9; k++) {
        const int i = tid + k * 256;
        A[a.out_off + si * E + i] = v[k] * r * w[i];
    }
}

// ---------------------------------------------------------------------------------------------
// depth attention ("block attention residuals"): out_q = sum_i softmax_i(q . n_i / sqrt(E)) n_i, n_i = rmsnorm(s_i)
// optionally followed by RMSNorm with a weight. q_off < 0: identity (out = raw s_0). One threadgroup per job, 256 threads.

// hcopy / hout: fp16 destinations of the batched kernel (normalized copies with row stride hstride halves; (normed) outputs
// with row stride E halves). nof32 bit q: output q is only wanted in fp16.
struct MixJob { uint nS, nQ; uint s_off[6]; int q_off; uint out_off[4]; int norm_off[4]; float eps; uint tstride; int ncopy[4][3]; uint pad_t;
                int hcopy[4][3]; int hout[4]; uint hstride, nof32; };

kernel void k_mix(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MixJob * jobs [[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]]) {
    // 768 threads, 3 channels per thread; all register arrays statically indexed (no spills)
    constant MixJob & J = jobs[tgp.x];
    const uint toff = tgp.y * J.tstride;
    threadgroup float part[24][32];
    threadgroup float red[32];
    threadgroup float sh2[24][4];
    const uint nS = J.nS, nQ = J.nQ;
    float s[6][3];
    #pragma unroll
    for (uint i = 0; i < 6; i++) {
        #pragma unroll
        for (int k = 0; k < 3; k++) s[i][k] = i < nS ? A[J.s_off[i] + toff + tid + k * 768] : 0.0f;
    }
    float o[4][3];
    if (J.q_off < 0) {
        #pragma unroll
        for (int k = 0; k < 3; k++) { o[0][k] = s[0][k]; o[1][k] = o[2][k] = o[3][k] = 0; }
    } else {
        device const float * Q = (device const float *) (PB + J.q_off);
        float qv[4][3];
        #pragma unroll
        for (uint q = 0; q < 4; q++) {
            #pragma unroll
            for (int k = 0; k < 3; k++) qv[q][k] = q < nQ ? Q[q * E + tid + k * 768] : 0.0f;
        }
        // v index: i*5 + 0 -> ss_i ; i*5 + 1 + q -> dot_iq
        #pragma unroll
        for (uint i = 0; i < 6; i++) {
            float ss = 0, d0 = 0, d1 = 0, d2 = 0, d3 = 0;
            #pragma unroll
            for (int k = 0; k < 3; k++) { ss += s[i][k] * s[i][k]; d0 += s[i][k] * qv[0][k]; d1 += s[i][k] * qv[1][k]; d2 += s[i][k] * qv[2][k]; d3 += s[i][k] * qv[3][k]; }
            ss = simd_sum(ss); d0 = simd_sum(d0); d1 = simd_sum(d1); d2 = simd_sum(d2); d3 = simd_sum(d3);
            if (lane == 0) { part[sg][i * 5 + 0] = ss; part[sg][i * 5 + 1] = d0; part[sg][i * 5 + 2] = d1; part[sg][i * 5 + 3] = d2; part[sg][i * 5 + 4] = d3; }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (tid < 30) { float t = 0; for (int g = 0; g < 24; g++) t += part[g][tid]; red[tid] = t; }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        float rr[6];
        #pragma unroll
        for (uint i = 0; i < 6; i++) rr[i] = rsqrt(red[i * 5] / E + 1e-6f);
        #pragma unroll
        for (uint q = 0; q < 4; q++) {
            float sc[6], mx = -INFINITY;
            #pragma unroll
            for (uint i = 0; i < 6; i++) { sc[i] = i < nS ? rr[i] * red[i * 5 + 1 + q] * (1.0f / 48.0f) : -INFINITY; mx = max(mx, sc[i]); }
            float den = 0;
            #pragma unroll
            for (uint i = 0; i < 6; i++) { sc[i] = i < nS ? exp(sc[i] - mx) : 0.0f; den += sc[i]; }
            #pragma unroll
            for (uint i = 0; i < 6; i++) sc[i] = sc[i] / den * rr[i];
            #pragma unroll
            for (int k = 0; k < 3; k++) { float acc = 0; for (uint i = 0; i < 6; i++) acc += sc[i] * s[i][k]; o[q][k] = acc; }
        }
    }
    const uint nOut = J.q_off < 0 ? 1 : nQ;
    // optional RMSNorm per output: one reduction round for all outputs
    float ssq[4];
    #pragma unroll
    for (uint q = 0; q < 4; q++) { float t = 0; for (int k = 0; k < 3; k++) t += o[q][k] * o[q][k]; ssq[q] = simd_sum(t); }
    if (lane == 0) for (int q = 0; q < 4; q++) sh2[sg][q] = ssq[q];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    #pragma unroll
    for (uint q = 0; q < 4; q++) {
        if (q >= nOut) break;
        float t = 0; for (int g = 0; g < 24; g++) t += sh2[g][q];
        // plain RMSNorm copies (eps 1e-6, no weight) for the loop controllers' inputs
        const float rn = rsqrt(t / E + 1e-6f);
        for (int c = 0; c < 3; c++) if (J.ncopy[q][c] >= 0) for (int k = 0; k < 3; k++) A[J.ncopy[q][c] + toff + tid + k * 768] = o[q][k] * rn;
        if (J.norm_off[q] >= 0) {
            const float r = rsqrt(t / E + J.eps);
            device const float * w = (device const float *) (PB + J.norm_off[q]);
            for (int k = 0; k < 3; k++) A[J.out_off[q] + toff + tid + k * 768] = o[q][k] * r * w[tid + k * 768];
        } else {
            for (int k = 0; k < 3; k++) A[J.out_off[q] + toff + tid + k * 768] = o[q][k];
        }
    }
}

// ---------------------------------------------------------------------------------------------
// generic segmented matvec: several weight matrices (possibly different quant types and inputs) in one dispatch.
// x is staged into threadgroup memory with optional transforms: * sigmoid(in2), RMSNorm(norm weight).
// epilogue 1: causal short conv (post-conv) with state + optional residual.

struct Seg {
    uint w_lo, w_hi, row_bytes, wtype;
    uint nrows, K, tg_start, in_off;
    int  in2_off, norm_off, ss_off, ss_n;
    uint out_off, epi; int res_off; uint cs_off;
    uint convw_off, pad0, pad1, pad2;
};
struct MvArgs { uint nseg; float eps; uint post, ctr; uint bias_off, sel_off; float wscale; uint pad; Seg seg[12]; };

// top-k over NEXP router logits (sigmoid scores + selection bias), normalized weights * wscale. one simdgroup.
inline void topk_sg(coherent(device) device float * A, device const uchar * PB, uint logits_off, uint bias_off, uint sel_off, float wscale, ushort lane) {
    coherent(device) device const float * lg = A + logits_off;
    device const float * bias = (device const float *) (PB + bias_off);
    float pr[4], sel[4];
    for (int i = 0; i < 4; i++) {
        const int e = lane * 4 + i;
        const float p = sigm(lg[e]), score = p + bias[e];
        // Inspect bits because these kernels are compiled with fast math.
        const bool finite = (as_type<uint>(score) & 0x7f800000u) != 0x7f800000u;
        pr[i] = finite ? p : 0.0f;
        sel[i] = finite ? score : as_type<float>(0xff7fffffu);
    }
    float wsum = 0, myw = 0; int myid = 0;
    for (int k = 0; k < TOPK; k++) {
        float bv = sel[0]; int bi = 0;
        for (int i = 1; i < 4; i++) if (sel[i] > bv) { bv = sel[i]; bi = i; }
        const float mv = simd_max(bv);
        const int candidate = simd_min((bv == mv) ? (int) (lane * 4 + bi) : NEXP);
        const int win = candidate < NEXP ? candidate : k;
        const float pw = simd_shuffle(pr[win % 4], (ushort) (win / 4));
        if ((int) (lane * 4 + bi) == win) sel[bi] = -INFINITY;
        if (lane == (ushort) k) { myid = win; myw = pw; }
        wsum += pw;
    }
    if (lane < TOPK) {
        A[sel_off + lane] = (float) myid;
        A[sel_off + TOPK + lane] = myw / (wsum + 1e-20f) * wscale;
    }
}

#define MV_NSG 4
#define MV_NR  2
#define MV_ROWS (MV_NSG * MV_NR)

template <typename AP>
inline void mv_epilogue(constant Seg & S, uint row, float y, AP A, device float * CS, device const uchar * PB) {
    if (S.epi == 0) { A[S.out_off + row] = y; return; }
    // post short-conv (static taps) over channel `row` (S.epi == 2: dry-state, read CS without updating)
    device float * h = CS + S.cs_off + row * 3;
    device const float * w = (device const float *) (PB + S.convw_off) + row * 4;
    const float h0 = h[0], h1 = h[1], h2 = h[2];
    const float conv = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y;
    if (S.epi == 1) { h[0] = h1; h[1] = h2; h[2] = y; }
    float o = (y + conv) * 0.4472135954999579f;  // 1/sqrt(5)
    if (S.res_off >= 0) o += A[S.res_off + row];
    A[S.out_off + row] = o;
}

// inputs are pre-normalized; x is read straight from device memory (L1/L2 cached), no staging/barriers
kernel void k_mv(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                 device float * CS [[buffer(4)]], constant MvArgs & args [[buffer(5)]], device atomic_uint * CTR [[buffer(7)]],
                 uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]],
                 ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup uint flag;
    uint si = 0;
    while (si + 1 < args.nseg && tg >= args.seg[si + 1].tg_start) si++;
    constant Seg & S = args.seg[si];
    const uint row0 = (tg - S.tg_start) * MV_ROWS + sg * MV_NR;
    if (row0 < S.nrows) {
    const ulong wbase = ulong(S.w_hi) << 32 | S.w_lo;
    device const uchar * base = (S.wtype == 30) ? PB : W;
    device const uchar * wp[MV_NR];
    for (int rr = 0; rr < MV_NR; rr++) wp[rr] = base + wbase + (ulong) min(row0 + rr, S.nrows - 1) * S.row_bytes;
    float sumf[MV_NR] = {0, 0};
    device const float * x = A + S.in_off;
    if (S.wtype == 12) dot_q4k<MV_NR>(wp, S.K / 256, x, lane, sumf);
    else if (S.wtype == 14) dot_q6k<MV_NR>(wp, S.K / 256, x, lane, sumf);
    else if (S.wtype == 11) dot_q3k<MV_NR>(wp, S.K / 256, x, lane, sumf);
    else if (S.wtype == 10) dot_q2k<MV_NR>(wp, S.K / 256, x, lane, sumf);
    else if (S.wtype == 202) dot_q3_0<MV_NR>(wp, S.K / 32, x, lane, sumf);
    else if (S.wtype == 8) dot_q8<MV_NR>(wp, S.K / 32, x, lane, sumf);
    else dot_bf16<MV_NR>(wp, S.K, x, lane, sumf);
    for (int rr = 0; rr < MV_NR; rr++) {
        const float y = simd_sum(sumf[rr]);
        if (lane == 0 && row0 + rr < S.nrows) {
            // post == 1: the last threadgroup reads every row, so they are stored device-coherent (see last_tg)
            if (args.post == 1) mv_epilogue(S, row0 + rr, y, (coherent(device) device float *) A, CS, PB);
            else mv_epilogue(S, row0 + rr, y, A, CS, PB);
        }
    }
    }
    if (args.post == 1 && last_tg(CTR + args.ctr, ntg, sg * 32 + lane, &flag) && sg == 0)
        topk_sg((coherent(device) device float *) A, PB, args.seg[0].out_off, args.bias_off, args.sel_off, args.wscale, lane);
}

// k_mv over the same weights for nv.x vectors at a stride of nv.y floats (the lanes of a decode batch): each weight row
// is read from memory once per step and applied to every vector; each vector's dot product is the same code, in the same
// order, as k_mv's. No epilogue (k_epi applies it per lane); the fused top-k, when asked, runs for every vector.
kernel void k_mvb(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                  constant MvArgs & args [[buffer(5)]], device atomic_uint * CTR [[buffer(7)]], constant uint2 & nv [[buffer(8)]],
                  uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]],
                  ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup uint flag;
    uint si = 0;
    while (si + 1 < args.nseg && tg >= args.seg[si + 1].tg_start) si++;
    constant Seg & S = args.seg[si];
    const uint row0 = (tg - S.tg_start) * MV_ROWS + sg * MV_NR;
    if (row0 < S.nrows) {
        const ulong wbase = ulong(S.w_hi) << 32 | S.w_lo;
        device const uchar * base = (S.wtype == 30) ? PB : W;
        device const uchar * wp[MV_NR];
        for (int rr = 0; rr < MV_NR; rr++) wp[rr] = base + wbase + (ulong) min(row0 + rr, S.nrows - 1) * S.row_bytes;
        for (uint v = 0; v < nv.x; v++) {
            float sumf[MV_NR] = {0, 0};
            device const float * x = A + S.in_off + v * nv.y;
            if (S.wtype == 12) dot_q4k<MV_NR>(wp, S.K / 256, x, lane, sumf);
            else if (S.wtype == 14) dot_q6k<MV_NR>(wp, S.K / 256, x, lane, sumf);
            else if (S.wtype == 11) dot_q3k<MV_NR>(wp, S.K / 256, x, lane, sumf);
            else if (S.wtype == 10) dot_q2k<MV_NR>(wp, S.K / 256, x, lane, sumf);
            else if (S.wtype == 202) dot_q3_0<MV_NR>(wp, S.K / 32, x, lane, sumf);
            else if (S.wtype == 8) dot_q8<MV_NR>(wp, S.K / 32, x, lane, sumf);
            else dot_bf16<MV_NR>(wp, S.K, x, lane, sumf);
            for (int rr = 0; rr < MV_NR; rr++) {
                const float y = simd_sum(sumf[rr]);
                if (lane == 0 && row0 + rr < S.nrows) {
                    // post == 1: the last threadgroup reads every row, so they are stored device-coherent (see last_tg)
                    if (args.post == 1) ((coherent(device) device float *) A)[S.out_off + v * nv.y + row0 + rr] = y;
                    else A[S.out_off + v * nv.y + row0 + rr] = y;
                }
            }
        }
    }
    if (args.post == 1 && last_tg(CTR + args.ctr, ntg, sg * 32 + lane, &flag) && sg == 0)
        for (uint v = 0; v < nv.x; v++) topk_sg((coherent(device) device float *) A, PB, args.seg[0].out_off + v * nv.y, args.bias_off, args.sel_off + v * nv.y, args.wscale, lane);
}

// mv_epilogue for one lane, after k_mvb wrote the raw projection y to out_off: the post short-conv over each channel
// from the lane's state, the residual, the result written back to out_off. Same arithmetic as mv_epilogue.
struct EpiArgs { uint out_off; int res_off; uint cs_off; uint convw_off; uint n; uint pad0, pad1, pad2; };
kernel void k_epi(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], device float * CS [[buffer(4)]],
                  constant EpiArgs & a [[buffer(5)]], uint row [[thread_position_in_grid]]) {
    if (row >= a.n) return;
    const float y = A[a.out_off + row];
    device float * h = CS + a.cs_off + row * 3;
    device const float * w = (device const float *) (PB + a.convw_off) + row * 4;
    const float h0 = h[0], h1 = h[1], h2 = h[2];
    const float conv = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y;
    h[0] = h1; h[1] = h2; h[2] = y;
    float o = (y + conv) * 0.4472135954999579f;  // 1/sqrt(5)
    if (a.res_off >= 0) o += A[a.res_off + row];
    A[a.out_off + row] = o;
}

// ---------------------------------------------------------------------------------------------
// loop controller: out = u*(1 - tanh(F.g)) + tanh(G.g)*m, with RMSNorm fused into the last TG.

struct CtrlJob { uint u_off, m_off, d_off, out_off, gain_off, forget_off, res_out, ss_off; int norm_w; uint ctr; };
struct CtrlArgs { uint nC; uint tstride; uint pad1, pad2; CtrlJob job[4]; };

// out = u*(1 - tanh(F.g)) + tanh(G.g)*m ; G,F: E x 64 bf16. 8 lanes per channel; 256-thread TG = 32 channels.
// writes per-TG partial sum of squares of out to ss_off[tg] (for a downstream RMSNorm). The last threadgroup reads every
// threadgroup's partial and output and rescales the outputs in place, so A is coherent(device) (see last_tg).
kernel void k_ctrl_apply(device const uchar * PB [[buffer(1)]], coherent(device) device float * A [[buffer(2)]], constant CtrlArgs & a [[buffer(5)]],
                         device atomic_uint * CTR [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]], uint3 ntg [[threadgroups_per_grid]],
                         ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup float sh[32];
    threadgroup uint flag;
    constant CtrlJob & J = a.job[tg.y];
    const uint tok = tg.z, toff = tok * a.tstride;
    const uint ch = tg.x * 32 + sg * 4 + lane / 8;
    const uint p = lane % 8;
    float g[8];
    for (int i = 0; i < 8; i++) g[i] = A[J.out_off + tok * 64 + p * 8 + i];
    ushort4 ga = *(device const ushort4 *) (PB + J.gain_off + ch * 128 + p * 16);
    ushort4 gb = *(device const ushort4 *) (PB + J.gain_off + ch * 128 + p * 16 + 8);
    ushort4 fa = *(device const ushort4 *) (PB + J.forget_off + ch * 128 + p * 16);
    ushort4 fb = *(device const ushort4 *) (PB + J.forget_off + ch * 128 + p * 16 + 8);
    float dg = bf16f(ga.x) * g[0] + bf16f(ga.y) * g[1] + bf16f(ga.z) * g[2] + bf16f(ga.w) * g[3] +
               bf16f(gb.x) * g[4] + bf16f(gb.y) * g[5] + bf16f(gb.z) * g[6] + bf16f(gb.w) * g[7];
    float df = bf16f(fa.x) * g[0] + bf16f(fa.y) * g[1] + bf16f(fa.z) * g[2] + bf16f(fa.w) * g[3] +
               bf16f(fb.x) * g[4] + bf16f(fb.y) * g[5] + bf16f(fb.z) * g[6] + bf16f(fb.w) * g[7];
    dg += simd_shuffle_xor(dg, 1); dg += simd_shuffle_xor(dg, 2); dg += simd_shuffle_xor(dg, 4);
    df += simd_shuffle_xor(df, 1); df += simd_shuffle_xor(df, 2); df += simd_shuffle_xor(df, 4);
    float o = 0;
    if (p == 0) {
        const float u = A[J.u_off + toff + ch], m = A[J.m_off + toff + ch];
        o = u - tanh(df) * u + tanh(dg) * m;
        A[J.res_out + toff + ch] = o;
    }
    const float ss = tg_sum(o * o, sh, sg, lane, 8);
    if (tid == 0) A[J.ss_off + tok * 128 + tg.x] = ss;
    if (J.norm_w >= 0 && last_tg(CTR + J.ctr, ntg.x, tid, &flag)) {
        float t = 0;
        for (uint i = 0; i < ntg.x; i++) t += A[J.ss_off + tok * 128 + i];
        const float r = rsqrt(t / E + 1e-6f);
        device const float * w = (device const float *) (PB + J.norm_w);
        for (uint i = tid; i < E; i += 256) A[J.res_out + toff + i] *= r * w[i];
    }
}

// ---------------------------------------------------------------------------------------------
// decode attention for one token, one kv head per TG column, keys split across TG rows (flash-decoding).
// fuses: K/V short conv (static + dynamic taps) with state update, K clip, V RMSNorm, Q clip, R clip,
// log-scale tau, relative-position bias, per-head sink, partial softmax.

struct AttnArgs {
    uint pos, nkeys, first_pos, ring, cap, k_base, v_base, cs_off;
    uint q_off, k_off, v_off, r_off, sink_off; int kdyn_off, vdyn_off; uint part_off;
    uint kconv_w, vconv_w, qclip_w, relclip_w, relbias_w; float tau; uint kps, nsplit;
    uint ctr, gate_off, out_off, pad;
    // sp0: index of this dispatch's first split among the layer's nsplit partials; noown: keys only (another dispatch computes
    // and stores the token's own K/V); row (g, idx) of the bound K/V lives at g * gstr + idx * istr; idx = pos - idx0 if !ring
    uint sp0, noown, gstr, istr, idx0;
    float lastbias;      // dev (key eviction experiments): added to the score of the dispatch's last key
    float log_alpha, log_floor; // GPU tau parameters when pad & 8 (half_io tensor decode)
};
#define KVROW(g, idx) ((g) * a.gstr + (idx) * a.istr)
#define KVIDX(p) (a.ring ? ((p) % a.cap) : ((p) - a.idx0))

#define KPS_MAX 256

// Scratch private to one (absolute key split, KV head, query) threadgroup.
struct SplitWork {
    float4 qs4[3][HD / 4];
    float rs[3][NREL];
    float kc[HD], vc[HD];
#if defined(KV8) || defined(KV4)
    float ksc, vsc;
#endif
    float ms_[4][3], ls_[4][3];
    float4 os_[4][3][32];
};

#pragma clang fp contract(off) reassociate(off)
template<bool own_value>
inline void attn_split(device const uchar * PB, device float * A, device const kv_t * KV,
                       const thread AttnArgs & a, threadgroup SplitWork & work, thread const float (&sink)[3],
                       uint sp, uint g, uint p_lo, uint p_hi, uint split_start, uint p1, uint gap_end,
                       ushort tid, ushort sg, ushort lane) {
    device const float * relb = (device const float *) (PB + a.relbias_w);
    // ---- barrier-free per-simdgroup online softmax over 8-key blocks (4 lanes per key for the scores)
    const ushort kk = lane / 4, pp = lane % 4;
    float m[3] = {-INFINITY, -INFINITY, -INFINITY}, l[3] = {0, 0, 0};
    float4 o[3] = {0, 0, 0};
    float4 rl[3];
    for (int h = 0; h < 3; h++) rl[h] = *(threadgroup const float4 *) (&work.rs[h][pp * 4]);
    for (uint pb = split_start + sg * 8; pb < p1; pb += 32) {
        if (pb + 8 <= p_lo) continue;
        if (gap_end > 0u && pb >= 64u && pb + 8u <= gap_end) continue;
        const uint raw_p = pb + kk;
        const bool valid = (raw_p >= p_lo) && (raw_p < p1) && (gap_end == 0u || raw_p < 64u || raw_p >= gap_end);
        const uint p = min(max(raw_p, p_lo), p1 - 1);
        const uint idx = KVIDX(p);
        float acc[3] = {0, 0, 0};
        if (own_value && p == a.pos) {
            for (int c = 0; c < 8; c++) {
                const float4 kf = *(threadgroup const float4 *) (&work.kc[pp * 32 + c * 4]);
                for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
            }
#if defined(KV8) || defined(KV4)
            if (work.ksc != 1.0f) for (int h = 0; h < 3; h++) acc[h] *= work.ksc;
#endif
        } else {
#ifdef KV4
            device const kv4_row * krow = KV + a.k_base + KVROW(g, idx);
            device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
            for (int c = 0; c < 8; c++) {
                const float4 kf = kv4_u16_to_f4(ku[c]);
                for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
            }
            const float ks = float(krow->sc);
            for (int h = 0; h < 3; h++) acc[h] *= ks;
#elif defined(KV8)
            device const kv_t * krow = KV + a.k_base + KVROW(g, idx);
            device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(char4(kr[c]));
                for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
            }
            const float ks = kv_vscale(krow);
            for (int h = 0; h < 3; h++) acc[h] *= ks;
#else
            device const half4 * kr = (device const half4 *) (KV + a.k_base + KVROW(g, idx) + pp * 32);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(kr[c]);
                for (int h = 0; h < 3; h++) acc[h] += dot(work.qs4[h][pp * 8 + c], kf);
            }
#endif
        }
        const uint d = a.pos - p;
        if (d < EXT) {
            const float4 bb = *(device const float4 *) (relb + d * NREL + pp * 4);
            for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
        }
        if (a.lastbias != 0.0f && valid && p == p_hi - 1) for (int h = 0; h < 3; h++) acc[h] += a.lastbias * 0.25f;
        float pr[3], sc_[3];
        for (int h = 0; h < 3; h++) {
            float t = acc[h];
            t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
            t = valid ? t - sink[h] : -INFINITY;
            const float mx = max(m[h], simd_max(t));
            sc_[h] = (m[h] == -INFINITY) ? 0.0f : exp(m[h] - mx);
            pr[h] = valid ? exp(t - mx) : 0.0f;
            l[h] = l[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
            m[h] = mx;
            o[h] *= sc_[h];
        }
#ifdef KV4
        { const float vsc = (own_value && p == a.pos) ? work.vsc : float((KV + a.v_base + KVROW(g, idx))->sc); for (int h = 0; h < 3; h++) pr[h] *= vsc; }
#elif defined(KV8)
        // each stored value vector's scale goes into its key's probability (the token's own vector is scaled by work.vsc)
        { const float vsc = (own_value && p == a.pos) ? work.vsc : kv_vscale(KV + a.v_base + KVROW(g, idx)); for (int h = 0; h < 3; h++) pr[h] *= vsc; }
#endif
        // V: lane owns dims [4*lane, 4*lane+4); 8 keys of this block
        for (ushort q = 0; q < 8; q++) {
            const uint pq = pb + q;
            if (pq < p_lo) continue;
            if (pq >= p1) break;
            if (gap_end > 0u && pq >= 64u && pq < gap_end) continue;
            const uint iq = KVIDX(pq);
            const float4 v = (own_value && pq == a.pos) ? *(threadgroup const float4 *) (&work.vc[lane * 4])
#ifdef KV4
                                           : kv4_u16_to_f4(((device const ushort *) (KV + a.v_base + KVROW(g, iq))->qs)[lane]);
#elif defined(KV8)
                                           : float4(char4(*(device const packed_char4 *) (KV + a.v_base + KVROW(g, iq) + lane * 4)));
#else
                                           : float4(*(device const half4 *) (KV + a.v_base + KVROW(g, iq) + lane * 4));
#endif
            for (int h = 0; h < 3; h++) o[h] += simd_shuffle(pr[h], q * 4) * v;
        }
    }
    // ---- merge the 4 simdgroups' partial softmax states
    if (lane == 0) for (int h = 0; h < 3; h++) { work.ms_[sg][h] = m[h]; work.ls_[sg][h] = l[h]; }
    for (int h = 0; h < 3; h++) work.os_[sg][h][lane] = o[h];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (int h = 0; h < 3; h++) {
        float M = -INFINITY;
        for (int s2 = 0; s2 < 4; s2++) M = max(M, work.ms_[s2][h]);
        float L = 0, O = 0;
        for (int s2 = 0; s2 < 4; s2++) {
            const float w = work.ms_[s2][h] == -INFINITY ? 0.0f : exp(work.ms_[s2][h] - M);
            L += w * work.ls_[s2][h];
            O += w * ((threadgroup const float *) work.os_[s2][h])[tid];
        }
        device float * P = A + a.part_off + ((g * 3 + h) * a.nsplit + a.sp0 + sp) * (HD + 2);
        if (tid == 0) { P[0] = M; P[1] = L; }
        P[2 + tid] = O;
    }
}

kernel void k_attn(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]]) {
    // one TG = (key split, kv head g) serving q heads 3g..3g+2; 128 threads; keys processed in chunks of 32
    threadgroup SplitWork work;
    threadgroup float red[4][8];
    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);
    // ---- phase 1: raw values + partial norms
    float q[3];
    for (int h = 0; h < 3; h++) {
        const uint H = g * 3 + 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, vx = 0;
    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 = 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 = 0;
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        r = A[a.r_off + 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(kx * kx), s4 = simd_sum(vx * vx);
        const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
        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];
    // logit = (q.k)/sqrt(HD) + r.B[d] - sink  (bias + sink are unscaled, as llama.cpp folds them into the mask)
#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 float qstored = half_io ? float(half(qr)) : qr;
        ((threadgroup float *) work.qs4[h])[tid] = qstored;
        dc_bias[h] = kv4_finite_or_zero(kv4_reduce128(qstored * 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;
        const float qv = q[h] * f;
        ((threadgroup float *) work.qs4[h])[tid] = half_io ? float(half(qv)) : qv;
    }
#endif
    if (tid < 48) work.rs[tid / 16][tid % 16] = r * 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);
        float ksc_val = 0.0f, vsc_val = 0.0f;
        const float qk = kv4_pack_row_unscaled(k_rot, tid, sg, lane, wht_sh, KV + a.k_base + KVROW(g, idx), !dry, ksc_val);
        const float qv = kv4_pack_row_unscaled(v_rot, tid, sg, lane, wht_sh, KV + a.v_base + KVROW(g, idx), !dry, vsc_val);
        if (half_io) {
            work.kc[tid] = qk; work.vc[tid] = qv;
            if (tid == 0) { work.ksc = ksc_val; work.vsc = vsc_val; }
        } else {
            work.kc[tid] = qk * ksc_val; work.vc[tid] = qv * vsc_val;
            if (tid == 0) { work.ksc = 1.0f; work.vsc = 1.0f; }
        }
#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);
        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);
        if (half_io) {
            work.kc[tid] = qk; work.vc[tid] = qv;
            if (tid == 0) { work.ksc = sk; work.vsc = sv; }
        } else {
            work.kc[tid] = qk * sk; work.vc[tid] = qv * sv;
            if (tid == 0) { work.ksc = 1.0f; work.vsc = 1.0f; }
        }
        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
        work.kc[tid] = half_io ? float(half(k)) : k;
        work.vc[tid] = half_io ? float(half(v)) : 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[3];
#ifdef KV4
    for (int h = 0; h < 3; h++) sink[h] = A[a.sink_off + g * 3 + h] - dc_bias[h];
#else
    for (int h = 0; h < 3; h++) sink[h] = A[a.sink_off + g * 3 + h];
#endif
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const AttnArgs keys = a;
    attn_split<true>(PB, A, KV, keys, work, sink, sp, g, p_lo, p_hi, split_start, p1, 0u, tid, sg, lane);
    // the last split of this kv group combines all splits (+ the zero-logit sink) and applies the sigmoid gate.
    // NOT race-free: the partials are plain device stores (see last_tg). Only the dev switch INK_FUSE_COMB reaches it
    // (every engine path defaults to the separate combine, and serve refuses the switch).
    threadgroup uint flag;
    if ((a.pad & 1u) == 0u && last_tg(CTR + a.ctr + g, a.nsplit, tid, &flag)) {
        for (int h = 0; h < 3; h++) {
            const uint H = g * 3 + h;
            device const float * P = A + a.part_off + H * a.nsplit * (HD + 2);
            float M = 0.0f;
            for (uint s2 = 0; s2 < a.nsplit; s2++) M = max(M, P[s2 * (HD + 2)]);
            float L = exp(-M), O = 0;
            for (uint s2 = 0; s2 < a.nsplit; s2++) {
                const float w = exp(P[s2 * (HD + 2)] - M);
                L += w * P[s2 * (HD + 2) + 1];
                O += w * P[s2 * (HD + 2) + 2 + tid];
            }
            float o_val = O / L;
#ifdef KV4
            o_val = sv_rad * wht128_tg(o_val, tid, sg, lane, wht_sh);
#endif
            const uint i = H * HD + tid;
            A[a.out_off + i] = o_val * sigm(A[a.gate_off + i]);
        }
    }
}

// combine split partials (+ zero-logit sink) and apply the sigmoid output gate. grid: NH TGs x 128 threads
// hout bit 0: write half directly to ((device half *) (A + a.out_off))[i] instead of f32.
// hout bit 1: read gate as half from ((device const half *) (A + a.gate_off))[i] instead of f32.
struct CombineArgs { uint part_off, nsplit, gate_off, out_off; uint hout, pad0, pad1, pad2; };
kernel void k_attn_combine(device float * A [[buffer(2)]], constant CombineArgs & a [[buffer(5)]],
                           uint h [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                           ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    device const float * P = A + a.part_off + h * a.nsplit * (HD + 2);
    float M = 0.0f;  // sink logit
    for (uint s = 0; s < a.nsplit; s++) M = max(M, P[s * (HD + 2)]);
    float L = exp(-M), o = 0;
    for (uint s = 0; s < a.nsplit; s++) {
        const float w = exp(P[s * (HD + 2)] - M);
        L += w * P[s * (HD + 2) + 1];
        o += w * P[s * (HD + 2) + 2 + tid];
    }
    float o_val = o / L;
#ifdef KV4
    threadgroup float wht_sh[128];
    o_val = kv4_rademacher(a.pad0 * 2u + 1u, h / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
    (void) sg; (void) lane;
#endif
    const uint i = h * HD + tid;
    const float gate = (a.hout & 2u) ? float(((device const half *) (A + a.gate_off))[i]) : A[a.gate_off + i];
    const float val = o_val * sigm(gate);
    if (a.hout & 1u) ((device half *) (A + a.out_off))[i] = half(val);
    else A[a.out_off + i] = val;
}

// 2D-batched split combine across all lanes in a decode batch. grid: (NH, nspans, 1) x 128 threads
// hout bit 0: write half directly to ((device half *) (A + a.out_off))[i] instead of f32.
// hout bit 1: read gate as half from ((device const half *) (A + a.gate_off))[i] instead of f32.
struct CombineDecArgs { uint desc_off, gate_off, out_off, swa; uint hout, pad0, pad1, pad2; };
kernel void k_attn_combine_dec(device float * A [[buffer(2)]], constant CombineDecArgs & 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]]) {
    const uint h = tgp.x, si = tgp.y;
    device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
    const uint nsplit = a.swa ? d.swa_nsplit : d.full_nsplit;
    device const float * P = A + d.part_off + h * nsplit * (HD + 2);
    float M = 0.0f;  // sink logit
    for (uint s = 0; s < nsplit; s++) M = max(M, P[s * (HD + 2)]);
    float L = exp(-M), o = 0;
    for (uint s = 0; s < nsplit; s++) {
        const float w = exp(P[s * (HD + 2)] - M);
        L += w * P[s * (HD + 2) + 1];
        o += w * P[s * (HD + 2) + 2 + tid];
    }
    float o_val = o / L;
#ifdef KV4
    threadgroup float wht_sh[128];
    o_val = kv4_rademacher(a.pad0 * 2u + 1u, h / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
    (void) sg; (void) lane;
#endif
    const uint i = si * (NH * HD) + h * HD + tid;
    const float gate = (a.hout & 2u) ? float(((device const half *) (A + a.gate_off))[i]) : A[a.gate_off + i];
    const float val = o_val * sigm(gate);
    if (a.hout & 1u) ((device half *) (A + a.out_off))[i] = half(val);
    else A[a.out_off + i] = val;
}

// Query rows for a resident span share one cache-fixed-split arithmetic regardless of
// whether the scheduler admitted one decode token or a multi-position prefill.
struct PreparedAttnArgs {
    uint pos0, window, cap; int idx0;
    uint k_base, v_base, q_off, r_off;
    uint sink_off, gate_off, out_off, relbias_w;
    uint part_off, kps, nsplit, half_io;
    uint ring, full_budget, kv4_slot, tg_rows;
    // `sel_words` != 0: sparse prefill (`INK_SPARSE_PREFILL`) on `k_attn_tc_fixed_blk`, which reads the per
    // (query block, KV head) key-block masks `sel_words` u32 words each from `buffer(14)`; mask row
    // `((pos >> 6) - sel_qb0) * NKV + g`. 0 everywhere else (every other kernel ignores both).
    uint nrows, sel_words, sel_qb0, pad2;
};

kernel void k_attn_fixed_b(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                           device const 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]]) {
    const uint row = tg.z, g = tg.y, sp = tg.x, pos = p.pos0 + row;
    const uint p_hi = pos + 1u;
    const bool pruned = (p.window == 0u) && (p.full_budget > 0u) && (p_hi > p.full_budget);
    uint p_lo, split_start, p1, gap_end = 0u;
    if (pruned) {
        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 (sp >= count) return;
        const uint abs_sp = (rlo == 0u || sp == 0u) ? sp : (rlo + sp - 1u);
        split_start = abs_sp * p.kps;
        p_lo = (abs_sp > 0u) ? recent_start : 0u;
        p1 = (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;
    } else {
        p_lo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
        split_start = (p_lo / p.kps + sp) * p.kps;
        if (split_start >= p_hi) return;
        p1 = min(p_hi, split_start + p.kps);
    }
    AttnArgs a = {};
    a.pos = pos; a.first_pos = p_lo; a.nkeys = p_hi - p_lo;
    a.cap = p.cap; a.ring = p.ring; a.idx0 = uint(p.idx0);
#ifdef KV4
    a.k_base = p.k_base; a.v_base = p.v_base; a.gstr = p.cap; a.istr = 1u;
#else
    a.k_base = p.k_base; a.v_base = p.v_base; a.gstr = p.cap * HD; a.istr = HD;
#endif
    a.part_off = p.part_off + row * NH * p.nsplit * (HD + 2);
    a.nsplit = p.nsplit; a.relbias_w = p.relbias_w;
    threadgroup SplitWork work;
    float sink[3];
    for (uint h = 0; h < 3; ++h) {
        const uint head = row * NH + g * 3 + h, qi = head * HD + tid;
        ((threadgroup float *) work.qs4[h])[tid] = p.half_io ? float(((device const half *) (A + p.q_off))[qi]) : A[p.q_off + qi];
        if (tid < NREL) work.rs[h][tid] = A[p.r_off + head * NREL + tid];
        sink[h] = A[p.sink_off + head];
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    attn_split<false>(PB, A, KV, a, work, sink, sp, g, p_lo, p_hi, split_start, p1, gap_end, tid, sg, lane);
}

kernel void k_attn_fixed_combine(device float * A [[buffer(2)]], constant PreparedAttnArgs & p [[buffer(5)]],
                                 uint2 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                                 ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    const uint row = tg.y, p_hi = p.pos0 + row + 1u;
    const bool pruned = (p.window == 0u) && (p.full_budget > 0u) && (p_hi > p.full_budget);
    uint count;
    if (pruned) {
        const uint recent_start = p_hi - (p.full_budget - 64u);
        const uint rlo = recent_start / p.kps;
        const uint sp_hi = (p_hi - 1u) / p.kps;
        count = (rlo == 0u) ? (sp_hi + 1u) : (1u + (sp_hi - rlo + 1u));
    } else {
        const uint p_lo = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
        count = (p_hi - 1u) / p.kps + 1u - p_lo / p.kps;
    }
    const uint head = row * NH + tg.x, qi = head * HD + tid;
    device const float * P = A + p.part_off + head * p.nsplit * (HD + 2);
    float M = 0.0f;
    for (uint s = 0; s < count; ++s) M = max(M, P[s * (HD + 2)]);
    float L = exp(-M), O = 0;
    for (uint s = 0; s < count; ++s) {
        const float w = exp(P[s * (HD + 2)] - M);
        L += w * P[s * (HD + 2) + 1];
        O += w * P[s * (HD + 2) + 2 + tid];
    }
    float o_val = O / L;
#ifdef KV4
    threadgroup float wht_sh[128];
    o_val = kv4_rademacher(p.kv4_slot * 2u + 1u, tg.x / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
    (void) sg; (void) lane;
#endif
    const float gate = p.half_io ? float(((device const half *) (A + p.gate_off))[qi]) : A[p.gate_off + qi];
    const float out = o_val * sigm(gate);
    if (p.half_io) ((device half *) (A + p.out_off))[qi] = half(out);
    else A[p.out_off + qi] = out;
}

#pragma clang fp contract(fast) reassociate(on)

// ---------------------------------------------------------------------------------------------
// MoE: top-k (sigmoid + selection bias), gate_up (Q4_K, fused [gate; up] rows), SiTU activation.
// grid: (FF / (NSG*2), TOPK) TGs of NSG simdgroups; each simdgroup does 2 gate rows + 2 up rows.

struct MoeArgs {
    uint logits_off, bias_off, sel_off, x_off;
    int  norm_off, ss_off, ss_n; float eps;
    uint gu_lo, gu_hi, gu_expert_bytes, gu_row_bytes;
    uint act_off; float wscale, beta, lbeta;
    uint dn_lo, dn_hi, dn_expert_bytes, dn_row_bytes;
    uint dn_type, out_off; int res_off; uint cs_off;
    uint convw_off, gu_type, gu_gs_lo, gu_gs_hi;
    uint dn_gs_lo, dn_gs_hi, no_state_write, pad1;
};

#define GU_NSG 4

kernel void k_topk(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]], constant MoeArgs & a [[buffer(5)]],
                   ushort lane [[thread_index_in_simdgroup]]) {
    topk_sg(A, PB, a.logits_off, a.bias_off, a.sel_off, a.wscale, lane);
}

// grid: (FF / GU_NSG, TOPK); each simdgroup computes gate row i and up row i of one expert -> SiTU
kernel void k_moe_gu(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                     constant MoeArgs & a [[buffer(5)]],
                     uint2 tgp [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    const uint k = tgp.y;
    const int e = (int) A[a.sel_off + k];
    const uint i = tgp.x * GU_NSG + sg;
    const ulong base = (ulong(a.gu_hi) << 32 | a.gu_lo) + (ulong) e * a.gu_expert_bytes;
    device const uchar * wp[2] = { W + base + (ulong) i * a.gu_row_bytes, W + base + (ulong) (FF + i) * a.gu_row_bytes };
    float sumf[2] = {0, 0};
    if (a.gu_type == 200) dot_nv4<2>(wp, E / 32, A + a.x_off, lane, sumf);
    else if (a.gu_type == 201) dot_mx8<2>(wp, E / 32, A + a.x_off, lane, sumf);
    else if (a.gu_type == 202) dot_q3_0<2>(wp, E / 32, A + a.x_off, lane, sumf);
    else if (a.gu_type == 11) dot_q3k<2>(wp, E / 256, A + a.x_off, lane, sumf);
    else if (a.gu_type == 10) dot_q2k<2>(wp, E / 256, A + a.x_off, lane, sumf);
    else if (a.gu_type == 8) dot_q8<2>(wp, E / 32, A + a.x_off, lane, sumf);
    else dot_q4k<2>(wp, E / 256, A + a.x_off, lane, sumf);
    const float g = a.gu_type == 200 ? gscale_at(W, a.gu_gs_lo, a.gu_gs_hi, e) * NV4_K : 1.0f;
    const float gt = simd_sum(sumf[0]) * g, up = simd_sum(sumf[1]) * g;
    if (lane == 0) {
        const float act = a.beta * tanh(gt / a.beta) * sigm(gt) * (a.lbeta > 0 ? a.lbeta * tanh(up / a.lbeta) : up);
        A[a.act_off + k * FF + i] = act;
    }
}

// down projection for all TOPK experts at once + weighted sum + post-conv + residual. Q8_0, Q5_0, NV4, or MX8 rows (K = FF).
// lane handles (expert, block) items f = lane + 32*s (TOPK*36 = 288 = 9*32); packed (unaligned) loads.
#define DN_NSG 2
#define DN_NR  2

template <int NR>
inline void down_rows(device const uchar * eb, uint row0, uint row_bytes, uint type, int b, thread const float4 * xv, float wk, thread float * acc) {
    for (int rr = 0; rr < NR; rr++) {
        device const uchar * rowp = eb + (ulong) (row0 + rr) * row_bytes;
        float sum = 0;
        if (type == 200) {
            device const uchar * bq = rowp + b * 18;
            device const packed_uchar4 * q4 = (device const packed_uchar4 *) (bq + 2);
            float al = 0, ah = 0;
            for (int i = 0; i < 4; i++) { const uchar4 q = uchar4(q4[i]); al += dot(xv[i], fp4f4(q & 0xF)); ah += dot(xv[4 + i], fp4f4(q >> 4)); }
            sum = e4m3f(bq[0]) * al + e4m3f(bq[1]) * ah;
        } else if (type == 201) {
            device const uchar * bq = rowp + b * 34;
            device const packed_uchar4 * q4 = (device const packed_uchar4 *) (bq + 2);
            for (int i = 0; i < 8; i++) sum += dot(xv[i], e4m3f4(uchar4(q4[i])));
            sum *= float(*(device const half *) bq) * MX8_K;
        } else if (type == 202) {
            device const block_q3_0 * bq = (device const block_q3_0 *) (rowp + (ulong) b * 14u);
            const uint qh = uint(bq->qh[0]) | (uint(bq->qh[1]) << 8) | (uint(bq->qh[2]) << 16) | (uint(bq->qh[3]) << 24);
            for (int i = 0; i < 8; i++) {
                const uint qb = bq->qs[i];
                const uint hb = qh >> (4 * i);
                const float4 wv = float4(
                    float(int(((qb >> 0) & 3u) | (((hb >> 0) & 1u) << 2)) - 4),
                    float(int(((qb >> 2) & 3u) | (((hb >> 1) & 1u) << 2)) - 4),
                    float(int(((qb >> 4) & 3u) | (((hb >> 2) & 1u) << 2)) - 4),
                    float(int(((qb >> 6) & 3u) | (((hb >> 3) & 1u) << 2)) - 4)
                );
                sum += dot(xv[i], wv);
            }
            sum *= float(bq->d);
        } else if (type == 8) {
            device const block_q8_0 * bq = (device const block_q8_0 *) rowp + b;
            device const packed_char4 * q = (device const packed_char4 *) bq->qs;
            for (int i = 0; i < 8; i++) sum += dot(xv[i], float4(char4(q[i])));
            sum *= float(bq->d);
        } else {
            device const block_q5_0 * bq = (device const block_q5_0 *) rowp + b;
            const uint qh = as_type<uint>(uchar4(*(device const packed_uchar4 *) bq->qh));
            device const packed_uchar4 * qs4 = (device const packed_uchar4 *) bq->qs;
            for (int i = 0; i < 4; i++) {
                const uchar4 q = uchar4(qs4[i]);
                const uint hl = qh >> (4 * i), hh = qh >> (4 * i + 16);
                const float4 lo = float4(int4(uint4(q & 0xF) | ((uint4(hl, hl >> 1, hl >> 2, hl >> 3) & 1) << 4))) - 16.0f;
                const float4 hi = float4(int4(uint4(q >> 4) | ((uint4(hh, hh >> 1, hh >> 2, hh >> 3) & 1) << 4))) - 16.0f;
                sum += dot(xv[i], lo) + dot(xv[4 + i], hi);
            }
            sum *= float(bq->d);
        }
        acc[rr] += wk * sum;
    }
}

kernel void k_moe_down(device const uchar * W [[buffer(0)]], device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                       device float * CS [[buffer(4)]], constant MoeArgs & a [[buffer(5)]],
                       uint tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    const uint row0 = (tg * DN_NSG + sg) * DN_NR;
    const ulong base = ulong(a.dn_hi) << 32 | a.dn_lo;
    float acc[DN_NR] = {0, 0};
#ifdef NV4_BAL
    if (a.dn_type == 200) {
        const short ix = lane / 4, il = lane % 4;
        for (int s = 0; s < 36; s++) {
            const int f = ix + 8 * s, k = f / 36, b = f % 36;
            device const float * xb = A + a.act_off + k * FF + b * 32 + il * 4;
            const float4 xl = *(device const float4 *) xb, xh = *(device const float4 *) (xb + 16);
            const int e = (int) A[a.sel_off + k];
            const float wk = A[a.sel_off + TOPK + k] * gscale_at(W, a.dn_gs_lo, a.dn_gs_hi, e) * NV4_K;
            device const uchar * eb = W + base + (ulong) e * a.dn_expert_bytes + b * 18;
            for (int rr = 0; rr < DN_NR; rr++) {
                device const ushort * p = (device const ushort *) (eb + (ulong) (row0 + rr) * a.dn_row_bytes);
                const float2 sc = e4m3f2(p[0]);
                float4 lo, hi; fp4x8(uint(p[1 + 2 * il]) | (uint(p[2 + 2 * il]) << 16), lo, hi);
                acc[rr] += wk * (sc.x * dot(xl, lo) + sc.y * dot(xh, hi));
            }
        }
    } else if (a.dn_type == 201) {
        const short ix = lane / 4, il = lane % 4;
        for (int s = 0; s < 36; s++) {
            const int f = ix + 8 * s, k = f / 36, b = f % 36;
            device const float4 * x4 = (device const float4 *) (A + a.act_off + k * FF + b * 32 + il * 8);
            const float4 xa = x4[0], xb = x4[1];
            const int e = (int) A[a.sel_off + k];
            const float wk = A[a.sel_off + TOPK + k] * MX8_K;
            device const uchar * eb = W + base + (ulong) e * a.dn_expert_bytes + b * 34;
            for (int rr = 0; rr < DN_NR; rr++) {
                device const ushort * p = (device const ushort *) (eb + (ulong) (row0 + rr) * a.dn_row_bytes);
                float4 q0, q1; e4m3x8(p + 1 + 4 * il, q0, q1);
                acc[rr] += wk * float(as_type<half>(p[0])) * (dot(xa, q0) + dot(xb, q1));
            }
        }
    } else
#endif
    for (int s = 0; s < 9; s++) {
        const int f = lane + 32 * s, k = f / 36, b = f % 36;
        device const float4 * x4 = (device const float4 *) (A + a.act_off + k * FF + b * 32);
        float4 xv[8];
        for (int i = 0; i < 8; i++) xv[i] = x4[i];
        const int e = (int) A[a.sel_off + k];
        const float g = a.dn_type == 200 ? gscale_at(W, a.dn_gs_lo, a.dn_gs_hi, e) * NV4_K : 1.0f;
        down_rows<DN_NR>(W + base + (ulong) e * a.dn_expert_bytes, row0, a.dn_row_bytes, a.dn_type, b, xv, A[a.sel_off + TOPK + k] * g, acc);
    }
    for (int rr = 0; rr < DN_NR; rr++) {
        const float y = simd_sum(acc[rr]);
        if (lane == 0) {
            const uint row = row0 + rr;
            device float * h = CS + a.cs_off + row * 3;
            device const float * w = (device const float *) (PB + a.convw_off) + row * 4;
            const float h0 = h[0], h1 = h[1], h2 = h[2];
            const float conv = w[0] * h0 + w[1] * h1 + w[2] * h2 + w[3] * y;
            if (a.no_state_write == 0u) { h[0] = h1; h[1] = h2; h[2] = y; }
            A[a.out_off + row] = A[a.res_off + row] + (y + conv) * 0.4472135954999579f;
        }
    }
}

// ---------------------------------------------------------------------------------------------
// argmax over logits (two stages). stage 1: grid G TGs x 1024 threads -> partial (val, idx). stage 2: 1 TG.
// never_tok (<|endoftext|>, Engine::set_never_token; 0xFFFFFFFFu = none) is never the argmax.
struct ArgmaxArgs { uint logits_off, n, part_off, nparts, out_index, checked, never_tok; uint pad1; };

kernel void k_argmax1(device float * A [[buffer(2)]], constant ArgmaxArgs & a [[buffer(5)]],
                      uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]], ushort tid [[thread_index_in_threadgroup]],
                      ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup float bv[32]; threadgroup int bi[32];
    float best = -INFINITY; int idx = 0x7fffffff;
    for (uint i = tg * 1024 + tid; i < a.n; i += ntg * 1024) {
        const uint bits = ((device const uint *) A)[a.logits_off + i];
        // Any NaN or +Inf (even at `never_tok`) poisons `best` to +Inf so `k_argmax2` fails closed (-1);
        // `-Inf` (0xff800000u) stays masked out for `k_gumbel` and empty-row callers.
        if ((bits & 0x7f800000u) == 0x7f800000u && bits != 0xff800000u) { best = INFINITY; idx = int(i); }
        else if (i != a.never_tok) {
            const float v = as_type<float>(bits);
            if (v > best) { best = v; idx = int(i); }
        }
    }
    const float m = simd_max(best);
    int c = best == m ? idx : 0x7fffffff; c = simd_min(c);
    if (lane == 0) { bv[sg] = m; bi[sg] = c; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (sg == 0) {
        float v = bv[lane]; int ii = bi[lane];
        const float m2 = simd_max(v);
        int c2 = v == m2 ? ii : 0x7fffffff; c2 = simd_min(c2);
        if (lane == 0) { A[a.part_off + 2 * tg] = m2; A[a.part_off + 2 * tg + 1] = as_type<float>(c2); }
    }
}

kernel void k_argmax2(device float * A [[buffer(2)]], constant ArgmaxArgs & a [[buffer(5)]], device int * toks [[buffer(6)]],
                      ushort lane [[thread_index_in_simdgroup]]) {
    float best = -INFINITY; int idx = 0x7fffffff;
    for (uint i = lane; i < a.nparts; i += 32) {
        const float v = A[a.part_off + 2 * i]; const int ii = as_type<int>(A[a.part_off + 2 * i + 1]);
        if (v > best || (v == best && ii < idx)) { best = v; idx = ii; }
    }
    const float m = simd_max(best);
    int c = best == m ? idx : 0x7fffffff; c = simd_min(c);
    if (lane == 0) {
        // Fail closed for checked Gumbel and for unchecked greedy session argmax.
        // An empty partial keeps idx at 0x7fffffff. Writing 0 there commits a real token id.
        // `checked` stays in ArgmaxArgs so both callers share one struct.
        const bool non_finite = (as_type<uint>(m) & 0x7f800000u) == 0x7f800000u;
        toks[a.out_index] = (non_finite || uint(c) >= a.n) ? -1 : c;
    }
}

// GPU Gumbel-max sampling (chadlyb/erisinky): argmax(softcap(l) / T + G), G = -log(-log(u)),
// draws from softmax(softcap(l) / T) when top_k == 0 && top_p >= 1.0.
// ban_tok != 0xFFFFFFFFu masks that token to -INFINITY (used by hard thinking_budget close); never_tok likewise
// (<|endoftext|>, Engine::set_never_token).
struct SampArgs { uint logits_off, n, seed_lo, seed_hi, pos, ban_tok, never_tok; float temp, softcap; };
inline uint mix32(uint h) { h ^= h >> 16; h *= 0x7feb352du; h ^= h >> 15; h *= 0x846ca68bu; h ^= h >> 16; return h; }
kernel void k_gumbel(device float * A [[buffer(2)]], constant SampArgs & a [[buffer(5)]],
                     uint i [[thread_position_in_grid]]) {
    if (i >= a.n) return;
    const uint raw = ((device const uint *) A)[a.logits_off + i];
    // Check the raw value before either masking or softcapping can hide the fault.
    if ((raw & 0x7f800000u) == 0x7f800000u) { A[a.logits_off + i] = INFINITY; return; }
    float x = as_type<float>(raw);
    if (i == a.ban_tok || i == a.never_tok) { A[a.logits_off + i] = -INFINITY; return; }
    // Match the CPU sampler's raw argmax, including its tie rule, at near-zero temperatures.
    if (a.temp < 1e-5f) return;
    if (a.softcap > 0.0f) x = a.softcap * precise::tanh(x / a.softcap);
    const uint h = mix32(mix32(mix32(mix32(i ^ 0x9e3779b9u) ^ a.pos) ^ a.seed_lo) ^ a.seed_hi);
    // u in (0, 1), never 1: 23 random bits plus a half step are exact in binary32.
    const float u = (float(h >> 9) + 0.5f) * (1.0f / 8388608.0f);
    // Scaling the noise instead of dividing the logits preserves the argmax and avoids overflow.
    A[a.logits_off + i] = x - a.temp * precise::log(-precise::log(u));
}

// Exact top-TK_C candidates of one raw logits row for the CPU top-k/top-p sampler (top_k <= 64, plus one
// slot for a banned token). Order is the CPU's `cmp_cand`: f32::total_cmp descending, then token id
// ascending. tk_key maps f32 bits to a uint whose unsigned order is total_cmp; non-finite logits set the
// row's bad word and become the empty entry (key 0, id ~0), which no finite logit can equal.
// Integer-only, so fast-math cannot change the selection. Row words: [bad, (key, id) x TK_C] at TK_ROW
// stride. Stage 1: grid (nchunks, 1, 1) x 256 threads, 8 logits per thread, one row of partials per
// chunk. Stage 2: one TG of 32 * ceil(nchunks / 32) threads merges each chunk's sorted list.
constant uint TK_C = 65;
constant uint TK_ROW = 132;
struct TopkCandArgs { uint logits_off, n, nchunks, part_off, out_off, pad0, pad1, pad2; };
// Takes the logit's raw bits (loaded as uint, never as float): fast-math cannot flush a subnormal or a -0.0 in a
// float load or register move it never sees (Emma Gemini's review).
inline uint tk_key(uint b) {
    if ((b & 0x7f800000u) == 0x7f800000u) return 0u;
    return (b & 0x80000000u) != 0u ? ~b : (b | 0x80000000u);
}
inline bool tk_better(uint k1, uint i1, uint k2, uint i2) { return k1 > k2 || (k1 == k2 && i1 < i2); }
// One selection round: every thread offers its head; all threads return the TG winner. `sk`/`si` are
// double-buffered by round parity so one barrier per round suffices.
inline void tk_round(thread uint & k, thread uint & i, threadgroup uint * sk, threadgroup uint * si,
                     uint nsg, ushort sg, ushort lane) {
    for (ushort d = 16; d > 0; d >>= 1) {
        const uint ok = simd_shuffle_xor(k, d), oi = simd_shuffle_xor(i, d);
        if (tk_better(ok, oi, k, i)) { k = ok; i = oi; }
    }
    if (lane == 0) { sk[sg] = k; si[sg] = i; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    k = sk[0]; i = si[0];
    for (uint s = 1; s < nsg; s++) if (tk_better(sk[s], si[s], k, i)) { k = sk[s]; i = si[s]; }
}

kernel void k_topk_cand1(device float * A [[buffer(2)]], constant TopkCandArgs & a [[buffer(5)]],
                         uint tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                         ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup uint sk[2][8], si[2][8], sbad[8];
    uint hk[8], hi[8];
    bool bad = false;
    for (uint j = 0; j < 8; j++) {
        const uint t = tg * 2048u + j * 256u + tid;
        const uint key = t < a.n ? tk_key(((device const uint *) A)[a.logits_off + t]) : 0u;
        bad = bad || (t < a.n && key == 0u);
        hk[j] = key; hi[j] = key != 0u ? t : 0xffffffffu;
    }
    // Sort the thread's 8 entries best-first (fixed indices keep them in registers).
    for (uint x = 1; x < 8; x++)
        for (uint y = x; y > 0; y--)
            if (tk_better(hk[y], hi[y], hk[y - 1], hi[y - 1])) {
                const uint tk = hk[y]; hk[y] = hk[y - 1]; hk[y - 1] = tk;
                const uint ti = hi[y]; hi[y] = hi[y - 1]; hi[y - 1] = ti;
            }
    const bool sb = simd_any(bad);
    if (lane == 0) sbad[sg] = sb ? 1u : 0u;
    device uint * P = (device uint *) A + a.part_off + tg * TK_ROW;
    for (uint r = 0; r < TK_C; r++) {
        uint k = hk[0], i = hi[0];
        tk_round(k, i, sk[r & 1], si[r & 1], 8, sg, lane);
        if (tid == 0) { P[1 + 2 * r] = k; P[2 + 2 * r] = i; }
        if (i != 0xffffffffu && hi[0] == i) {
            for (uint s = 0; s < 7; s++) { hk[s] = hk[s + 1]; hi[s] = hi[s + 1]; }
            hk[7] = 0u; hi[7] = 0xffffffffu;
        }
    }
    if (tid == 0) { uint b = 0; for (uint s = 0; s < 8; s++) b |= sbad[s]; P[0] = b; }
}

kernel void k_topk_cand2(device float * A [[buffer(2)]], constant TopkCandArgs & a [[buffer(5)]],
                         ushort tid [[thread_index_in_threadgroup]], ushort ntid [[threads_per_threadgroup]],
                         ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    threadgroup uint sk[2][32], si[2][32];
    device const uint * P = (device const uint *) A + a.part_off + tid * TK_ROW;
    device uint * O = (device uint *) A + a.out_off;
    const bool live = tid < a.nchunks;
    uint p = 0;
    const uint bad = simd_max(live ? P[0] : 0u);
    if (lane == 0) sk[1][sg] = bad;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid == 0) { uint b = 0; for (uint s = 0; s < ntid / 32u; s++) b |= sk[1][s]; O[0] = b; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint r = 0; r < TK_C; r++) {
        const bool has = live && p < TK_C;
        uint k = has ? P[1 + 2 * p] : 0u, i = has ? P[2 + 2 * p] : 0xffffffffu;
        const uint mine = i;
        tk_round(k, i, sk[r & 1], si[r & 1], ntid / 32u, sg, lane);
        if (tid == 0) { O[1 + 2 * r] = k; O[2 + 2 * r] = i; }
        if (i != 0xffffffffu && mine == i) p++;
    }
}

// Adaptive LoopCD-Logits (Liu et al., 2026, arXiv:2610.02185, Eqs. 3-4 & Appendix A.1-A.3)
// with exact logit softcapping: computes s3 = softcap(Z3), s1 = softcap(Z1), exact global
// top-2 probabilities (p_{3,(1)}, p_{3,(2)}) of softmax(s3), adaptive weight
//   omega_t = omega_max * clamp(1 - (p_{3,(1)} - p_{3,(2)}), 0, 1)
// and overwrites Z3[v] <- s3(v) + omega_t * (s3(v) - s1(v)) in-place.
// Downstream k_gumbel / CPU Sampler skips softcap only for rows with omega_max > 0.
// Grid: (1, n_lanes, 1), 1024 threads (32 simdgroups).
struct LoopCdArgs { uint logits_off, n, stride, pad0; float softcap; uint pad1, pad2, pad3; };
inline void top2_merge(thread float & m1, thread float & m2, float b1, float b2) {
    if (b1 >= m1) { m2 = max(m1, b2); m1 = b1; }
    else if (b1 > m2) { m2 = b1; }
}
kernel void k_loopcd_blend(device float * A [[buffer(2)]],
                           constant LoopCdArgs & a [[buffer(5)]],
                           constant float * OMEGA [[buffer(8)]],
                           device const float * LG_WEAK [[buffer(9)]],
                           uint2 tgp [[threadgroup_position_in_grid]],
                           ushort tid [[thread_index_in_threadgroup]],
                           ushort sg [[simdgroup_index_in_threadgroup]],
                           ushort lane [[thread_index_in_simdgroup]]) {
    if (a.n == 0u) return;
    const uint si = tgp.y;
    const ulong row_off = ulong(si) * ulong(a.stride);
    device float * Z3 = A + ulong(a.logits_off) + row_off;
    device const float * Z1 = LG_WEAK + row_off;
    const float omega_max = OMEGA[si];
    const float c = a.softcap;

    threadgroup float sm1[32], sm2[32], ssum[32];
    threadgroup float g_shared[3];

    // Disabled lanes (omega_max <= 0) keep exact raw logits untouched so mixed batches
    // never alter an unguided lane's arithmetic relative to standalone omega == 0 decode.
    if (omega_max <= 0.0f) return;

    // Pass 1: exact global top-2 of softcapped strong logits s3 across all 1024 threads.
    float m1 = -INFINITY, m2 = -INFINITY;
    for (uint v = tid; v < a.n; v += 1024u) {
        const float raw = Z3[v];
        const float s3 = c > 0.0f ? c * precise::tanh(raw / c) : raw;
        if (s3 >= m1) { m2 = m1; m1 = s3; }
        else if (s3 > m2) { m2 = s3; }
    }
    for (ushort off = 16; off > 0; off >>= 1) {
        const float o1 = simd_shuffle_xor(m1, off);
        const float o2 = simd_shuffle_xor(m2, off);
        top2_merge(m1, m2, o1, o2);
    }
    if (lane == 0) { sm1[sg] = m1; sm2[sg] = m2; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (sg == 0) {
        float bm1 = sm1[lane], bm2 = sm2[lane];
        for (ushort off = 16; off > 0; off >>= 1) {
            const float o1 = simd_shuffle_xor(bm1, off);
            const float o2 = simd_shuffle_xor(bm2, off);
            top2_merge(bm1, bm2, o1, o2);
        }
        if (lane == 0) { g_shared[0] = bm1; g_shared[1] = bm2; }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Pass 2: exact softmax partition function Z = sum_v exp(s3(v) - max1) and adaptive omega_t.
    const float max1 = g_shared[0];
    const float max2 = g_shared[1];
    float sum_e = 0.0f;
    for (uint v = tid; v < a.n; v += 1024u) {
        const float raw = Z3[v];
        const float s3 = c > 0.0f ? c * precise::tanh(raw / c) : raw;
        sum_e += precise::exp(s3 - max1);
    }
    const float sg_sum = simd_sum(sum_e);
    if (lane == 0) ssum[sg] = sg_sum;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (sg == 0) {
        const float z = simd_sum(ssum[lane]);
        if (lane == 0) {
            const bool z_ok = ((as_type<uint>(z) & 0x7f800000u) != 0x7f800000u) && (z > 0.0f);
            const float p1 = z_ok ? (1.0f / z) : 1.0f;
            const float p2 = (z_ok && max2 > -1e30f) ? (precise::exp(max2 - max1) / z) : 0.0f;
            g_shared[2] = z_ok ? (omega_max * clamp(1.0f - (p1 - p2), 0.0f, 1.0f)) : 0.0f;
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Pass 3: write guided post-softcap logits s3 + omega_t * (s3 - s1) back to Z3.
    const float omega = g_shared[2];
    for (uint v = tid; v < a.n; v += 1024u) {
        const float raw3 = Z3[v], raw1 = Z1[v];
        // Softcap maps infinities to finite values. Preserve any invalid model output
        // for the sampler, including when the adaptive weight rounds to zero.
        if ((as_type<uint>(raw3) & 0x7f800000u) == 0x7f800000u ||
            (as_type<uint>(raw1) & 0x7f800000u) == 0x7f800000u) {
            Z3[v] = as_type<float>(0x7fc00000u);
            continue;
        }
        const float s3 = c > 0.0f ? c * precise::tanh(raw3 / c) : raw3;
        if (omega > 0.0f) {
            const float s1 = c > 0.0f ? c * precise::tanh(raw1 / c) : raw1;
            Z3[v] = s3 + omega * (s3 - s1);
        } else {
            Z3[v] = s3;
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Layer 3 block-addressed KV cache helpers and decode split-K attention (`k_attn_blk`).
// In-block layout matches `src/blocks.rs::key_row` and `specs/InBlock.tla`:
//   [pass][K|V][head g in 0..NKV][pos in 0..64][d in 0..HD]
// Each 64-bit block-table entry stores `(slab_index << 62) | within_slab_byte_offset`.

#define KV_BLK 64u
#define KV_BLK_MASK 63u
#define KV_SLAB_MASK ((1UL << 62) - 1UL)
#ifdef KV4
#define KV_HEAD_BYTES  (ulong(KV_BLK) * ulong(sizeof(kv_t)))
#define KV_ROW_STEP    1u
#else
#define KV_HEAD_BYTES  (ulong(KV_BLK) * ulong(HD) * ulong(sizeof(kv_t)))
#define KV_ROW_STEP    HD
#endif
#define KV_PLANE_BYTES (ulong(NKV) * KV_HEAD_BYTES)
#define KV_PASS_BYTES  (2UL * KV_PLANE_BYTES)
// Mirrors `blocks::CLEARED_GPU_TABLE_ENTRY` (`u64::MAX`), distinct from `(slab = 0, byte_offset = 0)` (`0`).
#define KV_CLEARED_ENTRY (~0UL)

inline device kv_t * kv_blk_ptr(
    device uchar * s0, device uchar * s1, device uchar * s2, device uchar * s3,
    device const ulong * bt, uint blk, ulong in_slot_off)
{
    const ulong entry = bt[blk];
    if (entry == KV_CLEARED_ENTRY) return (device kv_t *) nullptr;
    const uint si = uint(entry >> 62);
    const ulong off = entry & KV_SLAB_MASK;
    device uchar * base = (si == 0) ? s0 : (si == 1 ? s1 : (si == 2 ? s2 : s3));
    return (device kv_t *) (base + off + in_slot_off);
}

#pragma clang fp contract(off) reassociate(off)
// ---------------------------------------------------------------------------------------------
// Layer 3 Multi-Query Shared-KV Grouped Decode (`k_kvprep_dec` + `k_attn_grp_dec`, G_MAX = 8).
// `DecAttnGroup` (24 bytes, mirrors Rust `DecAttnGroup`): groups up to 8 decode lanes sharing
// identical `(slot, generation)` BlockEntries across an interior cache-fixed absolute split.

#define DEC_GRP_MAX 8u

struct DecAttnGroup {
    uint   abs_sp;
    uint   count;
    ushort span_idx[DEC_GRP_MAX];
};

// `swa` bit 0: sliding-window layer; bit 1: dry_state (LoopCD weak pass: compute exact kc/vc into
// `kv_cur_off` without mutating CS or BlockPool KV); bit 2: half_io (read half q, write half qp,
// compute GPU tau from log_alpha/log_floor, round fp16 kv_cur to stored half); bits 8..15: KV4 slot.
struct KvPrepDecArgs {
    uint desc_off, pass_idx, cs_slot, swa;
    uint q_off, k_off, v_off, r_off;
    uint qp_off, rp_off, kv_cur_off; int kdyn_off;
    int  vdyn_off; uint kconv_w, vconv_w, qclip_w;
    uint relclip_w; float log_alpha, log_floor; uint sink_off;
};

struct AttnGrpDecArgs {
    uint desc_off, grp_off, qp_off, rp_off;
    uint kv_cur_off, sink_off, relbias_w, pass_idx;
    uint kps, swa, pad0, pad1;
};

// Runs ONCE per `(kv_head g, span si)` per attention layer (`grid = (NKV, nspans, 1)`, 128 threads/TG).
// Arithmetic is bit-identical to `k_attn` / `k_kvprep_b_blk` phase 1 + KV write.
kernel void k_kvprep_dec(device const uchar * PB [[buffer(1)]], device float * A [[buffer(2)]],
                         device uchar * KV0 [[buffer(3)]], device float * CS [[buffer(4)]],
                         constant KvPrepDecArgs & 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]]) {
    threadgroup float red[4][8];
    const uint g = tgp.x, si = tgp.y;
    const bool is_swa = (a.swa & 1u) != 0u;
    const bool dry = (a.swa & 2u) != 0u;
    const bool half_io = (a.swa & 4u) != 0u;
    device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
    const uint pos = d.pos;
    const float tau = half_io
        ? (is_swa ? 1.0f : (1.0f + a.log_alpha * log(max(1.0f, float(pos + 1u) / a.log_floor))))
        : (is_swa ? d.swa_tau : d.full_tau);
    const uint cs_off = d.cs_base + a.cs_slot;
    device const ulong * BT = BT_ALL + (is_swa ? d.bt_win_base : d.bt_full_base);
    const uint q_off = a.q_off + si * (NH * HD);
    const uint k_off = a.k_off + si * (NKV * HD);
    const uint v_off = a.v_off + si * (NKV * HD);
    const uint r_off = a.r_off + si * (NH * NREL);
    const uint qp_off = a.qp_off + si * (NH * HD);
    const uint rp_off = a.rp_off + si * (NH * NREL);
    const uint kc_off = a.kv_cur_off + si * (2 * NKV * HD) + g * HD;
    const uint vc_off = a.kv_cur_off + si * (2 * NKV * HD) + NKV * HD + g * HD;
    const int kdyn_off = a.kdyn_off >= 0 ? (a.kdyn_off + int(si * 32u)) : -1;
    const int vdyn_off = a.vdyn_off >= 0 ? (a.vdyn_off + int(si * 32u)) : -1;
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;
    device const float * qclip = (device const float *) (PB + a.qclip_w);

    float q[3];
    if (half_io) {
        device const half * qh = (device const half *) (A + a.q_off) + si * (NH * HD);
        for (int h = 0; h < 3; h++) { const uint H = g * 3 + h; q[h] = float(qh[H * HD + tid]) * qclip[H * HD + tid]; }
    } else {
        for (int h = 0; h < 3; h++) { const uint H = g * 3 + h; q[h] = A[q_off + H * HD + tid] * qclip[H * HD + tid]; }
    }

    float kx = 0, vx = 0;
    {
        const uint c = g * HD + tid;
        const float scl = kdyn_off >= 0 ? (1.0f / 3.0f) : 0.4472135954999579f;
        for (int which = 0; which < 2; which++) {
            const uint ch = 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 + cs_off + ch * 3;
            const float x = A[(which == 0 ? k_off : 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 ? kdyn_off : 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 = 0;
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        r = A[r_off + 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(kx * kx), s4 = simd_sum(vx * vx);
        const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
        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.swa >> 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]));
    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 = half_io ? float(half(qr)) : qr;
        if (half_io) {
            ((device half *) (A + a.qp_off))[si * (NH * HD) + H * HD + tid] = half(qr);
        } else {
            A[qp_off + 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 + si * NH + H] -= dc_b;
    }
#else
    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;
        if (half_io) {
            ((device half *) (A + a.qp_off))[si * (NH * HD) + H * HD + tid] = half(q[h] * f);
        } else {
            A[qp_off + H * HD + tid] = q[h] * f;
        }
    }
#endif
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        A[rp_off + H * NREL + i] = 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 = kx * kf, v = vx * vf;
#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 uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
    device kv_t * kp = dry ? (device kv_t *) nullptr : (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * KV_ROW_STEP);
    device kv_t * vp = dry ? (device kv_t *) nullptr : (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * KV_ROW_STEP);
    A[kc_off + tid] = kv4_pack_row(k_rot, tid, sg, lane, wht_sh, kp, !dry);
    A[vc_off + tid] = kv4_pack_row(v_rot, tid, sg, lane, wht_sh, vp, !dry);
#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);
    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);
    A[kc_off + tid] = qk * sk;
    A[vc_off + tid] = qv * sv;
    if (!dry) {
        const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
        device kv_t * kp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * HD;
        device kv_t * vp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * HD;
        kp[tid] = (kv_t) (int) qk;
        vp[tid] = (kv_t) (int) qv;
    }
#else
    A[kc_off + tid] = half_io ? float(half(k)) : k;
    A[vc_off + tid] = half_io ? float(half(v)) : v;
    if (!dry) {
        const uint blk = pos >> 6, ib = pos & KV_BLK_MASK;
        device kv_t * kp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff) + ib * HD;
        device kv_t * vp = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, voff) + ib * HD;
        kp[tid] = half(k);
        vp[tid] = half(v);
    }
#endif
}

// Singleton Layer 3 decode attention (`count == 1`: boundary/partial/divergent splits or `INK_NO_GRP_DEC=1`).
// 128 threads/TG, ~7.6 KiB TG memory, low register footprint for full occupancy.
kernel void k_attn_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]]) {
    threadgroup float4 qs4[3][HD / 4];
    threadgroup float  rs[3][NREL];
    threadgroup float  ms_[4][3];
    threadgroup float  ls_[4][3];
    threadgroup float4 os_[4][3][32];

    const uint gi = tgp.x, g = tgp.y;
    const bool is_swa = (a.swa & 1u) != 0u;
    const bool dry = (a.swa & 2u) != 0u;
    const bool half_io = (a.swa & 4u) != 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 rp_off = a.rp_off + si0 * (NH * NREL);
    if (half_io) {
        device const half * qph = (device const half *) (A + a.qp_off) + si0 * (NH * HD);
        for (int h = 0; h < 3; h++) {
            const uint H = g * 3 + h;
            ((threadgroup float *) qs4[h])[tid] = float(qph[H * HD + tid]);
        }
    } else {
        const uint qp_off = a.qp_off + si0 * (NH * HD);
        for (int h = 0; h < 3; h++) {
            const uint H = g * 3 + h;
            ((threadgroup float *) qs4[h])[tid] = A[qp_off + H * HD + tid];
        }
    }
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        rs[h][i] = A[rp_off + H * NREL + i];
    }
    float sink[3];
    for (int h = 0; h < 3; h++) sink[h] = A[a.sink_off + si0 * NH + g * 3 + h];
    threadgroup_barrier(mem_flags::mem_threadgroup);

    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;
    device const float * relb = (device const float *) (PB + a.relbias_w);
    const ushort kk = lane / 4, pp = lane % 4;
    const uint pos = d0.pos;
    const uint full_recent_start = is_swa ? 0u : d0.full_recent_start;
    const uint full_rlo = full_recent_start / a.kps;
    const uint p_lo = is_swa ? d0.swa_first_pos : ((full_recent_start > 0u && abs_sp > 0u) ? full_recent_start : 0u);
    const uint p1 = (!is_swa && full_recent_start > 0u && abs_sp == 0u && full_rlo > 0u)
        ? min(pos + 1u, 64u)
        : min(pos + 1u, split_end);
    const bool sink_recent_gap = (!is_swa && full_recent_start > 0u && abs_sp == 0u && full_rlo == 0u);
    const uint kc_off = a.kv_cur_off + si0 * (2 * NKV * HD) + g * HD;
    const uint vc_off = a.kv_cur_off + si0 * (2 * NKV * HD) + NKV * HD + g * HD;
    const bool cur_from_buf = dry || !half_io;
    float4 rl[3];
    for (int h = 0; h < 3; h++) rl[h] = *(threadgroup const float4 *) (&rs[h][pp * 4]);
    float mv[3] = {-INFINITY, -INFINITY, -INFINITY}, lv[3] = {0, 0, 0};
    float4 ov[3] = {0, 0, 0};
    for (uint pb = split_start + sg * 8; pb < p1; pb += 32) {
        if (pb + 8 <= p_lo) continue;
        if (sink_recent_gap && pb >= 64u && pb + 8u <= full_recent_start) continue;
        const uint raw_p = pb + kk;
        const bool valid = (raw_p >= p_lo) && (raw_p < p1) && (!sink_recent_gap || raw_p < 64u || raw_p >= full_recent_start);
        const uint p = min(max(raw_p, p_lo), p1 - 1);
        float acc[3] = {0, 0, 0};
        if (cur_from_buf && p == pos) {
            for (int c = 0; c < 8; c++) {
                const float4 kf = *(device const float4 *) (A + kc_off + pp * 32 + c * 4);
                for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
            }
        } else {
            device const kv_t * krow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, koff) + (p & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
            device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
            for (int c = 0; c < 8; c++) {
                const float4 kf = kv4_u16_to_f4(ku[c]);
                for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
            }
            const float ks = float(krow->sc);
            for (int h = 0; h < 3; h++) acc[h] *= ks;
#elif defined(KV8)
            device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(char4(kr[c]));
                for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
            }
            const float ks = kv_vscale(krow);
            for (int h = 0; h < 3; h++) acc[h] *= ks;
#else
            device const half4 * kr = (device const half4 *) (krow + pp * 32);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(kr[c]);
                for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
            }
#endif
        }
        const uint d_pos = pos - p;
        if (d_pos < EXT) {
            const float4 bb = *(device const float4 *) (relb + d_pos * NREL + pp * 4);
            for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
        }
        float pr[3], sc_[3];
        for (int h = 0; h < 3; h++) {
            float t = acc[h];
            t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
            t = valid ? t - sink[h] : -INFINITY;
            const float mx = max(mv[h], simd_max(t));
            sc_[h] = (mv[h] == -INFINITY) ? 0.0f : exp(mv[h] - mx);
            pr[h] = valid ? exp(t - mx) : 0.0f;
            lv[h] = lv[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
            mv[h] = mx;
            ov[h] *= sc_[h];
        }
#ifdef KV4
        {
            const float vsc = (cur_from_buf && p == pos) ? 1.0f : float((kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, voff) + (p & KV_BLK_MASK) * KV_ROW_STEP)->sc);
            for (int h = 0; h < 3; h++) pr[h] *= vsc;
        }
#elif defined(KV8)
        {
            const float vsc = (cur_from_buf && p == pos) ? 1.0f : kv_vscale(kv_blk_ptr(KV0, KV1, KV2, KV3, BT, p >> 6, voff) + (p & KV_BLK_MASK) * HD);
            for (int h = 0; h < 3; h++) pr[h] *= vsc;
        }
#endif
        for (ushort q = 0; q < 8; q++) {
            const uint pq = pb + q;
            if (pq < p_lo) continue;
            if (pq >= p1) break;
            if (sink_recent_gap && pq >= 64u && pq < full_recent_start) continue;
            const float4 v = (cur_from_buf && pq == pos) ? *(device const float4 *) (A + vc_off + lane * 4)
#ifdef KV4
                                         : kv4_u16_to_f4(((device const ushort *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * KV_ROW_STEP)->qs)[lane]);
#elif defined(KV8)
                                         : float4(char4(*(device const packed_char4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4)));
#else
                                         : float4(*(device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4));
#endif
            for (int h = 0; h < 3; h++) ov[h] += simd_shuffle(pr[h], q * 4) * v;
        }
    }
    if (lane == 0) for (int h = 0; h < 3; h++) { ms_[sg][h] = mv[h]; ls_[sg][h] = lv[h]; }
    for (int h = 0; h < 3; h++) os_[sg][h][lane] = ov[h];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const uint nsplit = is_swa ? d0.swa_nsplit : d0.full_nsplit;
    const uint local_sp = is_swa ? (abs_sp - (d0.swa_first_pos >> 6))
                                 : ((full_recent_start > 0u && abs_sp > 0u && full_rlo > 0u) ? (1u + abs_sp - full_rlo) : abs_sp);
    for (int h = 0; h < 3; h++) {
        float M_val = -INFINITY;
        for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, ms_[s2][h]);
        float L = 0, O = 0;
        for (int s2 = 0; s2 < 4; s2++) {
            const float w = ms_[s2][h] == -INFINITY ? 0.0f : exp(ms_[s2][h] - M_val);
            L += w * ls_[s2][h];
            O += w * ((threadgroup const float *) os_[s2][h])[tid];
        }
        device float * P = A + d0.part_off + ((g * 3 + h) * nsplit + local_sp) * (HD + 2);
        if (tid == 0) { P[0] = M_val; P[1] = L; }
        P[2 + tid] = O;
    }
}

union GrpSharedTile {
    struct {
#ifdef KV4
        kv4_row k[32];
        kv4_row v[32];
#else
        kv_t k[32][HD];
        kv_t v[32][HD];
#endif
    } kv;
    struct {
        float4 os[4][3][32];
        float  ms[4][3];
        float  ls[4][3];
    } red;
};

// Multi-query shared-KV grouped decode attention (`count` in `2..=8`, `grid = (n_shared_groups, NKV, 1)`, 512 threads/TG).
// 16 SIMD groups = 4 key stripes (`ksg = sg & 3`, exact `k_attn` order) x 4 lane pairs (`lsg = sg >> 2`, <= 2 lanes/SG).
// Cooperatively stages 32 K + 32 V vectors from DRAM ONCE into TG SRAM (`16.00 KiB` fp16 / `8.25 KiB` KV8) for all `m <= 8`
// lanes, fitting 2 TGs/core (1024 threads/core) on M5 with <= 60 regs/thread (zero register spills).
// Bit-for-bit identical to `k_attn` / `k_attn_dec_solo` / `k_attn_fixed_b_blk` on every lane and every split.
kernel void k_attn_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]]) {
    threadgroup GrpSharedTile sh;
#ifdef KV8
    threadgroup float ks_tile[32];
    threadgroup float vs_tile[32];
#endif

    const uint gi = tgp.x, g = tgp.y;
    const bool is_swa = (a.swa & 1u) != 0u;
    const bool half_io = (a.swa & 4u) != 0u;
    device const DecAttnGroup & grp = ((device const DecAttnGroup *) (A + a.grp_off))[gi];
    const uint m = grp.count;
    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;
    device const float * relb = (device const float *) (PB + a.relbias_w);

    const ushort ksg = sg & 3;
    const ushort lsg = sg >> 2;
    const ushort kk = lane / 4, pp = lane % 4;
    const uint u0 = uint(lsg) * 2u;
    const uint u1 = u0 + 1u;
    const bool has0 = u0 < m;
    const bool has1 = u1 < m;

    const uint si_u0 = has0 ? uint(grp.span_idx[u0]) : 0u;
    const uint si_u1 = has1 ? uint(grp.span_idx[u1]) : 0u;
    device const float4 * qp0 = (device const float4 *) (A + a.qp_off + si_u0 * (NH * HD) + (g * 3) * HD);
    device const float4 * qp1 = (device const float4 *) (A + a.qp_off + si_u1 * (NH * HD) + (g * 3) * HD);
    device const half4 * qph0 = (device const half4 *) ((device const half *) (A + a.qp_off) + si_u0 * (NH * HD) + (g * 3) * HD);
    device const half4 * qph1 = (device const half4 *) ((device const half *) (A + a.qp_off) + si_u1 * (NH * HD) + (g * 3) * HD);
    device const float * rp0 = A + a.rp_off + si_u0 * (NH * NREL) + (g * 3) * NREL;
    device const float * rp1 = A + a.rp_off + si_u1 * (NH * NREL) + (g * 3) * NREL;

    float mv0[3] = {-INFINITY, -INFINITY, -INFINITY}, lv0[3] = {0, 0, 0};
    float4 ov0[3] = {0, 0, 0};
    float mv1[3] = {-INFINITY, -INFINITY, -INFINITY}, lv1[3] = {0, 0, 0};
    float4 ov1[3] = {0, 0, 0};

    const uint pos0 = has0 ? descs[si_u0].pos : 0u;
    const uint pos1 = has1 ? descs[si_u1].pos : 0u;
    float s0[3], s1[3];
    if (has0) for (int h = 0; h < 3; h++) s0[h] = A[a.sink_off + si_u0 * NH + g * 3 + h];
    if (has1) for (int h = 0; h < 3; h++) s1[h] = A[a.sink_off + si_u1 * NH + g * 3 + h];

    for (uint pb_base = split_start; pb_base < split_end; pb_base += 32) {
        if (pb_base > split_start) threadgroup_barrier(mem_flags::mem_threadgroup);
        device const kv_t * k_blk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pb_base >> 6, koff) + (pb_base & KV_BLK_MASK) * KV_ROW_STEP;
        device const kv_t * v_blk = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pb_base >> 6, voff) + (pb_base & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
        for (uint i = tid; i < 32u * 33u; i += 512u) {
            ((threadgroup ushort *) sh.kv.k)[i] = ((device const ushort *) k_blk)[i];
            ((threadgroup ushort *) sh.kv.v)[i] = ((device const ushort *) v_blk)[i];
        }
#elif defined(KV8)
        ((threadgroup char4 *) sh.kv.k)[tid] = char4(((device const packed_char4 *) k_blk)[tid]);
        ((threadgroup char4 *) sh.kv.k)[tid + 512] = char4(((device const packed_char4 *) k_blk)[tid + 512]);
        ((threadgroup char4 *) sh.kv.v)[tid] = char4(((device const packed_char4 *) v_blk)[tid]);
        ((threadgroup char4 *) sh.kv.v)[tid + 512] = char4(((device const packed_char4 *) v_blk)[tid + 512]);
        if (tid < 32) {
            ks_tile[tid] = kv_vscale(k_blk + tid * HD);
            vs_tile[tid] = kv_vscale(v_blk + tid * HD);
        }
#else
        ((threadgroup half4 *) sh.kv.k)[tid] = ((device const half4 *) k_blk)[tid];
        ((threadgroup half4 *) sh.kv.k)[tid + 512] = ((device const half4 *) k_blk)[tid + 512];
        ((threadgroup half4 *) sh.kv.v)[tid] = ((device const half4 *) v_blk)[tid];
        ((threadgroup half4 *) sh.kv.v)[tid + 512] = ((device const half4 *) v_blk)[tid + 512];
#endif
        threadgroup_barrier(mem_flags::mem_threadgroup);

        if (has0 && has1) {
            const uint row_k = ksg * 8 + kk;
            const uint p = pb_base + row_k;
            float acc0[3] = {0, 0, 0};
            float acc1[3] = {0, 0, 0};
#ifdef KV4
            threadgroup const ushort * ku = (threadgroup const ushort *) sh.kv.k[row_k].qs + pp * 8;
            for (int c = 0; c < 8; c++) {
                const float4 kf = kv4_u16_to_f4(ku[c]);
                const uint qidx = pp * 8 + c;
                for (int h = 0; h < 3; h++) {
                    const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
                    const float4 q1v = half_io ? float4(qph1[h * 32 + qidx]) : qp1[h * 32 + qidx];
                    acc0[h] += dot(q0v, kf);
                    acc1[h] += dot(q1v, kf);
                }
            }
            const float ks = float(sh.kv.k[row_k].sc);
            for (int h = 0; h < 3; h++) { acc0[h] *= ks; acc1[h] *= ks; }
            const float vsc = float(sh.kv.v[row_k].sc);
#elif defined(KV8)
            threadgroup const char4 * kr = (threadgroup const char4 *) (&sh.kv.k[row_k][pp * 32]);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(kr[c]);
                const uint qidx = pp * 8 + c;
                for (int h = 0; h < 3; h++) {
                    const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
                    const float4 q1v = half_io ? float4(qph1[h * 32 + qidx]) : qp1[h * 32 + qidx];
                    acc0[h] += dot(q0v, kf);
                    acc1[h] += dot(q1v, kf);
                }
            }
            const float ks = ks_tile[row_k];
            for (int h = 0; h < 3; h++) { acc0[h] *= ks; acc1[h] *= ks; }
            const float vsc = vs_tile[row_k];
#else
            threadgroup const half4 * kr = (threadgroup const half4 *) (&sh.kv.k[row_k][pp * 32]);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(kr[c]);
                const uint qidx = pp * 8 + c;
                for (int h = 0; h < 3; h++) {
                    const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
                    const float4 q1v = half_io ? float4(qph1[h * 32 + qidx]) : qp1[h * 32 + qidx];
                    acc0[h] += dot(q0v, kf);
                    acc1[h] += dot(q1v, kf);
                }
            }
#endif
            const uint d0_pos = pos0 - p;
            if (d0_pos < EXT) {
                const float4 bb = *(device const float4 *) (relb + d0_pos * NREL + pp * 4);
                for (int h = 0; h < 3; h++) acc0[h] += dot(*(device const float4 *) (rp0 + h * NREL + pp * 4), bb);
            }
            const uint d1_pos = pos1 - p;
            if (d1_pos < EXT) {
                const float4 bb = *(device const float4 *) (relb + d1_pos * NREL + pp * 4);
                for (int h = 0; h < 3; h++) acc1[h] += dot(*(device const float4 *) (rp1 + h * NREL + pp * 4), bb);
            }
            float pr0[3], pr1[3];
            for (int h = 0; h < 3; h++) {
                float t0 = acc0[h];
                t0 += simd_shuffle_xor(t0, 1); t0 += simd_shuffle_xor(t0, 2);
                t0 -= s0[h];
                const float mx0 = max(mv0[h], simd_max(t0));
                const float sc0 = (mv0[h] == -INFINITY) ? 0.0f : exp(mv0[h] - mx0);
                float p0v = exp(t0 - mx0);
                lv0[h] = lv0[h] * sc0 + simd_sum(p0v) * 0.25f;
                mv0[h] = mx0;
                ov0[h] *= sc0;
#if defined(KV8) || defined(KV4)
                p0v *= vsc;
#endif
                pr0[h] = p0v;

                float t1 = acc1[h];
                t1 += simd_shuffle_xor(t1, 1); t1 += simd_shuffle_xor(t1, 2);
                t1 -= s1[h];
                const float mx1 = max(mv1[h], simd_max(t1));
                const float sc1 = (mv1[h] == -INFINITY) ? 0.0f : exp(mv1[h] - mx1);
                float p1v = exp(t1 - mx1);
                lv1[h] = lv1[h] * sc1 + simd_sum(p1v) * 0.25f;
                mv1[h] = mx1;
                ov1[h] *= sc1;
#if defined(KV8) || defined(KV4)
                p1v *= vsc;
#endif
                pr1[h] = p1v;
            }
            for (ushort q = 0; q < 8; q++) {
#ifdef KV4
                const float4 v = kv4_u16_to_f4(((threadgroup const ushort *) sh.kv.v[ksg * 8 + q].qs)[lane]);
#elif defined(KV8)
                const float4 v = float4(*(threadgroup const char4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#else
                const float4 v = float4(*(threadgroup const half4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#endif
                for (int h = 0; h < 3; h++) {
                    ov0[h] += simd_shuffle(pr0[h], q * 4) * v;
                    ov1[h] += simd_shuffle(pr1[h], q * 4) * v;
                }
            }
        } else if (has0) {
            const uint row_k = ksg * 8 + kk;
            const uint p = pb_base + row_k;
            float acc0[3] = {0, 0, 0};
#ifdef KV4
            threadgroup const ushort * ku = (threadgroup const ushort *) sh.kv.k[row_k].qs + pp * 8;
            for (int c = 0; c < 8; c++) {
                const float4 kf = kv4_u16_to_f4(ku[c]);
                const uint qidx = pp * 8 + c;
                for (int h = 0; h < 3; h++) {
                    const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
                    acc0[h] += dot(q0v, kf);
                }
            }
            const float ks = float(sh.kv.k[row_k].sc);
            for (int h = 0; h < 3; h++) acc0[h] *= ks;
            const float vsc = float(sh.kv.v[row_k].sc);
#elif defined(KV8)
            threadgroup const char4 * kr = (threadgroup const char4 *) (&sh.kv.k[row_k][pp * 32]);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(kr[c]);
                const uint qidx = pp * 8 + c;
                for (int h = 0; h < 3; h++) {
                    const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
                    acc0[h] += dot(q0v, kf);
                }
            }
            const float ks = ks_tile[row_k];
            for (int h = 0; h < 3; h++) acc0[h] *= ks;
            const float vsc = vs_tile[row_k];
#else
            threadgroup const half4 * kr = (threadgroup const half4 *) (&sh.kv.k[row_k][pp * 32]);
            for (int c = 0; c < 8; c++) {
                const float4 kf = float4(kr[c]);
                const uint qidx = pp * 8 + c;
                for (int h = 0; h < 3; h++) {
                    const float4 q0v = half_io ? float4(qph0[h * 32 + qidx]) : qp0[h * 32 + qidx];
                    acc0[h] += dot(q0v, kf);
                }
            }
#endif
            const uint d0_pos = pos0 - p;
            if (d0_pos < EXT) {
                const float4 bb = *(device const float4 *) (relb + d0_pos * NREL + pp * 4);
                for (int h = 0; h < 3; h++) acc0[h] += dot(*(device const float4 *) (rp0 + h * NREL + pp * 4), bb);
            }
            float pr0[3];
            for (int h = 0; h < 3; h++) {
                float t0 = acc0[h];
                t0 += simd_shuffle_xor(t0, 1); t0 += simd_shuffle_xor(t0, 2);
                t0 -= s0[h];
                const float mx0 = max(mv0[h], simd_max(t0));
                const float sc0 = (mv0[h] == -INFINITY) ? 0.0f : exp(mv0[h] - mx0);
                float p0v = exp(t0 - mx0);
                lv0[h] = lv0[h] * sc0 + simd_sum(p0v) * 0.25f;
                mv0[h] = mx0;
                ov0[h] *= sc0;
#if defined(KV8) || defined(KV4)
                p0v *= vsc;
#endif
                pr0[h] = p0v;
            }
            for (ushort q = 0; q < 8; q++) {
#ifdef KV4
                const float4 v = kv4_u16_to_f4(((threadgroup const ushort *) sh.kv.v[ksg * 8 + q].qs)[lane]);
#elif defined(KV8)
                const float4 v = float4(*(threadgroup const char4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#else
                const float4 v = float4(*(threadgroup const half4 *) (&sh.kv.v[ksg * 8 + q][lane * 4]));
#endif
                for (int h = 0; h < 3; h++) ov0[h] += simd_shuffle(pr0[h], q * 4) * v;
            }
        }
    }

    // Epilogue: reuse `sh.red` (aliasing `sh.kv`) across lanes `u = 0..m` with exact 4-stripe reduction.
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (uint u = 0; u < m; u++) {
        if (u > 0u) threadgroup_barrier(mem_flags::mem_threadgroup);
        if (uint(lsg) == (u >> 1)) {
            if ((u & 1u) == 0u) {
                if (lane == 0) for (int h = 0; h < 3; h++) { sh.red.ms[ksg][h] = mv0[h]; sh.red.ls[ksg][h] = lv0[h]; }
                for (int h = 0; h < 3; h++) sh.red.os[ksg][h][lane] = ov0[h];
            } else {
                if (lane == 0) for (int h = 0; h < 3; h++) { sh.red.ms[ksg][h] = mv1[h]; sh.red.ls[ksg][h] = lv1[h]; }
                for (int h = 0; h < 3; h++) sh.red.os[ksg][h][lane] = ov1[h];
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (tid < 128u) {
            const uint si = uint(grp.span_idx[u]);
            device const DecodeSpanDesc & du = descs[si];
            const uint nsplit = is_swa ? du.swa_nsplit : du.full_nsplit;
            const uint rlo = (!is_swa && du.full_recent_start > 0u) ? (du.full_recent_start / a.kps) : 0u;
            const uint local_sp = is_swa ? (abs_sp - (du.swa_first_pos >> 6))
                                         : ((du.full_recent_start > 0u && abs_sp > 0u && rlo > 0u) ? (1u + abs_sp - rlo) : abs_sp);
            for (int h = 0; h < 3; h++) {
                float M_val = -INFINITY;
                for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, sh.red.ms[s2][h]);
                float L = 0, O = 0;
                for (int s2 = 0; s2 < 4; s2++) {
                    const float w = sh.red.ms[s2][h] == -INFINITY ? 0.0f : exp(sh.red.ms[s2][h] - M_val);
                    L += w * sh.red.ls[s2][h];
                    O += w * ((threadgroup const float *) sh.red.os[s2][h])[tid];
                }
                device float * P = A + du.part_off + ((g * 3 + h) * nsplit + local_sp) * (HD + 2);
                if (tid == 0) { P[0] = M_val; P[1] = L; }
                P[2 + tid] = O;
            }
        }
    }
}

// Layer 3 block-addressed cache-fixed-split prefill attention (`grid = (nsplit, NKV, ceil(nrows / tg_rows))`,
// 128 threads/TG). Bit-for-bit identical to `k_attn_fixed_b`, `k_attn_dec_solo`, and `k_attn_grp_dec`.
// `p.k_base` carries the pass index within the pool kind (0..40 window, 0..8 full).
// A threadgroup runs `p.tg_rows` (1..ATT_TG_ROWS) consecutive query rows of one split: each K slice and V row is
// read once and applied to every row whose keys it is, in the per-row order a lone row uses. The host passes
// `tg_rows > 1` only when every row's split starts at `sp * kps` (full attention, no budget pruning).
#define ATT_TG_ROWS 4
kernel void k_attn_fixed_b_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)]],
                               uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                               ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    const uint g = tg.y, sp = tg.x, row0 = tg.z * p.tg_rows;
    const uint nr = min(p.tg_rows, p.nrows - row0);
    uint p_lo[ATT_TG_ROWS], split_start = 0u, p1[ATT_TG_ROWS], gap_end[ATT_TG_ROWS];
    bool live[ATT_TG_ROWS];
    uint p_max = 0u;
    for (uint r = 0; r < ATT_TG_ROWS; ++r) {
        live[r] = false; p_lo[r] = 0u; p1[r] = 0u; gap_end[r] = 0u;
        if (r >= nr) continue;
        const uint pos = p.pos0 + row0 + r, p_hi = pos + 1u;
        const bool pruned = (p.window == 0u) && (p.full_budget > 0u) && (p_hi > p.full_budget);
        uint ss;
        if (pruned) {
            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 (sp >= count) continue;
            const uint abs_sp = (rlo == 0u || sp == 0u) ? sp : (rlo + sp - 1u);
            ss = abs_sp * p.kps;
            p_lo[r] = (abs_sp > 0u) ? recent_start : 0u;
            p1[r] = (abs_sp == 0u && rlo > 0u) ? min(p_hi, 64u) : min(p_hi, ss + p.kps);
            if (abs_sp == 0u && rlo == 0u) gap_end[r] = recent_start;
        } else {
            p_lo[r] = (p.window != 0u && p_hi > p.window) ? (p_hi - p.window) : 0u;
            ss = (p_lo[r] / p.kps + sp) * p.kps;
            if (ss >= p_hi) continue;
            p1[r] = min(p_hi, ss + p.kps);
        }
        live[r] = true; split_start = ss; p_max = max(p_max, p1[r]);
    }
    if (p_max == 0u) return;
    const ulong koff = ulong(p.k_base) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    const ulong voff = koff + KV_PLANE_BYTES;

    threadgroup float4 qs4[ATT_TG_ROWS][3][HD / 4];
    threadgroup float  rs[ATT_TG_ROWS][3][NREL];
    threadgroup float  ms_[4][3];
    threadgroup float  ls_[4][3];
    threadgroup float4 os_[4][3][32];
    threadgroup float sink[ATT_TG_ROWS][3];
    for (uint r = 0; r < nr; ++r) {
        for (uint h = 0; h < 3; ++h) {
            const uint head = (row0 + r) * NH + g * 3 + h, qi = head * HD + tid;
            ((threadgroup float *) qs4[r][h])[tid] = p.half_io ? float(((device const half *) (A + p.q_off))[qi]) : A[p.q_off + qi];
            if (tid < NREL) rs[r][h][tid] = A[p.r_off + head * NREL + tid];
            if (tid == 0) sink[r][h] = A[p.sink_off + head];
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    device const float * relb = (device const float *) (PB + p.relbias_w);
    const ushort kk = lane / 4, pp = lane % 4;
    float mv[ATT_TG_ROWS][3], lv[ATT_TG_ROWS][3];
    float4 ov[ATT_TG_ROWS][3];
    for (uint r = 0; r < ATT_TG_ROWS; ++r) {
        for (int h = 0; h < 3; h++) {
            mv[r][h] = -INFINITY; lv[r][h] = 0; ov[r][h] = 0;
        }
    }
    // the shared key clamp: one row's own when tg_rows == 1; with more rows every live row has p_lo == 0
    const uint lo0 = p_lo[0];
    for (uint pb = split_start + sg * 8; pb < p_max; pb += 32) {
        const uint raw_p = pb + kk;
        const uint kp = min(max(raw_p, lo0), p_max - 1);
        device const kv_t * krow = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kp >> 6, koff) + (kp & KV_BLK_MASK) * KV_ROW_STEP;
#ifdef KV4
        device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
        float4 kf[8];
        for (int c = 0; c < 8; c++) kf[c] = kv4_u16_to_f4(ku[c]);
        const float ks = float(krow->sc);
        const float vsc = float((kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kp >> 6, voff) + (kp & KV_BLK_MASK) * KV_ROW_STEP)->sc);
#elif defined(KV8)
        device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
        float4 kf[8];
        for (int c = 0; c < 8; c++) kf[c] = float4(char4(kr[c]));
        const float ks = kv_vscale(krow);
        const float vsc = kv_vscale(kv_blk_ptr(KV0, KV1, KV2, KV3, BT, kp >> 6, voff) + (kp & KV_BLK_MASK) * HD);
#else
        device const half4 * kr = (device const half4 *) (krow + pp * 32);
        float4 kf[8];
        for (int c = 0; c < 8; c++) kf[c] = float4(kr[c]);
#endif
        bool run[ATT_TG_ROWS];
        float pr[ATT_TG_ROWS][3];
        for (uint r = 0; r < ATT_TG_ROWS; ++r) {
            const uint gap = gap_end[r];
            run[r] = live[r] && pb < p1[r] && !(pb + 8 <= p_lo[r]) && !(gap > 0u && pb >= 64u && pb + 8u <= gap);
            if (!run[r]) continue;
            const uint pos = p.pos0 + row0 + r;
            const bool valid = (raw_p >= p_lo[r]) && (raw_p < p1[r]) && (gap == 0u || raw_p < 64u || raw_p >= gap);
            float acc[3] = {0, 0, 0};
            for (int c = 0; c < 8; c++)
                for (int h = 0; h < 3; h++) acc[h] += dot(qs4[r][h][pp * 8 + c], kf[c]);
#if defined(KV4) || defined(KV8)
            for (int h = 0; h < 3; h++) acc[h] *= ks;
#endif
            // invalid lanes are masked to -inf below, so they skip the bias; valid ones have kp <= pos
            if (valid && pos >= kp && (pos - kp) < EXT) {
                const float4 bb = *(device const float4 *) (relb + (pos - kp) * NREL + pp * 4);
                for (int h = 0; h < 3; h++) acc[h] += dot(*(threadgroup const float4 *) (&rs[r][h][pp * 4]), bb);
            }
            for (int h = 0; h < 3; h++) {
                float t = acc[h];
                t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
                t = valid ? t - sink[r][h] : -INFINITY;
                const float mx = max(mv[r][h], simd_max(t));
                const float sc_ = (mv[r][h] == -INFINITY) ? 0.0f : exp(mv[r][h] - mx);
                pr[r][h] = valid ? exp(t - mx) : 0.0f;
                lv[r][h] = lv[r][h] * sc_ + simd_sum(pr[r][h]) * 0.25f;
                mv[r][h] = mx;
                ov[r][h] *= sc_;
#if defined(KV4) || defined(KV8)
                pr[r][h] *= vsc;
#endif
            }
        }
        for (ushort q = 0; q < 8; q++) {
            const uint pq = pb + q;
            if (pq >= p_max) break;
            if (pq < lo0 || (gap_end[0] > 0u && pq >= 64u && pq < gap_end[0])) continue;  // never read released blocks
            const float4 v =
#ifdef KV4
                kv4_u16_to_f4(((device const ushort *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * KV_ROW_STEP)->qs)[lane]);
#elif defined(KV8)
                float4(char4(*(device const packed_char4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4)));
#else
                float4(*(device const half4 *) (kv_blk_ptr(KV0, KV1, KV2, KV3, BT, pq >> 6, voff) + (pq & KV_BLK_MASK) * HD + lane * 4));
#endif
            for (uint r = 0; r < ATT_TG_ROWS; ++r) {
                if (!run[r] || pq < p_lo[r] || pq >= p1[r]) continue;
                if (gap_end[r] > 0u && pq >= 64u && pq < gap_end[r]) continue;
                for (int h = 0; h < 3; h++) ov[r][h] += simd_shuffle(pr[r][h], q * 4) * v;
            }
        }
    }
    for (uint r = 0; r < nr; ++r) {
        if (!live[r]) continue;
        if (r > 0u) threadgroup_barrier(mem_flags::mem_threadgroup);
        if (lane == 0) for (int h = 0; h < 3; h++) { ms_[sg][h] = mv[r][h]; ls_[sg][h] = lv[r][h]; }
        for (int h = 0; h < 3; h++) os_[sg][h][lane] = ov[r][h];
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const uint part_off = p.part_off + (row0 + r) * NH * p.nsplit * (HD + 2);
        for (int h = 0; h < 3; h++) {
            float M_val = -INFINITY;
            for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, ms_[s2][h]);
            float L = 0, O = 0;
            for (int s2 = 0; s2 < 4; s2++) {
                const float w = ms_[s2][h] == -INFINITY ? 0.0f : exp(ms_[s2][h] - M_val);
                L += w * ls_[s2][h];
                O += w * ((threadgroup const float *) os_[s2][h])[tid];
            }
            device float * P = A + part_off + ((g * 3 + h) * p.nsplit + sp) * (HD + 2);
            if (tid == 0) { P[0] = M_val; P[1] = L; }
            P[2 + tid] = O;
        }
    }
}
#pragma clang fp contract(off) reassociate(off)
// DSpark speculative rejection sampling (`k_dspark_reject`):
// Grid: (1, n_spans, 1), 1024 threads (32 simdgroups).
// - When `eff_temp < 1e-5f`: exact greedy verification against raw target argmax (lowest-token-ID tie break).
// - When `eff_temp >= 1e-5f`: exact Leviathan/Chen rejection sampling (`u < min(1, p_target[x] / p_draft[x])`),
//   exact Gumbel-max residual resampling over `[p_target - p_draft]_+` on rejection, and exact Gumbel-max
//   bonus token draw from `p_target` at row `k` when all `k` draft tokens are accepted.

struct DSparkSpanDesc {
    uint  target_off;
    uint  draft_lg_off;
    uint  draft_tok_off;
    uint  out_off;
    uint  k;
    uint  seed_lo;
    uint  seed_hi;
    uint  base_pos;
    uint  ban_tok;
    float temp;
    uint  never_tok; // <|endoftext|> (Engine::set_never_token), masked like ban_tok
    uint  onehot;    // 1: deterministic draft (prompt lookup), q = one_hot(dx); DRAFT_LG is not read
};

inline bool dspark_banned(const DSparkSpanDesc desc, uint v) { return v == desc.ban_tok || v == desc.never_tok; }

struct DSparkRejectArgs {
    uint  n_vocab;
    uint  target_stride;
    uint  draft_stride;
    float temp;
    float target_softcap;
    float draft_softcap;
    uint  pad0, pad1;
};

inline float dspark_uniform(uint stream_key, uint pos, uint seed_lo, uint seed_hi) {
    const uint h = mix32(mix32(mix32(mix32(stream_key) ^ pos) ^ seed_lo) ^ seed_hi);
    return (float(h >> 9) + 0.5f) * (1.0f / 8388608.0f);
}

inline float dspark_softcap(float raw, float cap) {
    return cap > 0.0f ? (cap * precise::tanh(raw / cap)) : raw;
}

inline void dspark_argmax_reduce(
    thread float & val,
    thread int & idx,
    ushort sg,
    ushort lane,
    threadgroup float * bv,
    threadgroup int * bi,
    threadgroup uint & out_tok,
    threadgroup float & out_val,
    uint n_vocab
) {
    const float m = simd_max(val);
    int c = (val == m) ? idx : 0x7fffffff;
    c = simd_min(c);
    if (lane == 0) { bv[sg] = m; bi[sg] = c; }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (sg == 0) {
        const float v2 = bv[lane];
        const int i2 = bi[lane];
        const float m2 = simd_max(v2);
        int c2 = (v2 == m2) ? i2 : 0x7fffffff;
        c2 = simd_min(c2);
        if (lane == 0) {
            out_val = m2;
            out_tok = uint(c2) < n_vocab ? uint(c2) : 0u;
        }
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
}

kernel void k_dspark_reject(
    device const float * A [[buffer(2)]],
    constant DSparkRejectArgs & a [[buffer(5)]],
    device const DSparkSpanDesc * DESCS [[buffer(6)]],
    device const uint * DRAFT_TOKS [[buffer(8)]],
    device const float * DRAFT_LG [[buffer(9)]],
    device uint * OUT [[buffer(10)]],
    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 bv[32], bq[32];
    threadgroup int   bi[32];
    threadgroup uint  bu[32];
    threadgroup float sh_f[4];
    threadgroup uint  sh_u[4];
    threadgroup uint  chosen_tok;
    threadgroup float chosen_val;

    const uint si = tgp.y;
    const DSparkSpanDesc desc = DESCS[si];
    const uint n = a.n_vocab;
    if (n == 0u) {
        if (tid == 0) { OUT[desc.out_off] = 1u; OUT[desc.out_off + 1] = 0u; }
        return;
    }

    const float eff_temp = (desc.temp >= 0.0f) ? desc.temp : a.temp;

    // ---- Greedy verification (`eff_temp < 1e-5f`): exact raw-logit target argmax match ----
    if (eff_temp < 1e-5f) {
        for (uint d = 0u; d <= desc.k; d++) {
            device const float * ZT = A + ulong(desc.target_off) + ulong(d) * ulong(a.target_stride);
            float best = -INFINITY;
            int best_i = 0x7fffffff;
            uint bad = 0u;
            for (uint v = tid; v < n; v += 1024u) {
                const float raw = ZT[v];
                if (isnan(raw) || isinf(raw)) { bad = 1u; continue; }
                if (dspark_banned(desc, v)) continue;
                if (raw > best || (raw == best && int(v) < best_i)) { best = raw; best_i = int(v); }
            }
            const uint sg_bad = simd_or(bad);
            if (lane == 0) bu[sg] = sg_bad;
            dspark_argmax_reduce(best, best_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
            if (sg == 0) {
                const uint all_bad = simd_or(bu[lane]);
                if (lane == 0) sh_u[0] = (all_bad != 0u || chosen_val == -INFINITY) ? 1u : 0u;
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);
            if (sh_u[0] != 0u) {
                if (tid == 0) { OUT[desc.out_off] = 1u; OUT[desc.out_off + 1] = 0u; }
                return;
            }
            const uint star = chosen_tok;
            if (d < desc.k) {
                const uint dx = DRAFT_TOKS[desc.draft_tok_off + d];
                if (dx >= n) {
                    if (tid == 0) { OUT[desc.out_off] = 2u; OUT[desc.out_off + 1] = 0u; }
                    return;
                }
                if (dx == star) {
                    if (tid == 0) OUT[desc.out_off + 2u + d] = dx;
                    threadgroup_barrier(mem_flags::mem_threadgroup);
                    continue;
                }
                if (tid == 0) {
                    OUT[desc.out_off + 0u] = 0u;
                    OUT[desc.out_off + 1u] = d;
                    OUT[desc.out_off + 2u + d] = star;
                }
                return;
            } else {
                if (tid == 0) {
                    OUT[desc.out_off + 0u] = 0u;
                    OUT[desc.out_off + 1u] = desc.k;
                    OUT[desc.out_off + 2u + desc.k] = star;
                }
                return;
            }
        }
        return;
    }

    // ---- Stochastic exact speculative rejection sampling (`eff_temp >= 1e-5f`) ----
    const float inv_temp = 1.0f / eff_temp;
    for (uint d = 0u; d < desc.k; d++) {
        const uint dx = DRAFT_TOKS[desc.draft_tok_off + d];
        if (dx >= n) {
            if (tid == 0) { OUT[desc.out_off] = 2u; OUT[desc.out_off + 1] = 0u; }
            return;
        }
        device const float * ZT = A + ulong(desc.target_off) + ulong(d) * ulong(a.target_stride);
        device const float * ZQ = DRAFT_LG + ulong(desc.draft_lg_off) + ulong(d) * ulong(a.draft_stride);

        // Pass 1: global max of scaled target & draft logits + non-finite guard.
        float mt = -INFINITY, mq = -INFINITY;
        uint bad = 0u;
        const bool onehot = desc.onehot != 0u;
        for (uint v = tid; v < n; v += 1024u) {
            const float rt = ZT[v];
            const float rq = onehot ? 0.0f : ZQ[v];
            if (isnan(rt) || isinf(rt)) { bad |= 1u; continue; }
            if (isnan(rq) || isinf(rq)) { bad |= 2u; continue; }
            if (dspark_banned(desc, v)) continue;
            mt = max(mt, dspark_softcap(rt, a.target_softcap) * inv_temp);
            mq = max(mq, dspark_softcap(rq, a.draft_softcap) * inv_temp);
        }
        const float smt = simd_max(mt), smq = simd_max(mq);
        const uint sbad = simd_or(bad);
        if (lane == 0) { bv[sg] = smt; bq[sg] = smq; bu[sg] = sbad; }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (sg == 0) {
            const float gmt = simd_max(bv[lane]);
            const float gmq = simd_max(bq[lane]);
            const uint gbad = simd_or(bu[lane]);
            if (lane == 0) {
                sh_f[0] = gmt;
                sh_f[1] = gmq;
                sh_u[0] = gbad != 0u ? ((gbad & 1u) != 0u ? 1u : 2u) : ((gmt == -INFINITY || gmq == -INFINITY) ? 1u : 0u);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (sh_u[0] != 0u) {
            if (tid == 0) { OUT[desc.out_off] = sh_u[0]; OUT[desc.out_off + 1] = 0u; }
            return;
        }
        const float max_t = sh_f[0], max_q = sh_f[1];

        // Pass 2: exact softmax partition sums Z_t and Z_q.
        float sum_t = 0.0f, sum_q = 0.0f;
        for (uint v = tid; v < n; v += 1024u) {
            if (dspark_banned(desc, v)) continue;
            const float st = dspark_softcap(ZT[v], a.target_softcap) * inv_temp;
            sum_t += precise::exp(st - max_t);
            if (!onehot) {
                const float sq = dspark_softcap(ZQ[v], a.draft_softcap) * inv_temp;
                sum_q += precise::exp(sq - max_q);
            } else {
                sum_q += 1.0f;
            }
        }
        const float sgt = simd_sum(sum_t), sgq = simd_sum(sum_q);
        if (lane == 0) { bv[sg] = sgt; bq[sg] = sgq; }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (sg == 0) {
            const float zt = simd_sum(bv[lane]);
            const float zq = simd_sum(bq[lane]);
            if (lane == 0) {
                sh_f[2] = zt;
                sh_f[3] = zq;
                const bool ok_z = !isnan(zt) && !isinf(zt) && zt > 0.0f && !isnan(zq) && !isinf(zq) && zq > 0.0f;
                if (!ok_z) {
                    sh_u[0] = 1u;
                    sh_u[1] = 0u;
                } else {
                    const float ptx = dspark_banned(desc, dx)
                        ? 0.0f
                        : (precise::exp(dspark_softcap(ZT[dx], a.target_softcap) * inv_temp - max_t) / zt);
                    // One-hot: q(dx) = 1, so the test below is `u < min(1, p(dx))` (a banned dx has p = 0 and is
                    // always rejected, its residual then being p itself).
                    const float pqx = onehot
                        ? 1.0f
                        : (dspark_banned(desc, dx)
                            ? 0.0f
                            : (precise::exp(dspark_softcap(ZQ[dx], a.draft_softcap) * inv_temp - max_q) / zq));
                    const float u_acc = dspark_uniform(0xA5A55A5Au ^ d, desc.base_pos + d, desc.seed_lo, desc.seed_hi);
                    const bool accept = (pqx <= 0.0f) ? (ptx > 0.0f) : (u_acc * pqx < min(pqx, ptx));
                    sh_u[0] = 0u;
                    sh_u[1] = accept ? 1u : 0u;
                }
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (sh_u[0] != 0u) {
            if (tid == 0) { OUT[desc.out_off] = sh_u[0]; OUT[desc.out_off + 1] = 0u; }
            return;
        }
        if (sh_u[1] != 0u) {
            if (tid == 0) OUT[desc.out_off + 2u + d] = dx;
            threadgroup_barrier(mem_flags::mem_threadgroup);
            continue;
        }

        // Rejected at d: resample from normalized [p_target - p_draft]_+ via exact Gumbel-max.
        const float inv_zt = 1.0f / sh_f[2];
        const float inv_zq = 1.0f / sh_f[3];
        float best = -INFINITY;
        int best_i = 0x7fffffff;
        for (uint v = tid; v < n; v += 1024u) {
            if (dspark_banned(desc, v)) continue;
            const float st = dspark_softcap(ZT[v], a.target_softcap) * inv_temp;
            // One-hot residual [p - one_hot(dx)]_+ is p with dx zeroed.
            const float diff = onehot
                ? (v == dx ? 0.0f : precise::exp(st - max_t) * inv_zt)
                : (precise::exp(st - max_t) * inv_zt
                    - precise::exp(dspark_softcap(ZQ[v], a.draft_softcap) * inv_temp - max_q) * inv_zq);
            if (diff > 0.0f) {
                const float uv = dspark_uniform(v ^ 0x6C8E9CF5u, desc.base_pos + d, desc.seed_lo, desc.seed_hi);
                const float g = precise::log(diff) - precise::log(-precise::log(uv));
                if (g > best || (g == best && int(v) < best_i)) { best = g; best_i = int(v); }
            }
        }
        dspark_argmax_reduce(best, best_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
        if (chosen_val == -INFINITY) {
            // Degenerate zero-residual fallback (identical p_target == p_draft): Gumbel-max over p_target.
            float fbest = -INFINITY;
            int fbest_i = 0x7fffffff;
            for (uint v = tid; v < n; v += 1024u) {
                if (dspark_banned(desc, v)) continue;
                const float st = dspark_softcap(ZT[v], a.target_softcap) * inv_temp;
                const float uv = dspark_uniform(v ^ 0x9e3779b9u, desc.base_pos + d, desc.seed_lo, desc.seed_hi);
                const float g = st - precise::log(-precise::log(uv));
                if (g > fbest || (g == fbest && int(v) < fbest_i)) { fbest = g; fbest_i = int(v); }
            }
            dspark_argmax_reduce(fbest, fbest_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
        }
        if (tid == 0) {
            OUT[desc.out_off + 0u] = 0u;
            OUT[desc.out_off + 1u] = d;
            OUT[desc.out_off + 2u + d] = chosen_tok;
        }
        return;
    }

    // All `k` draft tokens accepted: draw bonus token at row `k` from p_target via exact Gumbel-max.
    device const float * ZTK = A + ulong(desc.target_off) + ulong(desc.k) * ulong(a.target_stride);
    float best = -INFINITY;
    int best_i = 0x7fffffff;
    uint bad = 0u;
    for (uint v = tid; v < n; v += 1024u) {
        const float rt = ZTK[v];
        if (isnan(rt) || isinf(rt)) { bad = 1u; continue; }
        if (dspark_banned(desc, v)) continue;
        const float st = dspark_softcap(rt, a.target_softcap) * inv_temp;
        const float uv = dspark_uniform(v ^ 0x9e3779b9u, desc.base_pos + desc.k, desc.seed_lo, desc.seed_hi);
        const float g = st - precise::log(-precise::log(uv));
        if (g > best || (g == best && int(v) < best_i)) { best = g; best_i = int(v); }
    }
    const uint sbad = simd_or(bad);
    if (lane == 0) bu[sg] = sbad;
    dspark_argmax_reduce(best, best_i, sg, lane, bv, bi, chosen_tok, chosen_val, n);
    if (sg == 0) {
        const uint gbad = simd_or(bu[lane]);
        if (lane == 0) sh_u[0] = (gbad != 0u || chosen_val == -INFINITY) ? 1u : 0u;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (sh_u[0] != 0u) {
        if (tid == 0) { OUT[desc.out_off] = 1u; OUT[desc.out_off + 1] = 0u; }
        return;
    }
    if (tid == 0) {
        OUT[desc.out_off + 0u] = 0u;
        OUT[desc.out_off + 1u] = desc.k;
        OUT[desc.out_off + 2u + desc.k] = chosen_tok;
    }
}
#pragma clang fp contract(off) reassociate(off)

// ---------------------------------------------------------------------------------------------
// Dynamic WHT-2bit-Sketch Top-K Sparse Full-Attention Paging + Pinned Anchors (`--sparse-topk`).
// Each 64-token `BlockKind::Full` slot has `8` passes x `8` KV heads x `272 B` = `17,408 B`
// (`Wht2HeadSketch`: `8 x 8`-token sub-blocks in WHT-128 + Rademacher 2-bit Lloyd-Max coordinates).

#define WHT2_NSUB 8u
#define WHT2_SUB_TOKS 8u
#define SPARSE_MAX_BLKS 32768u
#define SPARSE_WIDE_CAND_CAP 4352u
#define SPARSE_4K_MAX_BLKS 4096u
#define SPARSE_4K_MASK_WORDS 128u
#define SPARSE_1K_MAX_BLKS 1024u
#define SPARSE_1K_MASK_WORDS 32u

constant float WHT2_LM2_VAL[4] = {
    -1.5104176f, -0.45278004f, 0.45278004f, 1.5104176f
};

struct Wht2HeadSketch {
    uint k_sk[WHT2_NSUB][8];
    half sc_sk[WHT2_NSUB];
};

inline float sparse_rademacher_sign(uint pass_idx, uint g, uint d) {
    uint h = (pass_idx * 2654435761u) ^ (g * 2246822519u) ^ (d * 3266489917u);
    h ^= h >> 16;
    h *= 0x85ebca6bu;
    h ^= h >> 13;
    return (h & 1u) ? -1.0f : 1.0f;
}

inline float sparse_wht128_tg(float x, ushort tid, ushort sg, ushort lane, threadgroup float * sh) {
    float o;
    o = simd_shuffle_xor(x, 1);  x = (lane & 1)  ? (o - x) : (x + o);
    o = simd_shuffle_xor(x, 2);  x = (lane & 2)  ? (o - x) : (x + o);
    o = simd_shuffle_xor(x, 4);  x = (lane & 4)  ? (o - x) : (x + o);
    o = simd_shuffle_xor(x, 8);  x = (lane & 8)  ? (o - x) : (x + o);
    o = simd_shuffle_xor(x, 16); x = (lane & 16) ? (o - x) : (x + o);
    sh[tid] = x;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    const float a0 = sh[lane];
    const float a1 = sh[32u + lane];
    const float a2 = sh[64u + lane];
    const float a3 = sh[96u + lane];
    const float b0 = a0 + a1, b1 = a0 - a1, b2 = a2 + a3, b3 = a2 - a3;
    float r;
    if (sg == 0)      r = b0 + b2;
    else if (sg == 1) r = b1 + b3;
    else if (sg == 2) r = b0 - b2;
    else              r = b1 - b3;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    return r * 0.08838834764831845f;
}

inline uint sparse_float_to_ord(float x) {
    const uint raw = as_type<uint>(x);
    if ((raw & 0x7fffffffu) > 0x7f800000u) return 0u;
    if (x == 0.0f) return 0x80000000u;
    return (raw & 0x80000000u) ? ~raw : (raw ^ 0x80000000u);
}

inline uint sparse_bt_pool_index(ulong entry, uint slots_per_slab) {
    const uint si = uint(entry >> 62);
    const uint within = uint((entry & KV_SLAB_MASK) / (8UL * KV_PASS_BYTES));
    return si * slots_per_slab + within;
}

inline void sparse_build_subblock_wht2(
    device const kv_t * k_head_base,
    uint pass_idx,
    uint g,
    uint sb,
    uint t0,
    uint t1,
    device Wht2HeadSketch * dst,
    ushort tid,
    ushort sg,
    ushort lane,
    threadgroup float * wht_sh,
    threadgroup float * red4
) {
    #pragma clang fp contract(off) reassociate(off)
    if (t1 > t0) {
        float sbs = 0.0f;
        for (uint t = t0; t < t1; t++) {
            device const kv_t * krow = k_head_base + ulong(t) * ulong(KV_ROW_STEP);
#ifdef KV4
            const uchar qb = krow->qs[tid >> 1];
            const uint nib = (tid & 1u) ? uint(qb >> 4) : uint(qb & 0xFu);
            sbs += LM4_VAL[nib] * kv4_finite_or_zero(float(krow->sc));
#elif defined(KV8)
            sbs += float(krow[tid]) * kv_vscale(krow);
#else
            sbs += float(krow[tid]);
#endif
        }
        const float sb_mean = sbs * (1.0f / float(t1 - t0));
#ifdef KV4
        (void) pass_idx; (void) g; (void) wht_sh;
        const float k_rot = sb_mean;
#else
        const float k_rot = sparse_wht128_tg(sparse_rademacher_sign(pass_idx, g, tid) * sb_mean, tid, sg, lane, wht_sh);
#endif
        float ss = k_rot * k_rot;
        ss += simd_shuffle_xor(ss, 1);
        ss += simd_shuffle_xor(ss, 2);
        ss += simd_shuffle_xor(ss, 4);
        ss += simd_shuffle_xor(ss, 8);
        ss += simd_shuffle_xor(ss, 16);
        if (lane == 0) red4[sg] = ss;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const float tot_ss = ((red4[0] + red4[1]) + red4[2]) + red4[3];
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const float rms = precise::sqrt(tot_ss * (1.0f / 128.0f));
        const half rms_h = half(rms);
        if (float(rms_h) > 0.0f) {
            const float u = k_rot / rms;
            const uint q = (u >= -0.9815988f ? 1u : 0u) + (u >= 0.0f ? 1u : 0u) + (u >= 0.9815988f ? 1u : 0u);
            uint w = q << ((tid & 15u) * 2u);
            w |= simd_shuffle_xor(w, 1);
            w |= simd_shuffle_xor(w, 2);
            w |= simd_shuffle_xor(w, 4);
            w |= simd_shuffle_xor(w, 8);
            if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = w;
            if (tid == 0) dst->sc_sk[sb] = rms_h;
        } else {
            if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = 0u;
            if (tid == 0) dst->sc_sk[sb] = half(0.0h);
        }
    } else {
        if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = 0u;
        if (tid == 0) dst->sc_sk[sb] = half(0.0h);
    }
}

struct BuildSketchBlkArgs {
    uint pass_idx, slots_per_slab, lo_blk, n_blks;
    uint end_pos, pad0, pad1, pad2;
};

// Layer 3 prefill range sketch builder (`grid = (n_blks, NKV, 1)`, 128 threads/TG).
kernel void k_build_full_sketch_blk(
    device uchar * KV0 [[buffer(3)]],
    constant BuildSketchBlkArgs & a [[buffer(5)]],
    device const ulong * BT [[buffer(8)]],
    device uchar * KV1 [[buffer(10)]],
    device uchar * KV2 [[buffer(11)]],
    device uchar * KV3 [[buffer(12)]],
    device Wht2HeadSketch * SKETCH [[buffer(13)]],
    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 wht_sh[128];
    threadgroup float red4[4];
    const uint bi = tgp.x, g = tgp.y;
    if (bi >= a.n_blks) return;
    const uint blk = a.lo_blk + bi;
    const ulong entry = BT[blk];
    if (entry == KV_CLEARED_ENTRY) return;
    const uint pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    device const kv_t * k_base = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
    const uint blk_start = blk * KV_BLK;
    const uint valid_toks = (a.end_pos > blk_start) ? min(uint(KV_BLK), a.end_pos - blk_start) : 0u;
    device Wht2HeadSketch * dst = SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
    for (uint sb = 0u; sb < WHT2_NSUB; sb++) {
        const uint t0 = sb * WHT2_SUB_TOKS;
        const uint t1 = min(t0 + WHT2_SUB_TOKS, valid_toks);
        sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
    }
}

struct BuildSketchSlotsArgs {
    uint n_slots, slots_per_slab, pad0, pad1;
};

// Layer 3 dirty-slot catch-up sketch builder (`grid = (n_slots, NKV, 8)`, 128 threads/TG).
// Rebuilds all 8 full passes in one launch for SSD-restored or pre-existing unsketched `Full` slots.
kernel void k_build_full_sketch_slots(
    device uchar * KV0 [[buffer(3)]],
    constant BuildSketchSlotsArgs & a [[buffer(5)]],
    device uchar * KV1 [[buffer(10)]],
    device uchar * KV2 [[buffer(11)]],
    device uchar * KV3 [[buffer(12)]],
    device Wht2HeadSketch * SKETCH [[buffer(13)]],
    device const uint2 * SLOTS [[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]]
) {
    threadgroup float wht_sh[128];
    threadgroup float red4[4];
    const uint idx = tgp.x, g = tgp.y, pass_idx = tgp.z;
    if (idx >= a.n_slots || pass_idx >= 8u) return;
    const uint2 spec = SLOTS[idx];
    const uint pool_idx = spec.x;
    const uint valid_toks = min(spec.y, uint(KV_BLK));
    const uint si = pool_idx / a.slots_per_slab;
    const ulong slot_off = ulong(pool_idx % a.slots_per_slab) * (8UL * KV_PASS_BYTES);
    const ulong koff = ulong(pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    device uchar * base = (si == 0u) ? KV0 : (si == 1u ? KV1 : (si == 2u ? KV2 : KV3));
    device const kv_t * k_base = (device const kv_t *) (base + slot_off + koff);
    device Wht2HeadSketch * dst = SKETCH + ((ulong(pool_idx) * 8ul + ulong(pass_idx)) * ulong(NKV) + ulong(g));
    for (uint sb = 0u; sb < WHT2_NSUB; sb++) {
        const uint t0 = sb * WHT2_SUB_TOKS;
        const uint t1 = min(t0 + WHT2_SUB_TOKS, valid_toks);
        sparse_build_subblock_wht2(k_base, pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
    }
}

struct UpdateSketchDecArgs {
    uint desc_off, pass_idx, slots_per_slab, nspans;
};

// Layer 3 decode single-subblock sketch updater (`grid = (NKV, nspans, 1)`, 128 threads/TG).
kernel void k_update_full_sketch_dec(
    device const float * A [[buffer(2)]],
    device uchar * KV0 [[buffer(3)]],
    constant UpdateSketchDecArgs & 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 Wht2HeadSketch * SKETCH [[buffer(13)]],
    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 wht_sh[128];
    threadgroup float red4[4];
    const uint g = tgp.x, si = tgp.y;
    if (si >= a.nspans) return;
    device const DecodeSpanDesc & d = ((device const DecodeSpanDesc *) (A + a.desc_off))[si];
    const uint pos = d.pos;
    const uint blk = pos >> 6;
    const uint ib = pos & KV_BLK_MASK;
    device const ulong * BT = BT_ALL + d.bt_full_base;
    const ulong entry = BT[blk];
    if (entry == KV_CLEARED_ENTRY) return;
    const uint pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
    const ulong koff = ulong(a.pass_idx) * KV_PASS_BYTES + ulong(g) * KV_HEAD_BYTES;
    device const kv_t * k_base = kv_blk_ptr(KV0, KV1, KV2, KV3, BT, blk, koff);
    device Wht2HeadSketch * dst = SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
    const uint sb = ib >> 3;
    const uint t0 = sb * WHT2_SUB_TOKS;
    const uint t1 = ib + 1u;
    sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
    if (ib == 0u) {
        for (uint rem = 1u; rem < WHT2_NSUB; rem++) {
            if ((tid & 15u) == 0u) dst->k_sk[rem][tid >> 4] = 0u;
            if (tid == 0) dst->sc_sk[rem] = half(0.0h);
        }
    }
}

struct BuildSketchL2Args {
    uint pass_idx, cap, lo_blk, n_blks;
    uint end_pos, single_sb_pos, use_single_sb, pad0;
};

// Layer 2 (`lane.kv_full`) sketch builder for prefill & decode (`grid = (n_blks, NKV, 1)`, 128 threads/TG).
kernel void k_build_full_sketch_l2(
    device const kv_t * KV [[buffer(3)]],
    constant BuildSketchL2Args & a [[buffer(5)]],
    device Wht2HeadSketch * SKETCH [[buffer(13)]],
    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 wht_sh[128];
    threadgroup float red4[4];
    const uint bi = tgp.x, g = tgp.y;
    if (bi >= a.n_blks) return;
    const uint blk = a.lo_blk + bi;
    const uint blk_start = blk * KV_BLK;
    const ulong head_off = ((ulong(a.pass_idx) * 2ul + 0ul) * ulong(NKV) + ulong(g)) * ulong(a.cap) * ulong(KV_ROW_STEP)
                         + ulong(blk_start) * ulong(KV_ROW_STEP);
    device const kv_t * k_base = KV + head_off;
    device Wht2HeadSketch * dst = SKETCH + ((ulong(blk) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
    if (a.use_single_sb != 0u) {
        const uint ib = a.single_sb_pos & KV_BLK_MASK;
        const uint sb = ib >> 3;
        sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, sb * WHT2_SUB_TOKS, ib + 1u, dst, tid, sg, lane, wht_sh, red4);
        if (ib == 0u) {
            for (uint rem = 1u; rem < WHT2_NSUB; rem++) {
                if ((tid & 15u) == 0u) dst->k_sk[rem][tid >> 4] = 0u;
                if (tid == 0) dst->sc_sk[rem] = half(0.0h);
            }
        }
        return;
    }
    const uint valid_toks = (a.end_pos > blk_start) ? min(uint(KV_BLK), a.end_pos - blk_start) : 0u;
    for (uint sb = 0u; sb < WHT2_NSUB; sb++) {
        const uint t0 = sb * WHT2_SUB_TOKS;
        const uint t1 = min(t0 + WHT2_SUB_TOKS, valid_toks);
        sparse_build_subblock_wht2(k_base, a.pass_idx, g, sb, t0, t1, dst, tid, sg, lane, wht_sh, red4);
    }
}

struct KvPrepL2DecArgs {
    uint pos, cap, k_base, v_base;
    uint cs_off, q_off, k_off, v_off;
    uint r_off, qp_off, rp_off, kv_cur_off;
    int  kdyn_off, vdyn_off;
    uint kconv_w, vconv_w;
    uint qclip_w, relclip_w, pass_idx, flags; // flags: bit 0 = half_io, bit 1 = dry, bit 2 = update_sketch, bits 8..15 = KV4 slot
    float tau, log_alpha, log_floor;
    uint sink_off;
};

// Layer 2 single-span K/V short-conv + Q/R clip + KV write + optional active sub-block sketch update
// (`grid = (NKV, 1, 1)`, 128 threads/TG). Exact arithmetic mirror of `k_attn` phase 1.
kernel void k_kvprep_l2_dec(
    device const uchar * PB [[buffer(1)]],
    device float * A [[buffer(2)]],
    device kv_t * KV [[buffer(3)]],
    device float * CS [[buffer(4)]],
    constant KvPrepL2DecArgs & a [[buffer(5)]],
    device Wht2HeadSketch * SKETCH [[buffer(13)]],
    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];
    threadgroup float wht_sh[128];
    threadgroup float red4[4];
    const uint g = tgp.x;
    const bool half_io = (a.flags & 1u) != 0u;
    const bool dry = (a.flags & 2u) != 0u;
    const bool update_sketch = (a.flags & 4u) != 0u;
    const float tau = half_io
        ? (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 * 3 + 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;
    {
        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 = 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 = 0.0f;
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        r = A[a.r_off + 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(kx * kx), s4 = simd_sum(vx * vx);
        const float s5 = simd_max(fabs(kx)), s6 = simd_max(fabs(vx));
        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
    const uint slot = (a.flags >> 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]));
    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 = half_io ? float(half(qr)) : qr;
        if (half_io) ((device half *) (A + a.qp_off))[H * HD + tid] = half(qr);
        else A[a.qp_off + 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 + H] -= dc_b;
    }
#else
    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 qv = q[h] * f;
        if (half_io) ((device half *) (A + a.qp_off))[H * HD + tid] = half(qv);
        else A[a.qp_off + H * HD + tid] = qv;
    }
#endif
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        A[a.rp_off + H * NREL + i] = 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);
    const float vf = rsqrt(tot[4] / HD + 1e-6f);
    const float k = kx * kf, v = vx * vf;
    const ulong gstr = ulong(a.cap) * ulong(KV_ROW_STEP);
    const ulong row_off = ulong(g) * gstr + ulong(a.pos) * ulong(KV_ROW_STEP);
    const uint kc_off = a.kv_cur_off + g * HD;
    const uint vc_off = a.kv_cur_off + NKV * HD + g * HD;
    float k_stored_cur;
#ifdef KV4
    const float k_rot_val = wht128_tg(sk_rad * k, tid, sg, lane, wht_sh) - mu_r;
    const float v_rot_val = wht128_tg(sv_rad * v, tid, sg, lane, wht_sh);
    device kv_t * kp = dry ? (device kv_t *) nullptr : (KV + ulong(a.k_base) + row_off);
    device kv_t * vp = dry ? (device kv_t *) nullptr : (KV + ulong(a.v_base) + row_off);
    k_stored_cur = kv4_pack_row(k_rot_val, tid, sg, lane, wht_sh, kp, !dry);
    A[kc_off + tid] = k_stored_cur;
    A[vc_off + tid] = kv4_pack_row(v_rot_val, tid, sg, lane, wht_sh, vp, !dry);
#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);
    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);
    k_stored_cur = qk * sk;
    A[kc_off + tid] = k_stored_cur;
    A[vc_off + tid] = qv * sv;
    if (!dry) {
        KV[ulong(a.k_base) + row_off + tid] = (kv_t) (int) qk;
        KV[ulong(a.v_base) + row_off + tid] = (kv_t) (int) qv;
    }
#else
    k_stored_cur = float(half(k));
    A[kc_off + tid] = half_io ? k_stored_cur : k;
    A[vc_off + tid] = half_io ? float(half(v)) : v;
    if (!dry) {
        KV[ulong(a.k_base) + row_off + tid] = half(k);
        KV[ulong(a.v_base) + row_off + tid] = half(v);
    }
#endif

    if (!dry && update_sketch) {
        const uint blk = a.pos >> 6;
        const uint ib = a.pos & KV_BLK_MASK;
        const uint sb = ib >> 3;
        const uint t0 = sb * WHT2_SUB_TOKS;
        device const kv_t * k_blk_base = KV + ulong(a.k_base) + ulong(g) * gstr + ulong(blk * KV_BLK) * ulong(KV_ROW_STEP);
        float sbs = 0.0f;
        for (uint t = t0; t <= ib; t++) {
            if (t == ib) {
                sbs += k_stored_cur;
            } else {
                device const kv_t * krow = k_blk_base + ulong(t) * ulong(KV_ROW_STEP);
#ifdef KV4
                const uchar qb = krow->qs[tid >> 1];
                const uint nib = (tid & 1u) ? uint(qb >> 4) : uint(qb & 0xFu);
                sbs += LM4_VAL[nib] * kv4_finite_or_zero(float(krow->sc));
#elif defined(KV8)
                sbs += float(krow[tid]) * kv_vscale(krow);
#else
                sbs += float(krow[tid]);
#endif
            }
        }
        const float sb_mean = sbs / float((ib + 1u) - t0);
#ifdef KV4
        const float k_rot = sb_mean;
#else
        const float k_rot = sparse_wht128_tg(sparse_rademacher_sign(a.pass_idx, g, tid) * sb_mean, tid, sg, lane, wht_sh);
#endif
        float ss = k_rot * k_rot;
        ss += simd_shuffle_xor(ss, 1);
        ss += simd_shuffle_xor(ss, 2);
        ss += simd_shuffle_xor(ss, 4);
        ss += simd_shuffle_xor(ss, 8);
        ss += simd_shuffle_xor(ss, 16);
        if (lane == 0) red4[sg] = ss;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const float tot_ss = (red4[0] + red4[1]) + (red4[2] + red4[3]);
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const float rms = sqrt(tot_ss * (1.0f / 128.0f));
        const half rms_h = half(rms);
        device Wht2HeadSketch * dst = SKETCH + ((ulong(blk) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
        if (float(rms_h) > 0.0f) {
            const float u = k_rot / rms;
            const uint qc = (u >= -0.9815988f ? 1u : 0u) + (u >= 0.0f ? 1u : 0u) + (u >= 0.9815988f ? 1u : 0u);
            uint w = qc << ((tid & 15u) * 2u);
            w |= simd_shuffle_xor(w, 1);
            w |= simd_shuffle_xor(w, 2);
            w |= simd_shuffle_xor(w, 4);
            w |= simd_shuffle_xor(w, 8);
            if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = w;
            if (tid == 0) dst->sc_sk[sb] = rms_h;
        } else {
            if ((tid & 15u) == 0u) dst->k_sk[sb][tid >> 4] = 0u;
            if (tid == 0) dst->sc_sk[sb] = half(0.0h);
        }
        if (ib == 0u) {
            for (uint rem = 1u; rem < WHT2_NSUB; rem++) {
                if ((tid & 15u) == 0u) dst->k_sk[rem][tid >> 4] = 0u;
                if (tid == 0) dst->sc_sk[rem] = half(0.0h);
            }
        }
    }
}

// Per-lane sparse decode descriptor (80 bytes, mirrors Rust `SparseDecTask`).
struct SparseDecTask {
    uint span_idx;
    uint pos;
    uint bt_full_base;
    uint anchor_blks;
    uint far_start_blk;
    uint n_far_blks;
    uint recent_start_blk;
    uint total_blks;
    uint top_k;
    uint total_sel_blks;
    uint blks_per_split;
    uint nsplit;
    uint sel_out_base;
    uint qp_off;
    uint rp_off;
    uint sink_off;
    uint kv_cur_off;
    uint part_off;
    uint kv_cap;
    uint flags; // bit 0: half_io, bit 1: cur_from_buf
};

struct ScoreFullSketchArgs {
    uint pass_idx, slots_per_slab, n_tasks, is_paged;
    uint tasks_u32_off, sel_u32_base, pass_sel_stride, pad0;
};

// Shared WHT-2bit-sketch scorer + exact 4-pass radix Top-K + pinned anchors & recent + sorted compaction.
template <uint MAX_BLKS, uint MASK_WORDS>
inline void score_full_sketch_dec_impl(
    device const float * A,
    constant ScoreFullSketchArgs & a,
    device const ulong * BT_ALL,
    device const Wht2HeadSketch * SKETCH,
    device uint * SPARSE_BUF,
    threadgroup float4 (*qs4)[HD / 4],
#ifndef KV4
    threadgroup float * wht_sh,
#endif
    threadgroup uint * sc_ord,
    threadgroup atomic_uint * hist,
    threadgroup atomic_uint * sel_mask,
    threadgroup uint * pop_scan,
    threadgroup uint & g_cut_prefix,
    threadgroup uint & g_cut_rem,
    uint2 tgp,
    ushort tid,
    ushort sg,
    ushort lane
) {
    const uint g = tgp.x, u_task = tgp.y;
    if (u_task >= a.n_tasks) return;
    device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
    const bool half_io = (task.flags & 1u) != 0u;

    if (tid < MASK_WORDS) {
        atomic_store_explicit(&sel_mask[tid], 0u, memory_order_relaxed);
    }

#ifdef KV4
    // Under `--kv4`, `k_kvprep_dec` / `k_kvprep_l2_dec` already rotated `qp = WHT-128(D_K * q)`
    // and folded `-<qp, mu_rot>` into `A[task.sink_off]`: zero extra WHT butterfly needed!
    if (tid < 128u) {
        for (uint h = 0u; h < 3u; h++) {
            const uint H = g * 3u + h;
            const float qv = half_io
                ? float(((device const half *) (A + task.qp_off))[H * HD + tid])
                : A[task.qp_off + H * HD + tid];
            ((threadgroup float *) qs4[h])[tid] = qv;
        }
    }
#else
    // Rotate 3 query heads `3g..3g+2` with WHT-128(D * qp) using 256-thread uniform barriers.
    {
        const ushort half_id = tid >> 7;
        const ushort ltid = tid & 127u;
        const ushort lsg = sg & 3u;
        const uint H = g * 3u + uint(half_id);
        const float qv = half_io
            ? float(((device const half *) (A + task.qp_off))[H * HD + ltid])
            : A[task.qp_off + H * HD + ltid];
        float x = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv;
        float o;
        o = simd_shuffle_xor(x, 1);  x = (lane & 1)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 2);  x = (lane & 2)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 4);  x = (lane & 4)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 8);  x = (lane & 8)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 16); x = (lane & 16) ? (o - x) : (x + o);
        wht_sh[tid] = x;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const ushort base = half_id * 128u;
        const float a0 = wht_sh[base + lane], a1 = wht_sh[base + 32u + lane];
        const float a2 = wht_sh[base + 64u + lane], a3 = wht_sh[base + 96u + lane];
        const float b0 = a0 + a1, b1 = a0 - a1, b2 = a2 + a3, b3 = a2 - a3;
        float r = (lsg == 0) ? (b0 + b2) : (lsg == 1 ? (b1 + b3) : (lsg == 2 ? (b0 - b2) : (b1 - b3)));
        ((threadgroup float *) qs4[half_id])[ltid] = r * 0.08838834764831845f;
        threadgroup_barrier(mem_flags::mem_threadgroup);

        float x2 = 0.0f;
        if (half_id == 0u) {
            const uint H2 = g * 3u + 2u;
            const float qv2 = half_io
                ? float(((device const half *) (A + task.qp_off))[H2 * HD + ltid])
                : A[task.qp_off + H2 * HD + ltid];
            x2 = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv2;
        }
        o = simd_shuffle_xor(x2, 1);  x2 = (lane & 1)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 2);  x2 = (lane & 2)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 4);  x2 = (lane & 4)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 8);  x2 = (lane & 8)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 16); x2 = (lane & 16) ? (o - x2) : (x2 + o);
        wht_sh[tid] = x2;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (half_id == 0u) {
            const float c0 = wht_sh[lane], c1 = wht_sh[32u + lane], c2 = wht_sh[64u + lane], c3 = wht_sh[96u + lane];
            const float d0 = c0 + c1, d1 = c0 - c1, d2 = c2 + c3, d3 = c2 - c3;
            float r2 = (lsg == 0) ? (d0 + d2) : (lsg == 1 ? (d1 + d3) : (lsg == 2 ? (d0 - d2) : (d1 - d3)));
            ((threadgroup float *) qs4[2])[ltid] = r2 * 0.08838834764831845f;
        }
    }
#endif

    float sink[3];
    for (int h = 0; h < 3; h++) sink[h] = A[task.sink_off + g * 3u + uint(h)];

    const uint capped_total_blks = min(task.total_blks, MAX_BLKS);
    const uint capped_anchor_blks = min(task.anchor_blks, capped_total_blks);
    const uint capped_recent_start = min(task.recent_start_blk, capped_total_blks);
    const uint capped_far_start = min(task.far_start_blk, capped_recent_start);

    // Pin anchor blocks `[0 .. capped_anchor_blks)` and recent blocks `[capped_recent_start .. capped_total_blks)`.
    for (uint b = tid; b < capped_anchor_blks; b += 256u) {
        atomic_fetch_or_explicit(&sel_mask[b >> 5], 1u << (b & 31u), memory_order_relaxed);
    }
    for (uint b = capped_recent_start + tid; b < capped_total_blks; b += 256u) {
        atomic_fetch_or_explicit(&sel_mask[b >> 5], 1u << (b & 31u), memory_order_relaxed);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Score candidate far blocks `[capped_far_start .. capped_far_start + nfar)`:
    // 32 lanes = 8 sub-blocks (`sb = lane >> 2`) x 4 quarters of 32 dims (`pp = lane & 3`).
    const uint nfar = min(task.n_far_blks, capped_recent_start - capped_far_start);
    const uint K_ret = min(task.top_k, nfar);
    const ushort sb = lane >> 2;
    const ushort pp = lane & 3u;
    device const ulong * BT = (a.is_paged != 0u) ? (BT_ALL + task.bt_full_base) : nullptr;

    for (uint p = sg; p < nfar; p += 8u) {
        const uint blk = capped_far_start + p;
        uint pool_idx = blk;
        bool blk_ok = true;
        if (a.is_paged != 0u) {
            const ulong entry = BT[blk];
            if (entry == KV_CLEARED_ENTRY) blk_ok = false;
            else pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
        }
        float best_s = -1.0e30f;
        if (blk_ok) {
            device const Wht2HeadSketch * sm = SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
            const float sc = float(sm->sc_sk[sb]);
            const uint2 w2 = *(device const uint2 *) (sm->k_sk[sb] + pp * 2u);
            float acc[3] = {0.0f, 0.0f, 0.0f};
            if (sc > 0.0f) {
                #pragma unroll
                for (int i = 0; i < 2; i++) {
                    const uint u = w2[i];
                    const float4 k0 = float4(WHT2_LM2_VAL[u & 3u], WHT2_LM2_VAL[(u >> 2) & 3u], WHT2_LM2_VAL[(u >> 4) & 3u], WHT2_LM2_VAL[(u >> 6) & 3u]);
                    const float4 k1 = float4(WHT2_LM2_VAL[(u >> 8) & 3u], WHT2_LM2_VAL[(u >> 10) & 3u], WHT2_LM2_VAL[(u >> 12) & 3u], WHT2_LM2_VAL[(u >> 14) & 3u]);
                    const float4 k2 = float4(WHT2_LM2_VAL[(u >> 16) & 3u], WHT2_LM2_VAL[(u >> 18) & 3u], WHT2_LM2_VAL[(u >> 20) & 3u], WHT2_LM2_VAL[(u >> 22) & 3u]);
                    const float4 k3 = float4(WHT2_LM2_VAL[(u >> 24) & 3u], WHT2_LM2_VAL[(u >> 26) & 3u], WHT2_LM2_VAL[(u >> 28) & 3u], WHT2_LM2_VAL[(u >> 30) & 3u]);
                    for (int h = 0; h < 3; h++) {
                        acc[h] += dot(qs4[h][pp * 8 + i * 4 + 0], k0) + dot(qs4[h][pp * 8 + i * 4 + 1], k1)
                                + dot(qs4[h][pp * 8 + i * 4 + 2], k2) + dot(qs4[h][pp * 8 + i * 4 + 3], k3);
                    }
                }
            }
            for (int h = 0; h < 3; h++) {
                float s = acc[h];
                s += simd_shuffle_xor(s, 1);
                s += simd_shuffle_xor(s, 2);
                if (sc > 0.0f) best_s = max(best_s, s * sc - sink[h]);
            }
        }
        const float page_s = simd_max(best_s);
        if (lane == 0) sc_ord[p] = sparse_float_to_ord(page_s);
    }

    if (tid == 0) {
        g_cut_prefix = 0u;
        g_cut_rem = K_ret;
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Exact 4-pass 8-bit radix Top-K selection over `sc_ord[0..nfar]`, followed by deterministic ascending tie-break.
    if (K_ret > 0u && nfar > 0u) {
        for (int rpass = 0; rpass < 4; rpass++) {
            const uint shift = uint((3 - rpass) * 8);
            const uint mask_shift = (rpass == 0) ? 0u : uint((4 - rpass) * 8);
            const uint prefix = g_cut_prefix;
            atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed);
            threadgroup_barrier(mem_flags::mem_threadgroup);
            for (uint p = tid; p < nfar; p += 256u) {
                const uint u = sc_ord[p];
                if (rpass == 0 || (u >> mask_shift) == prefix) {
                    atomic_fetch_add_explicit(&hist[(u >> shift) & 255u], 1u, memory_order_relaxed);
                }
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);
            if (tid == 0) {
                uint acc = 0u, chosen = 0u;
                const uint target = g_cut_rem;
                for (int bi = 255; bi >= 0; bi--) {
                    const uint c = atomic_load_explicit(&hist[bi], memory_order_relaxed);
                    if (acc + c >= target) { chosen = uint(bi); break; }
                    acc += c;
                }
                g_cut_prefix = (prefix << 8) | chosen;
                g_cut_rem = target - acc;
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);
        }

        const uint thresh32 = g_cut_prefix;
        uint rem_ties = g_cut_rem;
        for (uint p = tid; p < nfar; p += 256u) {
            if (sc_ord[p] > thresh32) {
                const uint blk = capped_far_start + p;
                atomic_fetch_or_explicit(&sel_mask[blk >> 5], 1u << (blk & 31u), memory_order_relaxed);
            }
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);

        for (uint base_p = 0u; base_p < nfar && rem_ties > 0u; base_p += 256u) {
            const uint p = base_p + tid;
            const uint is_tie = (p < nfar && sc_ord[p] == thresh32) ? 1u : 0u;
            const uint sg_excl = simd_prefix_exclusive_sum(is_tie);
            const uint sg_tot = simd_sum(is_tie);
            if (lane == 0) pop_scan[sg] = sg_tot;
            threadgroup_barrier(mem_flags::mem_threadgroup);
            uint sg_base = 0u;
            for (ushort s = 0; s < sg; s++) sg_base += pop_scan[s];
            if (is_tie != 0u && (sg_base + sg_excl) < rem_ties) {
                const uint blk = capped_far_start + p;
                atomic_fetch_or_explicit(&sel_mask[blk >> 5], 1u << (blk & 31u), memory_order_relaxed);
            }
            const uint stripe_sum = pop_scan[0] + pop_scan[1] + pop_scan[2] + pop_scan[3]
                                  + pop_scan[4] + pop_scan[5] + pop_scan[6] + pop_scan[7];
            rem_ties = (stripe_sum >= rem_ties) ? 0u : (rem_ties - stripe_sum);
            threadgroup_barrier(mem_flags::mem_threadgroup);
        }
    }

    // Compact `sel_mask` into `SPARSE_BUF` in strictly ascending block-index order.
    const uint n_words = min((capped_total_blks + 31u) >> 5, MASK_WORDS);
    uint word = 0u;
    uint cnt = 0u;
    if (tid < n_words) {
        word = atomic_load_explicit(&sel_mask[tid], memory_order_relaxed);
        cnt = popcount(word);
    }
    const uint sg_excl = simd_prefix_exclusive_sum(cnt);
    const uint sg_tot = simd_sum(cnt);
    if (lane == 0) pop_scan[sg] = sg_tot;
    threadgroup_barrier(mem_flags::mem_threadgroup);
    if (tid < n_words && word != 0u) {
        uint out_idx = sg_excl;
        for (ushort s = 0; s < sg; s++) out_idx += pop_scan[s];
        device uint * sel_out = 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);
        uint w = word;
        while (w != 0u) {
            const uint bit = ctz(w);
            if (out_idx < task.total_sel_blks) {
                sel_out[out_idx] = (uint(tid) << 5) + bit;
            }
            out_idx++;
            w &= (w - 1u);
        }
    }
}

// Fast 4K-block (`<= 256K` ctx) WHT-2bit-sketch scorer + radix Top-K.
// Grid: (NKV, n_tasks, 1), TG = 256 threads (8 simdgroups).
kernel void k_score_full_sketch_dec(
    device const float * A [[buffer(2)]],
    constant ScoreFullSketchArgs & a [[buffer(5)]],
    device const ulong * BT_ALL [[buffer(8)]],
    device const Wht2HeadSketch * SKETCH [[buffer(13)]],
    device uint * SPARSE_BUF [[buffer(14)]],
    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 float4 qs4[3][HD / 4];
#ifndef KV4
    threadgroup float  wht_sh[256];
#endif
    threadgroup uint   sc_ord[SPARSE_4K_MAX_BLKS];
    threadgroup atomic_uint hist[256];
    threadgroup atomic_uint sel_mask[SPARSE_4K_MASK_WORDS];
    threadgroup uint   pop_scan[8];
    threadgroup uint   g_cut_prefix;
    threadgroup uint   g_cut_rem;

    score_full_sketch_dec_impl<SPARSE_4K_MAX_BLKS, SPARSE_4K_MASK_WORDS>(
        A, a, BT_ALL, SKETCH, SPARSE_BUF, qs4,
#ifndef KV4
        wht_sh,
#endif
        sc_ord, hist, sel_mask, pop_scan, g_cut_prefix, g_cut_rem, tgp, tid, sg, lane
    );
}

// Ultra-long-context (`> 256K` up to `2M` tokens = `32,768` 64-token blocks) WHT-2bit-sketch scorer
// using a single-pass chunked SRAM Top-K tournament (`SPARSE_WIDE_CAND_CAP = 4,352` `(ord, blk)` pairs in <= 29 KB TG SRAM,
// zero extra global scratch buffers, 100% bit-identical block selection & ascending tie-breaking to `select_sparse_topk_cpu`).
// Grid: (NKV, n_tasks, 1), TG = 256 threads (8 simdgroups).
kernel void k_score_full_sketch_dec_wide(
    device const float * A [[buffer(2)]],
    constant ScoreFullSketchArgs & a [[buffer(5)]],
    device const ulong * BT_ALL [[buffer(8)]],
    device const Wht2HeadSketch * SKETCH [[buffer(13)]],
    device uint * SPARSE_BUF [[buffer(14)]],
    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 float4 qs4[3][HD / 4];
#ifndef KV4
    threadgroup float  wht_sh[256];
#endif
    threadgroup uint   cand_ord[SPARSE_WIDE_CAND_CAP];
    threadgroup ushort cand_blk[SPARSE_WIDE_CAND_CAP];
    threadgroup atomic_uint hist[256];
    threadgroup uint   pop_scan[8];
    threadgroup uint   g_cut_prefix;
    threadgroup uint   g_cut_rem;

    const uint g = tgp.x, u_task = tgp.y;
    if (u_task >= a.n_tasks) return;
    device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
    const bool half_io = (task.flags & 1u) != 0u;

#ifdef KV4
    if (tid < 128u) {
        for (uint h = 0u; h < 3u; h++) {
            const uint H = g * 3u + h;
            const float qv = half_io
                ? float(((device const half *) (A + task.qp_off))[H * HD + tid])
                : A[task.qp_off + H * HD + tid];
            ((threadgroup float *) qs4[h])[tid] = qv;
        }
    }
#else
    {
        const ushort half_id = tid >> 7;
        const ushort ltid = tid & 127u;
        const ushort lsg = sg & 3u;
        const uint H = g * 3u + uint(half_id);
        const float qv = half_io
            ? float(((device const half *) (A + task.qp_off))[H * HD + ltid])
            : A[task.qp_off + H * HD + ltid];
        float x = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv;
        float o;
        o = simd_shuffle_xor(x, 1);  x = (lane & 1)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 2);  x = (lane & 2)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 4);  x = (lane & 4)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 8);  x = (lane & 8)  ? (o - x) : (x + o);
        o = simd_shuffle_xor(x, 16); x = (lane & 16) ? (o - x) : (x + o);
        wht_sh[tid] = x;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        const ushort base = half_id * 128u;
        const float a0 = wht_sh[base + lane], a1 = wht_sh[base + 32u + lane];
        const float a2 = wht_sh[base + 64u + lane], a3 = wht_sh[base + 96u + lane];
        const float b0 = a0 + a1, b1 = a0 - a1, b2 = a2 + a3, b3 = a2 - a3;
        float r = (lsg == 0) ? (b0 + b2) : (lsg == 1 ? (b1 + b3) : (lsg == 2 ? (b0 - b2) : (b1 - b3)));
        ((threadgroup float *) qs4[half_id])[ltid] = r * 0.08838834764831845f;
        threadgroup_barrier(mem_flags::mem_threadgroup);

        float x2 = 0.0f;
        if (half_id == 0u) {
            const uint H2 = g * 3u + 2u;
            const float qv2 = half_io
                ? float(((device const half *) (A + task.qp_off))[H2 * HD + ltid])
                : A[task.qp_off + H2 * HD + ltid];
            x2 = sparse_rademacher_sign(a.pass_idx, g, ltid) * qv2;
        }
        o = simd_shuffle_xor(x2, 1);  x2 = (lane & 1)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 2);  x2 = (lane & 2)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 4);  x2 = (lane & 4)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 8);  x2 = (lane & 8)  ? (o - x2) : (x2 + o);
        o = simd_shuffle_xor(x2, 16); x2 = (lane & 16) ? (o - x2) : (x2 + o);
        wht_sh[tid] = x2;
        threadgroup_barrier(mem_flags::mem_threadgroup);
        if (half_id == 0u) {
            const float c0 = wht_sh[lane], c1 = wht_sh[32u + lane], c2 = wht_sh[64u + lane], c3 = wht_sh[96u + lane];
            const float d0 = c0 + c1, d1 = c0 - c1, d2 = c2 + c3, d3 = c2 - c3;
            float r2 = (lsg == 0) ? (d0 + d2) : (lsg == 1 ? (d1 + d3) : (lsg == 2 ? (d0 - d2) : (d1 - d3)));
            ((threadgroup float *) qs4[2])[ltid] = r2 * 0.08838834764831845f;
        }
    }
#endif
    threadgroup_barrier(mem_flags::mem_threadgroup);

    float sink[3];
    for (int h = 0; h < 3; h++) sink[h] = A[task.sink_off + g * 3u + uint(h)];

    const uint capped_total_blks = min(task.total_blks, SPARSE_MAX_BLKS);
    const uint capped_anchor_blks = min(task.anchor_blks, capped_total_blks);
    const uint capped_recent_start = min(task.recent_start_blk, capped_total_blks);
    const uint capped_far_start = clamp(task.far_start_blk, capped_anchor_blks, capped_recent_start);
    const uint nfar = min(task.n_far_blks, capped_recent_start - capped_far_start);
    const uint K_ret = min(task.top_k, min(nfar, SPARSE_4K_MAX_BLKS - 1u));

    const ushort sb = lane >> 2;
    const ushort pp = lane & 3u;
    device const ulong * BT = (a.is_paged != 0u) ? (BT_ALL + task.bt_full_base) : nullptr;

    uint running_m = 0u;
    if (K_ret > 0u && nfar > 0u) {
        uint far_off = 0u;
        while (far_off < nfar) {
            const uint chunk_cap = SPARSE_WIDE_CAND_CAP - running_m;
            const uint chunk_len = min(nfar - far_off, chunk_cap);
            for (uint q = sg; q < chunk_len; q += 8u) {
                const uint blk = capped_far_start + far_off + q;
                uint pool_idx = blk;
                bool blk_ok = true;
                if (a.is_paged != 0u) {
                    const ulong entry = BT[blk];
                    if (entry == KV_CLEARED_ENTRY) blk_ok = false;
                    else pool_idx = sparse_bt_pool_index(entry, a.slots_per_slab);
                }
                float best_s = -1.0e30f;
                if (blk_ok) {
                    device const Wht2HeadSketch * sm =
                        SKETCH + ((ulong(pool_idx) * 8ul + ulong(a.pass_idx)) * ulong(NKV) + ulong(g));
                    const float sc = float(sm->sc_sk[sb]);
                    const uint2 w2 = *(device const uint2 *) (sm->k_sk[sb] + pp * 2u);
                    float acc[3] = {0.0f, 0.0f, 0.0f};
                    if (sc > 0.0f) {
                        #pragma unroll
                        for (int i = 0; i < 2; i++) {
                            const uint u = w2[i];
                            const float4 k0 = float4(WHT2_LM2_VAL[u & 3u], WHT2_LM2_VAL[(u >> 2) & 3u], WHT2_LM2_VAL[(u >> 4) & 3u], WHT2_LM2_VAL[(u >> 6) & 3u]);
                            const float4 k1 = float4(WHT2_LM2_VAL[(u >> 8) & 3u], WHT2_LM2_VAL[(u >> 10) & 3u], WHT2_LM2_VAL[(u >> 12) & 3u], WHT2_LM2_VAL[(u >> 14) & 3u]);
                            const float4 k2 = float4(WHT2_LM2_VAL[(u >> 16) & 3u], WHT2_LM2_VAL[(u >> 18) & 3u], WHT2_LM2_VAL[(u >> 20) & 3u], WHT2_LM2_VAL[(u >> 22) & 3u]);
                            const float4 k3 = float4(WHT2_LM2_VAL[(u >> 24) & 3u], WHT2_LM2_VAL[(u >> 26) & 3u], WHT2_LM2_VAL[(u >> 28) & 3u], WHT2_LM2_VAL[(u >> 30) & 3u]);
                            for (int h = 0; h < 3; h++) {
                                acc[h] += dot(qs4[h][pp * 8 + i * 4 + 0], k0) + dot(qs4[h][pp * 8 + i * 4 + 1], k1)
                                        + dot(qs4[h][pp * 8 + i * 4 + 2], k2) + dot(qs4[h][pp * 8 + i * 4 + 3], k3);
                            }
                        }
                    }
                    for (int h = 0; h < 3; h++) {
                        float s = acc[h];
                        s += simd_shuffle_xor(s, 1);
                        s += simd_shuffle_xor(s, 2);
                        if (sc > 0.0f) best_s = max(best_s, s * sc - sink[h]);
                    }
                }
                const float page_s = simd_max(best_s);
                if (lane == 0) {
                    cand_ord[running_m + q] = sparse_float_to_ord(page_s);
                    cand_blk[running_m + q] = ushort(blk);
                }
            }
            const uint total_cand = running_m + chunk_len;
            far_off += chunk_len;
            if (tid == 0) {
                g_cut_prefix = 0u;
                g_cut_rem = K_ret;
            }
            threadgroup_barrier(mem_flags::mem_threadgroup);

            if (total_cand <= K_ret) {
                running_m = total_cand;
                continue;
            }

            // Exact 4-pass 8-bit radix Top-K threshold over `cand_ord[0..total_cand]`.
            for (int rpass = 0; rpass < 4; rpass++) {
                const uint shift = uint((3 - rpass) * 8);
                const uint mask_shift = (rpass == 0) ? 0u : uint((4 - rpass) * 8);
                const uint prefix = g_cut_prefix;
                atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed);
                threadgroup_barrier(mem_flags::mem_threadgroup);
                for (uint idx = tid; idx < total_cand; idx += 256u) {
                    const uint u = cand_ord[idx];
                    if (rpass == 0 || (u >> mask_shift) == prefix) {
                        atomic_fetch_add_explicit(&hist[(u >> shift) & 255u], 1u, memory_order_relaxed);
                    }
                }
                threadgroup_barrier(mem_flags::mem_threadgroup);
                if (tid == 0) {
                    uint acc = 0u, chosen = 0u;
                    const uint target = g_cut_rem;
                    for (int bi = 255; bi >= 0; bi--) {
                        const uint c = atomic_load_explicit(&hist[bi], memory_order_relaxed);
                        if (acc + c >= target) { chosen = uint(bi); break; }
                        acc += c;
                    }
                    g_cut_prefix = (prefix << 8) | chosen;
                    g_cut_rem = target - acc;
                }
                threadgroup_barrier(mem_flags::mem_threadgroup);
            }

            // Order-preserving in-place compaction of `cand[0..total_cand] -> cand[0..K_ret]`,
            // maintaining `cand_blk[0] < cand_blk[1] < ... < cand_blk[K_ret - 1]` strictly ascending.
            const uint thresh32 = g_cut_prefix;
            uint rem_ties = g_cut_rem;
            uint out_count = 0u;
            for (uint base_i = 0u; base_i < total_cand; base_i += 256u) {
                const uint i = base_i + uint(tid);
                const bool in_range = i < total_cand;
                const uint u = in_range ? cand_ord[i] : 0u;
                const ushort b = in_range ? cand_blk[i] : 0u;
                threadgroup_barrier(mem_flags::mem_threadgroup);

                const uint is_tie = (in_range && u == thresh32) ? 1u : 0u;
                const uint tie_sg_excl = simd_prefix_exclusive_sum(is_tie);
                const uint tie_sg_tot = simd_sum(is_tie);
                if (lane == 0) pop_scan[sg] = tie_sg_tot;
                threadgroup_barrier(mem_flags::mem_threadgroup);
                uint tie_sg_base = 0u;
                for (ushort s = 0; s < sg; s++) tie_sg_base += pop_scan[s];
                const bool take_tie = (is_tie != 0u) && ((tie_sg_base + tie_sg_excl) < rem_ties);
                const uint tie_stripe_sum = pop_scan[0] + pop_scan[1] + pop_scan[2] + pop_scan[3]
                                          + pop_scan[4] + pop_scan[5] + pop_scan[6] + pop_scan[7];
                rem_ties = (tie_stripe_sum >= rem_ties) ? 0u : (rem_ties - tie_stripe_sum);
                threadgroup_barrier(mem_flags::mem_threadgroup);

                const uint keep = ((in_range && u > thresh32) || take_tie) ? 1u : 0u;
                const uint keep_sg_excl = simd_prefix_exclusive_sum(keep);
                const uint keep_sg_tot = simd_sum(keep);
                if (lane == 0) pop_scan[sg] = keep_sg_tot;
                threadgroup_barrier(mem_flags::mem_threadgroup);
                uint keep_sg_base = 0u;
                for (ushort s = 0; s < sg; s++) keep_sg_base += pop_scan[s];
                if (keep != 0u) {
                    const uint dst_idx = out_count + keep_sg_base + keep_sg_excl;
                    cand_ord[dst_idx] = u;
                    cand_blk[dst_idx] = b;
                }
                const uint keep_stripe_sum = pop_scan[0] + pop_scan[1] + pop_scan[2] + pop_scan[3]
                                           + pop_scan[4] + pop_scan[5] + pop_scan[6] + pop_scan[7];
                out_count += keep_stripe_sum;
                threadgroup_barrier(mem_flags::mem_threadgroup);
            }
            running_m = K_ret;
        }
    }

    // Write the 3 disjoint strictly-ascending segments (`0..anchors`, `cand_blk[0..running_m]`, `recent..total`)
    // directly into `SPARSE_BUF` in ascending block-index order.
    device uint * sel_out = 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);
    for (uint b = tid; b < capped_anchor_blks; b += 256u) {
        if (b < task.total_sel_blks) {
            sel_out[b] = b;
        }
    }
    for (uint i = tid; i < running_m; i += 256u) {
        const uint out_idx = capped_anchor_blks + i;
        if (out_idx < task.total_sel_blks) {
            sel_out[out_idx] = uint(cand_blk[i]);
        }
    }
    const uint n_recent = capped_total_blks - capped_recent_start;
    for (uint r = tid; r < n_recent; r += 256u) {
        const uint out_idx = capped_anchor_blks + running_m + r;
        if (out_idx < task.total_sel_blks) {
            sel_out[out_idx] = capped_recent_start + r;
        }
    }
}

// Compact 1K-block (`<= 64K` ctx) WHT-2bit-sketch scorer (`sc_ord[1024]` = 4 KB TG SRAM for higher occupancy at 64-128 lanes).
// Bit-identical block selection to `k_score_full_sketch_dec` whenever `total_blks <= 1024`.
kernel void k_score_full_sketch_dec_1k(
    device const float * A [[buffer(2)]],
    constant ScoreFullSketchArgs & a [[buffer(5)]],
    device const ulong * BT_ALL [[buffer(8)]],
    device const Wht2HeadSketch * SKETCH [[buffer(13)]],
    device uint * SPARSE_BUF [[buffer(14)]],
    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 float4 qs4[3][HD / 4];
#ifndef KV4
    threadgroup float  wht_sh[256];
#endif
    threadgroup uint   sc_ord[SPARSE_1K_MAX_BLKS];
    threadgroup atomic_uint hist[256];
    threadgroup atomic_uint sel_mask[SPARSE_1K_MASK_WORDS];
    threadgroup uint   pop_scan[8];
    threadgroup uint   g_cut_prefix;
    threadgroup uint   g_cut_rem;

    score_full_sketch_dec_impl<SPARSE_1K_MAX_BLKS, SPARSE_1K_MASK_WORDS>(
        A, a, BT_ALL, SKETCH, SPARSE_BUF, qs4,
#ifndef KV4
        wht_sh,
#endif
        sc_ord, hist, sel_mask, pop_scan, g_cut_prefix, g_cut_rem, tgp, tid, sg, lane
    );
}

// -------------------------------------------------------------------------------------------------
// Sparse prefill (`INK_SPARSE_PREFILL`): content-dependent top-k key-block selection for prefill query blocks,
// in the spirit of SSA (subq.ai, "How SSA makes long context practical"): each 64-row query block of a full pass
// picks the key blocks it attends to by the same WHT-2bit block sketches and the same scorer
// (`score_full_sketch_dec_impl`, exact radix top-k, pinned anchors and recent blocks) that sparse decode uses, and
// `k_attn_tc_fixed_blk` then computes exact attention over just the selected blocks' keys.
//
// 1. `k_sparse_pf_prep` (grid `(n_qb, NH)`, 128 threads): the query block's summary query, the float mean of its
//    live rows' `qp` (and of their sinks) per head, and one `SparseDecTask` per query block whose geometry mirrors
//    `sparse_prefill_task_cpu` in `engine.rs`: a block below the context floor or within the budget selects every
//    causal block (`anchor_blks = total_blks`), any other pins `anchors` + the 16 recent blocks (its own block
//    last) and scores the far blocks between them.
// 2. `k_score_full_sketch_dec{,_1k,_wide}` over those tasks (`A` = this scratch, `half_io = 0`).
// 3. `k_sparse_pf_mask` (grid `(NKV, n_qb)`, 256 threads): the sorted selected-block lists as bitmasks,
//    `sel_words` u32 words per (query block, KV head), the layout `k_attn_tc_fixed_blk` reads.

struct SparsePfPrepArgs {
    uint q_pos0, q_rows, qp_off, sink_off;
    uint half_io, n_qb, qb0, anchors;
    uint recent, top_k, min_ctx, qm_off;
    uint sm_off, sel_stride, pad0, pad1;
};

kernel void k_sparse_pf_prep(
    device const float * A [[buffer(2)]],
    constant SparsePfPrepArgs & a [[buffer(5)]],
    device uint * SCR [[buffer(14)]],
    uint2 tgp [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]]
) {
    #pragma clang fp contract(off) reassociate(off)
    const uint q = tgp.x, H = tgp.y;
    if (q >= a.n_qb || H >= NH) return;
    const uint qb = a.qb0 + q;
    const uint q_end = a.q_pos0 + a.q_rows;
    const uint r_lo = max(a.q_pos0, qb * 64u) - a.q_pos0;
    const uint r_hi = min(q_end, qb * 64u + 64u) - a.q_pos0;
    device float * qm = (device float *) SCR;
    if (tid < HD) {
        float s = 0.0f;
        for (uint r = r_lo; r < r_hi; ++r) {
            const ulong at = ulong(r) * (NH * HD) + H * HD + tid;
            s += a.half_io ? float(((device const half *) (A + a.qp_off))[at]) : A[a.qp_off + at];
        }
        qm[a.qm_off + (q * NH + H) * HD + tid] = s / float(max(r_hi - r_lo, 1u));
    }
    if (tid == 0u) {
        float s = 0.0f;
        for (uint r = r_lo; r < r_hi; ++r) s += A[a.sink_off + r * NH + H];
        qm[a.sm_off + q * NH + H] = s / float(max(r_hi - r_lo, 1u));
    }
    if (tid == 0u && H == 0u) {
        const uint total = qb + 1u, pos = qb * 64u + 63u;
        const uint budget = a.anchors + a.recent + a.top_k;
        const bool pass = (a.top_k == 0u) || (pos < a.min_ctx) || (pos < budget * 64u) || (total <= budget);
        uint anchor_blks, far_start, n_far, recent_start, top_k, total_sel;
        if (pass) {
            anchor_blks = total; far_start = total; n_far = 0u; recent_start = total; top_k = 0u; total_sel = total;
        } else {
            recent_start = total - a.recent;
            anchor_blks = min(a.anchors, recent_start);
            far_start = anchor_blks;
            n_far = recent_start - far_start;
            top_k = min(a.top_k, n_far);
            total_sel = anchor_blks + top_k + a.recent;
        }
        device SparseDecTask & t = ((device SparseDecTask *) SCR)[q];
        t.span_idx = 0u; t.pos = pos; t.bt_full_base = 0u;
        t.anchor_blks = anchor_blks; t.far_start_blk = far_start; t.n_far_blks = n_far;
        t.recent_start_blk = recent_start; t.total_blks = total; t.top_k = top_k; t.total_sel_blks = total_sel;
        t.blks_per_split = 0u; t.nsplit = 0u; t.sel_out_base = q * NKV * a.sel_stride;
        t.qp_off = a.qm_off + q * NH * HD; t.rp_off = 0u; t.sink_off = a.sm_off + q * NH;
        t.kv_cur_off = 0u; t.part_off = 0u; t.kv_cap = 0u; t.flags = 0u;
    }
}

struct SparsePfMaskArgs {
    uint n_qb, sel_u32_base, mask_off, sel_words;
};

#define SPARSE_PF_MAX_WORDS (SPARSE_MAX_BLKS / 32u)

kernel void k_sparse_pf_mask(
    constant SparsePfMaskArgs & a [[buffer(5)]],
    device uint * SCR [[buffer(14)]],
    uint2 tgp [[threadgroup_position_in_grid]],
    ushort tid [[thread_index_in_threadgroup]]
) {
    threadgroup atomic_uint m[SPARSE_PF_MAX_WORDS];
    const uint g = tgp.x, q = tgp.y;
    if (q >= a.n_qb) return;
    const uint words = min(a.sel_words, SPARSE_PF_MAX_WORDS);
    for (uint w = tid; w < words; w += 256u) atomic_store_explicit(&m[w], 0u, memory_order_relaxed);
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device const SparseDecTask & t = ((device const SparseDecTask *) SCR)[q];
    device const uint * list = SCR + a.sel_u32_base + t.sel_out_base + g * t.total_sel_blks;
    for (uint i = tid; i < t.total_sel_blks; i += 256u) {
        const uint b = list[i];
        if ((b >> 5) < words) atomic_fetch_or_explicit(&m[b >> 5], 1u << (b & 31u), memory_order_relaxed);
    }
    threadgroup_barrier(mem_flags::mem_threadgroup);
    device uint * out = SCR + a.mask_off + (q * NKV + g) * a.sel_words;
    for (uint w = tid; w < words; w += 256u) out[w] = atomic_load_explicit(&m[w], memory_order_relaxed);
}

struct AttnSparseDecArgs {
    uint pass_idx, n_tasks, is_paged, relbias_w;
    uint tasks_u32_off, sel_u32_base, pass_sel_stride, pad0;
};

// Split-K full attention over sorted selected 64-token blocks (`anchor + top_k + 16`).
// Grid: (max_nsplit, NKV, n_tasks), TG = 128 threads (4 simdgroups).
kernel void k_attn_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]]
) {
    threadgroup float4 qs4[3][HD / 4];
    threadgroup float  rs[3][NREL];
    threadgroup float  ms_[4][3];
    threadgroup float  ls_[4][3];
    threadgroup float4 os_[4][3][32];

    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 half_io = (task.flags & 1u) != 0u;
    const bool cur_from_buf = ((task.flags & 2u) != 0u) || (a.pad0 != 0u);
    if (half_io) {
        device const half * qph = (device const half *) (A + task.qp_off);
        for (int h = 0; h < 3; h++) {
            const uint H = g * 3 + h;
            ((threadgroup float *) qs4[h])[tid] = float(qph[H * HD + tid]);
        }
    } else {
        for (int h = 0; h < 3; h++) {
            const uint H = g * 3 + h;
            ((threadgroup float *) qs4[h])[tid] = A[task.qp_off + H * HD + tid];
        }
    }
    if (tid < 48) {
        const uint h = tid / 16, i = tid % 16, H = g * 3 + h;
        rs[h][i] = A[task.rp_off + H * NREL + i];
    }
    float sink[3];
    for (int h = 0; h < 3; h++) sink[h] = A[task.sink_off + g * 3 + h];
    threadgroup_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 ushort kk = lane / 4, pp = lane % 4;
    const uint pos = task.pos;
    const uint kc_off = task.kv_cur_off + g * HD;
    const uint vc_off = task.kv_cur_off + NKV * HD + g * HD;

    float4 rl[3];
    for (int h = 0; h < 3; h++) rl[h] = *(threadgroup const float4 *) (&rs[h][pp * 4]);
    float mv[3] = {-INFINITY, -INFINITY, -INFINITY}, lv[3] = {0, 0, 0};
    float4 ov[3] = {0, 0, 0};

    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 ib_base = sg * 8u; ib_base < KV_BLK; ib_base += 32u) {
            const uint pb = blk_p0 + ib_base;
            if (pb >= p1) break;
            const uint raw_p = pb + kk;
            const bool valid = raw_p < p1;
            const uint p = min(raw_p, p1 - 1u);
            const uint ib = p - blk_p0;
            float acc[3] = {0, 0, 0};
            if (cur_from_buf && p == pos) {
                for (int c = 0; c < 8; c++) {
                    const float4 kf = *(device const float4 *) (A + kc_off + pp * 32 + c * 4);
                    for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
                }
            } else {
                device const kv_t * krow = k_blk + ib * KV_ROW_STEP;
#ifdef KV4
                device const ushort * ku = (device const ushort *) krow->qs + pp * 8;
                for (int c = 0; c < 8; c++) {
                    const float4 kf = kv4_u16_to_f4(ku[c]);
                    for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
                }
                const float ks = float(krow->sc);
                for (int h = 0; h < 3; h++) acc[h] *= ks;
#elif defined(KV8)
                device const packed_char4 * kr = (device const packed_char4 *) (krow + pp * 32);
                for (int c = 0; c < 8; c++) {
                    const float4 kf = float4(char4(kr[c]));
                    for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
                }
                const float ks = kv_vscale(krow);
                for (int h = 0; h < 3; h++) acc[h] *= ks;
#else
                device const half4 * kr = (device const half4 *) (krow + pp * 32);
                for (int c = 0; c < 8; c++) {
                    const float4 kf = float4(kr[c]);
                    for (int h = 0; h < 3; h++) acc[h] += dot(qs4[h][pp * 8 + c], kf);
                }
#endif
            }
            const uint d_pos = pos - p;
            if (d_pos < EXT) {
                const float4 bb = *(device const float4 *) (relb + d_pos * NREL + pp * 4);
                for (int h = 0; h < 3; h++) acc[h] += dot(rl[h], bb);
            }
            float pr[3], sc_[3];
            for (int h = 0; h < 3; h++) {
                float t = acc[h];
                t += simd_shuffle_xor(t, 1); t += simd_shuffle_xor(t, 2);
                t = valid ? t - sink[h] : -INFINITY;
                const float mx = max(mv[h], simd_max(t));
                sc_[h] = (mv[h] == -INFINITY) ? 0.0f : exp(mv[h] - mx);
                pr[h] = valid ? exp(t - mx) : 0.0f;
                lv[h] = lv[h] * sc_[h] + simd_sum(pr[h]) * 0.25f;
                mv[h] = mx;
                ov[h] *= sc_[h];
            }
#ifdef KV4
            {
                const float vsc = (cur_from_buf && p == pos) ? 1.0f : float((v_blk + ib * KV_ROW_STEP)->sc);
                for (int h = 0; h < 3; h++) pr[h] *= vsc;
            }
#elif defined(KV8)
            {
                const float vsc = (cur_from_buf && p == pos) ? 1.0f : kv_vscale(v_blk + ib * HD);
                for (int h = 0; h < 3; h++) pr[h] *= vsc;
            }
#endif
            for (ushort q = 0; q < 8; q++) {
                const uint pq = pb + q;
                if (pq >= p1) break;
                const uint iq = pq - blk_p0;
                const float4 v = (cur_from_buf && pq == pos)
                    ? *(device const float4 *) (A + vc_off + lane * 4)
#ifdef KV4
                    : kv4_u16_to_f4(((device const ushort *) (v_blk + iq * KV_ROW_STEP)->qs)[lane]);
#elif defined(KV8)
                    : float4(char4(*(device const packed_char4 *) (v_blk + iq * HD + lane * 4)));
#else
                    : float4(*(device const half4 *) (v_blk + iq * HD + lane * 4));
#endif
                for (int h = 0; h < 3; h++) ov[h] += simd_shuffle(pr[h], q * 4) * v;
            }
        }
    }

    if (lane == 0) for (int h = 0; h < 3; h++) { ms_[sg][h] = mv[h]; ls_[sg][h] = lv[h]; }
    for (int h = 0; h < 3; h++) os_[sg][h][lane] = ov[h];
    threadgroup_barrier(mem_flags::mem_threadgroup);
    for (int h = 0; h < 3; h++) {
        float M_val = -INFINITY;
        for (int s2 = 0; s2 < 4; s2++) M_val = max(M_val, ms_[s2][h]);
        float L = 0, O = 0;
        for (int s2 = 0; s2 < 4; s2++) {
            const float w = ms_[s2][h] == -INFINITY ? 0.0f : exp(ms_[s2][h] - M_val);
            L += w * ls_[s2][h];
            O += w * ((threadgroup const float *) os_[s2][h])[tid];
        }
        device float * P = A + task.part_off + ((g * 3 + h) * task.nsplit + sp) * (HD + 2);
        if (tid == 0) { P[0] = M_val; P[1] = L; }
        P[2 + tid] = O;
    }
}

// Split combine of verify rows that ran `k_attn_sparse_dec` (`--sparse-topk` with DSpark / prompt-lookup verify).
// One task per query row: the task's own `part_off` and `nsplit`, exactly as `k_attn_combine_dec` reads them from a
// decode span's `DecodeSpanDesc`, and the same arithmetic in the same order, so a verify row combines to the bits a
// decode step at that position writes. Row `task.pos - a.pos0` of the span's gate / output rows.
// grid: (NH, n_tasks, 1) x 128 threads. hout bit 0: write half; bit 1: read gate as half. pad0: KV4 slot.
struct CombineSparseRowsArgs { uint tasks_u32_off, n_tasks, pos0, gate_off; uint out_off, hout, pad0, pad1; };
kernel void k_attn_combine_sparse_rows(device float * A [[buffer(2)]], constant CombineSparseRowsArgs & a [[buffer(5)]],
                                       device const uint * SPARSE_BUF [[buffer(14)]],
                                       uint2 tgp [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
                                       ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
    const uint h = tgp.x, u_task = tgp.y;
    if (u_task >= a.n_tasks) return;
    device const SparseDecTask & task = ((device const SparseDecTask *) (SPARSE_BUF + a.tasks_u32_off))[u_task];
    const uint nsplit = task.nsplit;
    device const float * P = A + task.part_off + h * nsplit * (HD + 2);
    float M = 0.0f;  // sink logit
    for (uint s = 0; s < nsplit; s++) M = max(M, P[s * (HD + 2)]);
    float L = exp(-M), o = 0;
    for (uint s = 0; s < nsplit; s++) {
        const float w = exp(P[s * (HD + 2)] - M);
        L += w * P[s * (HD + 2) + 1];
        o += w * P[s * (HD + 2) + 2 + tid];
    }
    float o_val = o / L;
#ifdef KV4
    threadgroup float wht_sh[128];
    o_val = kv4_rademacher(a.pad0 * 2u + 1u, h / 3u, tid) * wht128_tg(o_val, tid, sg, lane, wht_sh);
#else
    (void) sg; (void) lane;
#endif
    const uint row = task.pos - a.pos0;
    const uint i = row * (NH * HD) + h * HD + tid;
    const float gate = (a.hout & 2u) ? float(((device const half *) (A + a.gate_off))[i]) : A[a.gate_off + i];
    const float val = o_val * sigm(gate);
    if (a.hout & 1u) ((device half *) (A + a.out_off))[i] = half(val);
    else A[a.out_off + i] = val;
}
#pragma clang fp contract(off) reassociate(off)