onnx-runtime-ep-cuda 0.1.0-dev.6

CUDA execution provider for the ORT 2.0 runtime (Phase 2a: cudarc + cuBLASLt MatMul; custom fused kernels deferred)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
//! `com.microsoft::MatMulNBits`: decode-specialized packed INT4/INT8 GEMV plus
//! the block-wise dequantization and f32 cuBLASLt GEMM fallback used for prefill.

use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use cudarc::driver::{LaunchConfig, PushKernelArg, sys::CUdeviceptr};
use onnx_runtime_ep_api::{
    DeviceGraphResource, DevicePtr, DevicePtrMut, EpError, Kernel, KernelFactory, Result,
    TensorMetadata, TensorMut, TensorView, WorkspaceRequirement, WorkspaceView,
};
use onnx_runtime_ir::{DataType, Node};

use crate::blas::{self, GemmDtype, GemmEpilogue, GemmEpilogueKind, GemmEx, GemmParams};
use crate::error::driver_err;
use crate::kernels::marlin_gemm;
use crate::runtime::{CudaRuntime, GraphDeviceAllocation, cuptr, raw_ptr};

const DEQUANT_MODULE: &str = "matmul_nbits_dequant_f32";
const DEQUANT_ENTRY: &str = "matmul_nbits_dequant_f32";
const GEMV_MODULE: &str = "matmul_nbits_gemv";
const GEMV_F32_ENTRY: &str = "matmul_nbits_gemv_f32";
const GEMV_INT8_F32_ENTRY: &str = "matmul_nbits_gemv_int8_f32";
/// Structurally-selected int4 / `block_size == 128` / asymmetric fp32-activation
/// decode GEMV. It preserves the generic f32 GEMV's per-thread accumulation and
/// reduction order while folding block arithmetic and vectorizing packed-nibble
/// loads.
const GEMV_INT4_F32_BLOCK128_ENTRY: &str = "matmul_nbits_gemv_int4_f32_block128";
/// Structurally-selected int8 / `block_size == 128` / asymmetric fp32-activation
/// decode GEMV. Bit-for-bit identical to the generic [`GEMV_F32_ENTRY`] path
/// (same per-thread depth stride, same per-element expression, same fp32
/// reduction) but with `block_size == 128` folded into a shift (`>> 7`) so the
/// per-weight division/modulo, the runtime bit-width branch, and the repeated
/// `column * k_blocks` scale/zero-point base recomputation all drop out.
const GEMV_INT8_F32_BLOCK128_ENTRY: &str = "matmul_nbits_gemv_int8_f32_block128";
const QUANTIZE_ACCURACY4_ENTRY: &str = "matmul_nbits_quantize_accuracy4_block32";
const GEMV_ACCURACY4_ENTRY: &str = "matmul_nbits_gemv_accuracy4_block32";
const GEMV_ACCURACY4_STAGE64_ENTRY: &str = "matmul_nbits_gemv_accuracy4_block32_stage64";
// General-block-size fp32-activation accuracy_level=4 decode entries. These give
// the fp32 `run` path the same "quantize the activation to int8 once, then run a
// parallelized GEMV" treatment the block-32 path already enjoys, but for any
// power-of-two block_size and for the asymmetric (zero-point) int4 layout. They
// are bit-for-bit identical to the grid-starved `matmul_nbits_accuracy4` tiled
// GEMM (same per-K-block int8 activation quantization, same per-block integer
// dot, same sequential fp32 block accumulation) — only the parallelization
// differs, so decode tokens are unchanged.
const QUANTIZE_ACCURACY4_BLOCKWISE_ENTRY: &str = "matmul_nbits_quantize_accuracy4_blockwise";
const GEMV_ACCURACY4_BLOCKWISE_ENTRY: &str = "matmul_nbits_gemv_accuracy4_blockwise";
const ACCURACY4_MODULE: &str = "matmul_nbits_accuracy4";
const ACCURACY4_ENTRY: &str = "matmul_nbits_accuracy4";
const BLOCK_THREADS: u32 = 256;
const GEMV_ACCURACY4_THREADS: u32 = 256;
const GEMV_ACCURACY4_COLUMNS_PER_BLOCK: usize = 8;
const GEMV_ACCURACY4_SHARED_BYTES: u32 = 32 * 32;
const GEMV_ACCURACY4_STAGE64_SHARED_BYTES: u32 = 64 * 32;
const GEMV_F16_MODULE: &str = "matmul_nbits_gemv_f16";
const GEMV_F16_ENTRY: &str = "matmul_nbits_gemv_f16";
const GEMV_INT8_F16_ENTRY: &str = "matmul_nbits_gemv_int8_f16";
/// Split-K specialization of [`GEMV_INT8_F16_ENTRY`]. ncu showed the single-warp
/// standalone int8 GEMV grid-starved on Phi's int8 down projection (grid 384,
/// ~0.48 waves/SM, ~35% occupancy, 28µs) — unlike the fused RMSNorm-prologue int8
/// kernel, it has no serial prologue, so partitioning the K reduction across
/// [`GEMV_INT8_F16_SPLITK`] cooperating warps per output column multiplies the
/// grid to fill the SMs and directly attacks the memory-latency bound. The K-slice
/// partials are summed in fp32 (a new block-sum association vs the single-warp
/// kernel), so this path is near-equal — not byte-identical — to the plain entry;
/// asymmetric-zp parity is validated against a dequant reference to tolerance. Only
/// launched when `K % 256 == 0` (whole 256-wide steps, no divergent tail) and the
/// weights carry zero points; symmetric int8 keeps the byte-identical single-warp
/// kernel.
const GEMV_INT8_F16_SPLITK_ENTRY: &str = "matmul_nbits_gemv_int8_f16_splitk";
/// Warps cooperating per output column in the split-K standalone int8 GEMV. Must
/// match `K_SPLIT` in `matmul_nbits_gemv_int8_f16_splitk`. A block keeps its
/// `blockDim.x / 32` warps but now covers `warps / K_SPLIT` columns, so the launch
/// grid grows by this factor.
const GEMV_INT8_F16_SPLITK: usize = 2;
const GEMM_F16_ENTRY: &str = "matmul_nbits_gemm_f16";
/// Model-agnostic fp16 int4 decode GEMV for any power-of-two `block_size` (16,
/// 64, 128, 256, ...). The tuned [`GEMV_F16_ENTRY`]/[`GEMV_F16_SCALES_F16_ENTRY`]
/// kernels bake in the block-32 four-lane/eight-block warp layout; this entry
/// instead derives the scale/zero-point block index from the actual
/// `block_size` (`block = depth / block_size`) so a lane's contiguous 8-element
/// chunk maps to the correct block regardless of block width.
const GEMV_F16_GENERAL_BS_ENTRY: &str = "matmul_nbits_gemv_f16_general_bs";
/// Split-K counterpart of [`GEMV_F16_GENERAL_BS_ENTRY`]: `K_SPLIT` warps
/// cooperate on one output column and reduce their fp32 partials through shared
/// memory, so the launch grid is `K_SPLIT`x larger and fills the SMs on the
/// grid-starved block!=32 decode projections (medium/KV GEMVs run at ~0.5
/// waves single-warp). Near-equal (not byte-identical) to the single-warp
/// entry — the split reorders the partial-sum association, the same trade the
/// block-32 split-K entries already ship by default.
const GEMV_F16_GENERAL_BS_SPLITK_ENTRY: &str = "matmul_nbits_gemv_f16_general_bs_splitk";
/// Wide-load (128-bit `uint4` weight load, software-pipelined) counterpart of
/// [`GEMV_F16_GENERAL_BS_ENTRY`]. Each lane owns 32 contiguous nibbles per step
/// and streams them with one pipelined `uint4` load (4x fewer load instructions,
/// 2+ loads in flight) to raise memory-level parallelism / DRAM bandwidth on
/// the M=1 int4 decode GEMV toward ORT's (head-to-head: ORT 2.42 TB/s vs our
/// 0.92 TB/s at the same grid/occupancy — a pure narrow-load-issue gap). int4
/// only; requires `block_size % 32 == 0 && k % 32 == 0`. Near-equal (32-wide
/// lane interleave regroups the fp32 partials), gated greedy-token-identical.
const GEMV_F16_GENERAL_BS_WIDE_ENTRY: &str = "matmul_nbits_gemv_f16_general_bs_wide";
/// Wide-load counterpart of [`GEMV_F16_GENERAL_BS_SPLITK_ENTRY`] (see
/// [`GEMV_F16_GENERAL_BS_WIDE_ENTRY`]): `K_SPLIT` warps each walk a
/// `32 * K_SPLIT`-strided set of 32-nibble chunks with pipelined `uint4` loads.
const GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY: &str = "matmul_nbits_gemv_f16_general_bs_splitk_wide";
/// Column register-blocked wide-load GEMV
/// (`matmul_nbits_gemv_f16_general_bs_wide_multicol`): each warp emits
/// [`GEMV_F16_WIDE_MULTICOL_NC`] output columns, decoding each activation
/// sub-word once and reusing it across the columns. Attacks the L1/TEX-throughput
/// limiter of [`GEMV_F16_GENERAL_BS_WIDE_ENTRY`] (redundant per-column activation
/// re-reads) while staying byte-identical (per-column fp32 accumulation order
/// unchanged). Non-split-K only (used on the wide, occupancy-filled gate_up).
const GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY: &str =
    "matmul_nbits_gemv_f16_general_bs_wide_multicol";
/// fp16 mixed-precision counterpart of
/// [`GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY`]
/// (`matmul_nbits_gemv_f16_general_bs_wide_multicol_fp16`): identical
/// column-register-blocking, but the per-chunk MAC runs in fp16 `__hfma2` (two
/// fused MACs/instruction) to cut the dequant/MAC ALU that limits the fp32
/// multicol kernel — the fp16-vs-fp16 equal-conditions path against ORT's fp16
/// `MatMulFloatInt4Kernel`. The entire per-lane K reduction runs in fp16
/// `__half2` accumulators (each 32-product chunk summed in fp16, its per-block
/// scale folded in with `__hfma2`), exactly mirroring ORT's
/// `MatMulFloat4BitsKernelM1`; fp32 is used ONLY in the final cross-lane
/// warp-shuffle reduction. This is safe (no token-flipping mantissa loss)
/// because each lane strides K by 32 and folds only a handful of chunks, so the
/// fp16 accumulation is a wide, shallow tree of depth ~tens, not K. Because the
/// arithmetic mirrors ORT's it lands in ORT's own error class — NOT byte-identical
/// to the fp32 path, so it is opt-in via [`use_gemv_fp16`] and gated on accuracy
/// (error <= ORT vs an f64 oracle), not bit-identity.
const GEMV_F16_GENERAL_BS_WIDE_MULTICOL_FP16_ENTRY: &str =
    "matmul_nbits_gemv_f16_general_bs_wide_multicol_fp16";
/// Interleaved + biased (symmetric-only, OPT-IN) counterpart of
/// [`GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY`]
/// (`matmul_nbits_gemv_f16_general_bs_wide_multicol_interleaved`). Same
/// column-register-blocking wide-load geometry, but consumes offline
/// nibble-interleaved weights and folds the symmetric `-8` bias into the LOP3
/// magic-removal constants (TRT-LLM `FastInterleavedAndBiasedNumericArrayConverter`
/// lever). This drops the per-block zero-point `sub.f16x2` and the `prmt.b32`
/// activation reorder from the decode inner loop (~14 -> ~9 dequant instrs / 8
/// values), attacking the instruction/issue-slot limiter of the M=1 decode GEMV.
/// Byte-identical output to the fp32 multicol kernel on symmetric weights.
/// Enabled only when [`interleave_dequant_enabled`] is set; the dispatch swaps
/// the packed pointer for the interleaved cache buffer at the same time.
const GEMV_F16_GENERAL_BS_WIDE_MULTICOL_INTERLEAVED_ENTRY: &str =
    "matmul_nbits_gemv_f16_general_bs_wide_multicol_interleaved";
/// Interleaved + biased (symmetric-only, OPT-IN) counterpart of
/// [`GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY`]
/// (`matmul_nbits_gemv_f16_general_bs_splitk_wide_interleaved`). Same split-K
/// wide-load geometry (K_SPLIT warps/column, shared-memory fp32 partial
/// reduction), but consumes offline nibble-interleaved weights and folds the
/// symmetric `-8` bias into the LOP3 converter. Captures the grid-starved
/// narrow-N projections (glm qkv/down) that take the split-K path, compounding
/// the multicol lever. Byte-identical to the non-interleaved split-K wide kernel
/// on symmetric weights. Enabled only when [`interleave_dequant_enabled`] is set.
const GEMV_F16_GENERAL_BS_SPLITK_WIDE_INTERLEAVED_ENTRY: &str =
    "matmul_nbits_gemv_f16_general_bs_splitk_wide_interleaved";
/// Multicol x split-K hybrid of [`GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY`]
/// (`matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol`): keeps the split-K
/// grid-fill (K_SPLIT warps/column group, shared-memory fp32 partial reduction)
/// but register-blocks [`GEMV_F16_WIDE_MULTICOL_NC`] output columns per warp, so
/// each warp issues WIDE_NC independent 128-bit weight loads per chunk. This
/// ports the gate_up `wide_multicol` kernel's memory-level parallelism (which
/// runs at ~37% DRAM peak) to the grid-starved medium-N split-K projections
/// (down_proj / qkv / attn-out) that the single-column split-K wide kernel left
/// latency-bound at ~16% DRAM peak. A 256-thread CTA covers
/// `(8 / K_SPLIT) * GEMV_F16_WIDE_MULTICOL_NC` output columns. Byte-identical to
/// [`GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY`] (same per-lane depth0/stride, same
/// per-column accumulation order, same K_SPLIT reduction order).
const GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY: &str =
    "matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol";
/// Interleaved + biased (symmetric-only, OPT-IN) sibling of
/// [`GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY`]
/// (`matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol_interleaved`). Same
/// multicol x split-K geometry, consumes offline nibble-interleaved weights and
/// folds the symmetric -8 bias into the LOP3 converter. Byte-identical to the
/// non-interleaved multicol split-K kernel on symmetric weights; enabled only
/// when [`interleave_dequant_enabled`] is set.
const GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_INTERLEAVED_ENTRY: &str =
    "matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol_interleaved";
/// Offline int4 nibble-interleave pass entry
/// (`matmul_nbits_interleave_int4`); runs once per weight into the cache buffer.
const INTERLEAVE_INT4_ENTRY: &str = "matmul_nbits_interleave_int4";
/// Output columns each warp emits in the register-blocked wide GEMV. Must match
/// `#define WIDE_NC` in the CUDA source. A 256-thread CTA (8 warps) therefore
/// covers `8 * GEMV_F16_WIDE_MULTICOL_NC` columns.
const GEMV_F16_WIDE_MULTICOL_NC: usize = 4;
/// Warps cooperating per output column in the block!=32 general_bs split-K GEMV.
/// Must match `constexpr int K_SPLIT` in `matmul_nbits_gemv_f16_general_bs_splitk`.
/// A block keeps its `blockDim.x / 32` warps but now covers `warps / K_SPLIT`
/// columns, so the launch grid grows by this factor. Tuned to 4 on glm-4-9b
/// (block-128, N=4096 medium projections): K_SPLIT=2 lifts the grid-starved
/// single-warp launch from ~0.5 to ~1 wave, K_SPLIT=4 to ~2 waves (the
/// latency-hiding target), which measured fastest (+9.7% decode vs single-warp);
/// K_SPLIT=8 saturated.
const GENERAL_BS_SPLITK: usize = 4;
/// Warps cooperating per output column GROUP in the multicol x split-K hybrid
/// GEMV (`matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol`). Kept at 4
/// (independent of [`GENERAL_BS_SPLITK`] so it can be tuned separately) because
/// the hybrid register-blocks [`GEMV_F16_WIDE_MULTICOL_NC`] columns per warp
/// (WIDE_NC independent weight-load streams supply the memory-level parallelism),
/// so K_SPLIT only has to refill the grid. With WIDE_NC=4 a 256-thread CTA covers
/// `(8 / K_SPLIT) * WIDE_NC` columns; K_SPLIT=4 lands N=4096 at ~1 wave and
/// measured fastest — K_SPLIT=8 (~2 waves) regressed decode (the 8-way partial
/// reduction + halved per-warp work outweighed the extra grid-fill). Must match
/// `constexpr int K_SPLIT` in the `*_splitk_wide_multicol*` CUDA kernels.
const GENERAL_BS_SPLITK_MULTICOL: usize = 4;
/// Model-agnostic fp16 int4/int8 prefill GEMM for any power-of-two `block_size`.
/// Mirrors [`GEMM_F16_ENTRY`] but walks `K` in fixed 32-wide tiles and computes
/// `block = depth / block_size`, decoupling the tile width from the block width.
const GEMM_F16_GENERAL_BS_ENTRY: &str = "matmul_nbits_gemm_f16_general_bs";
const GEMV_F16_SCALES_F16_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16";
/// Asymmetric-zero-point specialization of [`GEMV_F16_SCALES_F16_ENTRY`]. The
/// symmetric entry above is compiled with `HasZp == false`, which
/// dead-code-eliminates the per-block zero-point global load and folds the
/// subtrahend to the constant fp16 `8.0` (byte-identical to the pre-zero-point
/// path). Weights that actually carry zero points launch this `_zp` entry so
/// only the asymmetric path pays for the extra per-block load.
const GEMV_F16_SCALES_F16_ZP_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_zp";
/// Prefetch-pipelined siblings of [`GEMV_F16_SCALES_F16_ENTRY`] /
/// [`GEMV_F16_SCALES_F16_ZP_ENTRY`]. Same lane->nibble mapping, fp16
/// accumulation, and reduction order (BYTE-IDENTICAL output), but a depth-4
/// register shift register keeps 4 weight loads in flight per lane to hide the
/// Long-Scoreboard global-load latency that dominates the single-warp kernel
/// (ncu: ~75% of warp cycles stalled on the one in-flight 32-bit load). Selected
/// by [`use_scales_f16_pipeline`] (default-on for the single-warp block-32 int4
/// path; `ONNX_GENAI_GEMV_PIPELINE=0` forces the original entry for A/B).
const GEMV_F16_SCALES_F16_PIPE_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_pipe";
const GEMV_F16_SCALES_F16_ZP_PIPE_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_zp_pipe";
const GEMV_F16_SCALES_F16_SPLITK_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_splitk";
/// Split-K specialization for standalone fp16/scales-fp16 int4 GEMV. ncu showed
/// the plain single-warp kernel can be grid-starved
/// (~0.36 waves/SM, ~64% of the SMs idle) and memory-latency bound: partitioning
/// the K reduction across [`GEMV_F16_SCALES_F16_ZP_SPLITK`] cooperating warps per
/// output column multiplies the grid, filling the machine so the extra in-flight
/// loads hide the Long-Scoreboard latency. The K-slice partials are summed in
/// fp32 (a new block-sum association vs the single-warp kernel), so this path is
/// near-equal — not byte-identical — to the plain `_zp` kernel; the asymmetric-zp
/// parity tests track a dequant reference to tolerance.
const GEMV_F16_SCALES_F16_ZP_SPLITK_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_zp_splitk";
/// Prefetch-pipelined siblings of the block-32 scales-fp16 split-K int4 GEMVs.
/// Same K_SPLIT geometry, lane->nibble mapping and per-split accumulation order,
/// so they are bit-identical to the non-`_pf` split-K entries; the only change
/// is that each lane keeps `PF` weight-word loads in flight (a register-resident
/// shift register) to hide the Long-Scoreboard weight-load latency that the
/// split-K loop otherwise stalls on. Selected by [`use_scales_f16_zp_splitk_pf`]
/// (default-on; `ONNX_GENAI_ZP_SPLITK_PREFETCH=0` forces the plain split-K entry
/// for A/B).
const GEMV_F16_SCALES_F16_SPLITK_PF_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_splitk_pf";
const GEMV_F16_SCALES_F16_ZP_SPLITK_PF_ENTRY: &str =
    "matmul_nbits_gemv_f16_scales_f16_zp_splitk_pf";
/// Warps cooperating per output column in the split-K asymmetric int4 GEMV. Must
/// match `K_SPLIT` in `matmul_nbits_gemv_f16_scales_f16_splitk`. A block keeps
/// its `blockDim.x / 32` warps but now covers `warps / K_SPLIT` columns, so the
/// launch grid grows by this factor.
const GEMV_F16_SCALES_F16_ZP_SPLITK: usize = 2;
/// Deep-split entry for output widths that are still grid-starved at
/// [`GEMV_F16_SCALES_F16_ZP_SPLITK`]. See
/// [`scales_f16_zp_split_factor`] for when it is chosen.
const GEMV_F16_SCALES_F16_ZP_SPLITK8_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_zp_splitk8";
/// Prefetch-pipelined sibling of [`GEMV_F16_SCALES_F16_ZP_SPLITK8_ENTRY`]
/// (default-on; `ONNX_GENAI_ZP_SPLITK_PREFETCH=0` forces the plain deep-split
/// entry for A/B).
const GEMV_F16_SCALES_F16_ZP_SPLITK8_PF_ENTRY: &str =
    "matmul_nbits_gemv_f16_scales_f16_zp_splitk8_pf";
/// Warps per output column in [`GEMV_F16_SCALES_F16_ZP_SPLITK8_ENTRY`]. Must
/// match the `K_SPLIT` template argument of that entry, and must not exceed the
/// 8 warps of the 256-thread launch (at equality each CTA covers one column).
const GEMV_F16_SCALES_F16_ZP_SPLITK8: usize = 8;
/// General fp16/fp16-scales GEMV with a fused RMS-normalization prologue (see
/// [`crate::optimizer::CudaSkipRmsNormMatMulFusion`]). It normalizes the input
/// activation in-kernel — byte-identically to `skip_rmsnorm_f16_warp_half4` —
/// before the standard `scales_f16` int4 dot, folding a
/// `SkipSimplifiedLayerNormalization` normalization into the following GEMV.
const GEMV_F16_SCALES_F16_RMSNORM_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_rmsnorm";
const GEMV_F16_SCALES_F16_RMSNORM_SPLITK_ENTRY: &str =
    "matmul_nbits_gemv_f16_scales_f16_rmsnorm_splitk";
/// Asymmetric-zero-point specialization of [`GEMV_F16_SCALES_F16_RMSNORM_ENTRY`]
/// (see [`GEMV_F16_SCALES_F16_ZP_ENTRY`] for the `HasZp` specialization scheme).
const GEMV_F16_SCALES_F16_RMSNORM_ZP_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_rmsnorm_zp";
/// INT8 sibling of [`GEMV_F16_SCALES_F16_RMSNORM_ENTRY`]. Shares the RMS
/// reduction and normalized-activation staging bit-for-bit and swaps in the
/// block-32 int8 dequant dot, fusing a `SkipSimplifiedLayerNormalization` into
/// the following int8 GEMV (e.g. Phi's int8 qkv projection). Compiled in the
/// same symmetric/`_zp` `HasZp` pair as the int4 sibling so a future
/// symmetric-int8 model keeps the constant-subtrahend (no per-block load) path.
const GEMV_INT8_F16_SCALES_F16_RMSNORM_ENTRY: &str =
    "matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm";
/// Asymmetric-zero-point specialization of
/// [`GEMV_INT8_F16_SCALES_F16_RMSNORM_ENTRY`] (Phi int8 qkv carries zero points).
const GEMV_INT8_F16_SCALES_F16_RMSNORM_ZP_ENTRY: &str =
    "matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm_zp";
/// Standalone RMS-normalization prologue used by the fused GEMV's M>1 prefill
/// path (see [`MatMulNBitsKernel::launch_rmsnorm_prefill`]).
const RMSNORM_PREFILL_ENTRY: &str = "matmul_nbits_rmsnorm_f16_warp_half4";
/// One warp (32 lanes) normalizes one token row in the prefill prologue.
const RMSNORM_PREFILL_THREADS: u32 = 32;
const GEMV_F16_DOWN_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_down";
/// Grid-fill specializations of [`GEMV_F16_DOWN_ENTRY`]: identical numerics with
/// 4 / 2 columns per CTA instead of 8, so the launch grid grows 2x / 4x to fill
/// the multiprocessors on grid-starved (small-N) tall-skinny down projections.
/// Every output column is still reduced entirely within one CTA in the same
/// order, so the fp32 accumulation is bit-identical to the 8-column entry — only
/// the CTA count changes. Selected by [`select_down_columns`] from the device
/// multiprocessor count.
const GEMV_F16_DOWN_C4_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_down_c4";
const GEMV_F16_DOWN_C2_ENTRY: &str = "matmul_nbits_gemv_f16_scales_f16_down_c2";
const GEMM_F16_TILE: usize = 16;

/// Upper bound on batch `M` for which small-batch decode reuses the capture-safe
/// single-row decode GEMV once per row instead of the tiled prefill GEMM.
///
/// Why a bound exists: the M>1 tiled GEMM tiles the M dimension in
/// [`GEMM_F16_TILE`]-row (16) blocks with a grid of `ceil(M/16)` tile-rows, so
/// for any `M in [1, 16]` it launches the *same* `(N/16) x 1` CTA grid and pays
/// a full weight-grid dequant+MAC pass whose cost is independent of `M`. A
/// single-row decode GEMV instead reads the weights once for one row; looping it
/// `M` times reads the weights `M` times but skips the tiled GEMM's fixed
/// full-grid overhead, so it is faster while `M x gemv_step < tiled_step`.
///
/// Measured crossover on **RTX 4060 Laptop 8 GB, i7-13800H (14C/20T), CUDA 13.1**,
/// `qwen05b-q4` (native CUDA, fp16 activation, int4): the M==1 decode GEMV runs a
/// full forward step in ~2.55 ms; the tiled GEMM step is ~28.6 ms and flat for
/// M=2..16. So `M x 2.55 ms < 28.6 ms` holds up to `M ~ 11`. The default is set
/// conservatively below that measured crossover; the ratio is a kernel-efficiency
/// property (both paths are weight-bandwidth bound on the same weights) so it is
/// approximately model-independent, but it IS hardware-dependent — retune per
/// #1261 via `ONNX_GENAI_DECODE_GEMV_LOOP_MAX_M` rather than trusting this number
/// on a different GPU.
const DECODE_GEMV_LOOP_MAX_M_DEFAULT: usize = 8;
/// The decode GEMVs load activation chunks as `uint4` (8 fp16 values). The base
/// allocation is aligned, so every per-row sub-view remains 16-byte aligned only
/// when the row stride `K * sizeof(fp16)` is a multiple of 16 bytes.
const GEMV_F16_ACTIVATION_VECTOR_ELEMENTS: usize = 8;

fn decode_gemv_loop_rows_aligned(k: usize) -> bool {
    k.is_multiple_of(GEMV_F16_ACTIVATION_VECTOR_ELEMENTS)
}

fn marlin_weight_inputs_are_constant(constant_inputs: &[bool], gate_up_swiglu: bool) -> bool {
    if gate_up_swiglu {
        constant_inputs.get(1) == Some(&true) && constant_inputs.get(3) == Some(&true)
    } else {
        constant_inputs.get(1) == Some(&true)
    }
}

/// Resolve the looped-decode-GEMV batch bound, honoring the
/// `ONNX_GENAI_DECODE_GEMV_LOOP_MAX_M` override (read once per process). Setting
/// it to `1` disables the loop (all `M>1` go to the tiled GEMM), which is the
/// byte-identical A/B baseline for measuring the change.
fn decode_gemv_loop_max_m() -> usize {
    static CACHE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *CACHE.get_or_init(|| {
        std::env::var("ONNX_GENAI_DECODE_GEMV_LOOP_MAX_M")
            .ok()
            .and_then(|value| value.trim().parse::<usize>().ok())
            .filter(|&value| value >= 1)
            .unwrap_or(DECODE_GEMV_LOOP_MAX_M_DEFAULT)
    })
}

const GEMV_F16_SMALL_THREADS: u32 = 64;
const GEMV_F16_LARGE_THREADS: u32 = 256;
const GEMV_F16_SMALL_N_MAX: usize = 1152;
/// Block-quantization size the down-projection tiling assumes. It stages the
/// activation as `K/8` permuted half8 vectors and indexes them as 4 `uint4` per
/// K-block (`block*4 .. block*4+3`), i.e. exactly 32 activation elements per
/// block, and it has **no** partial-block tail. So the variant is only correct
/// when `block_size == 32` and `K` is a whole multiple of 32.
const GEMV_F16_DOWN_BLOCK_SIZE: usize = 32;
const GEMV_F16_DOWN_THREADS: u32 = 256;
const GEMV_F16_DOWN_COLUMNS_PER_BLOCK: usize = 8;
const GATE_UP_SWIGLU_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_swiglu";
const GATE_UP_DECOMPOSED_SWIGLU_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu";
const GATE_UP_SWIGLU_RMSNORM_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm";
const GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm";
/// Asymmetric-zero-point specializations of the paired gate/up SwiGLU entries
/// (see [`GEMV_F16_SCALES_F16_ZP_ENTRY`] for the `HasZp` specialization scheme).
const GATE_UP_SWIGLU_ZP_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_swiglu_zp";
const GATE_UP_DECOMPOSED_SWIGLU_ZP_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_zp";
const GATE_UP_SWIGLU_RMSNORM_ZP_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_zp";
const GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_ZP_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm_zp";
/// Fused-symmetric (`ONNX_GENAI_GATEUP_VEC`) specializations of the four
/// SYMMETRIC paired gate/up SwiGLU entries. Byte-identical to the entries above
/// — the dequant folds the `- 8` symmetric zero point into the magic-bias
/// constants (see `int4x8_to_half2x4_sym8`), issuing four fewer `f16x2` ops per
/// weight word to relieve the issue-bound decode GEMV. Selected by
/// [`gate_up_vec_enabled`] (default-ON, byte-identical magic-bias-fold;
/// `ONNX_GENAI_GATEUP_VEC=0` forces scalar for A/B). The asymmetric `_zp` entries
/// have no `_vec` sibling: their per-block zero point cannot fold to a constant.
const GATE_UP_SWIGLU_VEC_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_swiglu_vec";
const GATE_UP_DECOMPOSED_SWIGLU_VEC_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_vec";
const GATE_UP_SWIGLU_RMSNORM_VEC_ENTRY: &str = "matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_vec";
const GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_VEC_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm_vec";
/// Occupancy-raised (`ONNX_GENAI_GATEUP_OCC`) siblings of the two SYMMETRIC
/// RMS-norm-fused `_vec` entries. Same kernel body + `__launch_bounds__(256, 8)`
/// (32 regs → 8 blocks/SM, 100% theoretical vs 75% register-limited) to hide the
/// Short-Scoreboard shared-load latency of the staged activation. Byte-identical
/// to the `_vec` entries (register-allocation hint only).
const GATE_UP_SWIGLU_RMSNORM_VEC_OCC_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_vec_occ";
const GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_VEC_OCC_ENTRY: &str =
    "matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm_vec_occ";
const GATE_UP_SWIGLU_THREADS: u32 = 256;

const DEQUANT_SRC: &str = r#"
extern "C" __global__ void matmul_nbits_dequant_f32(
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const int* group_indices,
    float* weight_kn,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int bits)
{
    const long total = (long)k * n;
    for (long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
         idx < total; idx += (long)gridDim.x * blockDim.x) {
        const int depth = (int)(idx / n);
        const int output = (int)(idx % n);
        const int block = depth / block_size;
        const int within = depth - block * block_size;
        const int bit_offset = within * bits;
        const unsigned char byte =
            packed[((long)output * k_blocks + block) * blob_size + bit_offset / 8];
        const int mask = bits == 8 ? 255 : ((1 << bits) - 1);
        const int quantized = (byte >> (bit_offset & 7)) & mask;
        const int group = group_indices ? group_indices[depth] : block;
        if (group < 0 || group >= k_blocks) {
            weight_kn[idx] = 0.0f;
            continue;
        }
        int zero_point = 1 << (bits - 1);
        if (zero_points) {
            const int zp_bit_offset = group * bits;
            const unsigned char zp =
                zero_points[(long)output * zp_row_bytes + zp_bit_offset / 8];
            zero_point = (zp >> (zp_bit_offset & 7)) & mask;
        }
        weight_kn[idx] =
            ((float)quantized - (float)zero_point) * scales[(long)output * k_blocks + group];
    }
}
"#;

const DEQUANT_F16_MODULE: &str = "matmul_nbits_dequant_f16";
const DEQUANT_F16_ENTRY: &str = "matmul_nbits_dequant_f16";

/// Half-precision dequantization feeding a cuBLASLt tensor-core GEMM.
///
/// The f32 dequant feeds a `CUDA_R_32F` cuBLASLt GEMM, which on A100 runs at the
/// 19.5 TFLOP/s FP32 rate. Materializing the weights as `__half` lets the same
/// GEMM run on tensor cores with f32 accumulation instead, and halves the
/// scratch buffer.
///
/// It writes `[N, K]` rather than the f32 path's `[K, N]`, and the GEMM
/// transposes it back. `[N, K]` is the order the weights are already packed in,
/// so a thread reads one aligned 32-bit word of eight nibbles and writes the
/// eight halves they expand to as one aligned 16-byte store, with the group's
/// scale and zero point loaded once for the whole word. The `[K, N]` order would
/// instead stride every packed read by a full quantized row.
///
/// Restricted to 4-bit weights whose block size is a multiple of 8 and a power
/// of two, so a word never straddles two groups and the group index is a shift.
/// Everything else keeps the general path.
const DEQUANT_F16_SRC: &str = r#"
#include <cuda_fp16.h>

// grid.x covers K/8 eight-weight words, grid.y one output column each.
extern "C" __global__ void matmul_nbits_dequant_f16(
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    __half* __restrict__ weight_nk,
    const int k,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int block_shift,
    const int scales_fp16)
{
    const int words = k >> 3;
    const int w = (int)(blockIdx.x * blockDim.x + threadIdx.x);
    if (w >= words) return;
    const int out = (int)blockIdx.y;

    const int depth0 = w << 3;
    const int block = depth0 >> block_shift;

    const long row_bytes = (long)k_blocks * blob_size;
    const unsigned codes =
        *reinterpret_cast<const unsigned*>(packed + (long)out * row_bytes + (long)w * 4);

    const long scale_idx = (long)out * k_blocks + block;
    const float scale = scales_fp16
        ? __half2float(reinterpret_cast<const __half*>(scales_raw)[scale_idx])
        : reinterpret_cast<const float*>(scales_raw)[scale_idx];

    float zero_point = 8.0f;
    if (zero_points) {
        const unsigned char byte = zero_points[(long)out * zp_row_bytes + (block >> 1)];
        zero_point = (float)((block & 1) ? (byte >> 4) : (byte & 15));
    }

    __half2 out2[4];
    #pragma unroll
    for (int i = 0; i < 4; ++i) {
        const float lo = (float)((codes >> (8 * i)) & 15) - zero_point;
        const float hi = (float)((codes >> (8 * i + 4)) & 15) - zero_point;
        out2[i] = __floats2half2_rn(lo * scale, hi * scale);
    }
    *reinterpret_cast<float4*>(weight_nk + (long)out * k + depth0) =
        *reinterpret_cast<const float4*>(out2);
}
"#;

const GEMV_SRC: &str = r#"
__device__ __forceinline__ float warp_sum(float value)
{
    for (int offset = 16; offset > 0; offset >>= 1) {
        value += __shfl_down_sync(0xffffffffu, value, offset);
    }
    return value;
}

__device__ __forceinline__ float block_sum(float value)
{
    __shared__ float warp_sums[32];
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;
    value = warp_sum(value);
    if (lane == 0) {
        warp_sums[warp] = value;
    }
    __syncthreads();
    value = threadIdx.x < ((blockDim.x + 31) >> 5) ? warp_sums[lane] : 0.0f;
    return warp == 0 ? warp_sum(value) : 0.0f;
}

// Model-agnostic fp32-activation int4/int8 decode GEMV supporting any
// power-of-two block_size. The int4 path is bit-for-bit identical to the
// original (nibble unpack, symmetric default 8, per-block-nibble zero points);
// the int8 branch reads one byte per weight, uses a symmetric default of 128,
// and reads one whole-byte zero point per block. The tuned block-32 int8 entry
// (`matmul_nbits_gemv_int8_f32`) bakes in the block-32 geometry; block sizes
// other than 32 route here so the block index derives from the real block_size.
extern "C" __global__ void matmul_nbits_gemv_f32(
    const float* activation,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int bits)
{
    const int column = (int)blockIdx.x;
    if (column >= n) {
        return;
    }

    float value = 0.0f;
    for (int depth = (int)threadIdx.x; depth < k; depth += (int)blockDim.x) {
        const int block = depth / block_size;
        const int within = depth - block * block_size;
        const long blob_base = ((long)column * k_blocks + block) * blob_size;
        int quantized;
        int zero_point;
        if (bits == 8) {
            quantized = (int)packed[blob_base + within];
            zero_point =
                zero_points ? (int)zero_points[(long)column * k_blocks + block] : 128;
        } else {
            const unsigned char byte = packed[blob_base + within / 2];
            quantized = (within & 1) ? (byte >> 4) : (byte & 15);
            zero_point = 8;
            if (zero_points) {
                const unsigned char zp =
                    zero_points[(long)column * zp_row_bytes + block / 2];
                zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
            }
        }
        value += activation[depth] * ((float)quantized - (float)zero_point)
            * scales[(long)column * k_blocks + block];
    }

    value = block_sum(value);
    if (threadIdx.x == 0) {
        output[column] = value + (bias ? bias[column] : 0.0f);
    }
}

extern "C" __global__ void matmul_nbits_gemv_int8_f32(
    const float* activation,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int k_blocks)
{
    const int column = (int)blockIdx.x;
    if (column >= n) {
        return;
    }

    float value = 0.0f;
    for (int depth = (int)threadIdx.x; depth < k; depth += (int)blockDim.x) {
        const int block = depth >> 5;
        const int within = depth & 31;
        const int quantized =
            (int)packed[((long)column * k_blocks + block) * 32 + within];
        const int zero_point =
            zero_points ? (int)zero_points[(long)column * k_blocks + block] : 128;
        value += activation[depth] * ((float)quantized - (float)zero_point)
            * scales[(long)column * k_blocks + block];
    }

    value = block_sum(value);
    if (threadIdx.x == 0) {
        output[column] = value + (bias ? bias[column] : 0.0f);
    }
}

// Structurally-selected int8 / block_size == 128 / asymmetric fp32-activation
// decode GEMV. This is a specialization of `matmul_nbits_gemv_f32` for the
// generic block-128 int8 loop that dominates Qwen3-0.6B decode. It is
// BIT-FOR-BIT IDENTICAL to that kernel: each thread walks the same depth stride
// (grid-stride by blockDim), evaluates the same per-element expression
// `activation * ((float)quantized - (float)zero_point) * scale`, and reduces in
// the same block_sum order — only the address arithmetic is cheaper.
//
// With block_size == 128 the block index is a shift (`depth >> 7`) instead of an
// integer divide, and the packed-byte address collapses: for blob_size == 128,
//   (column*k_blocks + block)*128 + (depth - block*128) == column*k_blocks*128 + depth,
// so `within` (the modulo) disappears entirely. The `column * k_blocks` base is
// hoisted once into `col_kb` for the scale and zero-point rows, and the runtime
// `bits == 8` branch of the generic kernel is gone. The `zero_points ? : 128`
// selection is retained (uniform across the CTA, effectively free) so the result
// stays identical whether or not zero points are present; dispatch restricts
// this entry to the asymmetric case in practice.
extern "C" __global__ void matmul_nbits_gemv_int8_f32_block128(
    const float* activation,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int k_blocks)
{
    const int column = (int)blockIdx.x;
    if (column >= n) {
        return;
    }

    const long col_kb = (long)column * k_blocks;
    const long packed_row = col_kb << 7;  // k_blocks * 128 bytes per weight row
    const float* col_scales = scales + col_kb;
    const unsigned char* col_zp = zero_points ? zero_points + col_kb : (const unsigned char*)0;

    float value = 0.0f;
    for (int depth = (int)threadIdx.x; depth < k; depth += (int)blockDim.x) {
        const int block = depth >> 7;
        const int quantized = (int)packed[packed_row + depth];
        const int zero_point = col_zp ? (int)col_zp[block] : 128;
        value += activation[depth] * ((float)quantized - (float)zero_point)
            * col_scales[block];
    }

    value = block_sum(value);
    if (threadIdx.x == 0) {
        output[column] = value + (bias ? bias[column] : 0.0f);
    }
}

// Int4 counterpart of the block-128 int8 specialization above. Each warp owns
// 32 consecutive depths, hence 16 aligned packed bytes. Four lanes load one
// aligned 32-bit word each and shuffle it to the eight lanes consuming its
// nibbles. This removes duplicate scalar byte loads without changing any
// thread's depth sequence or fp32 arithmetic.
extern "C" __global__ void matmul_nbits_gemv_int4_f32_block128(
    const float* activation,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int k_blocks)
{
    const int column = (int)blockIdx.x;
    if (column >= n) {
        return;
    }

    const int lane = (int)threadIdx.x & 31;
    const long col_kb = (long)column * k_blocks;
    const long packed_row = col_kb << 6;  // k_blocks * 64 bytes per weight row
    const float* col_scales = scales + col_kb;
    const unsigned char* col_zp =
        zero_points + (long)column * ((k_blocks + 1) >> 1);

    float value = 0.0f;
    for (int depth = (int)threadIdx.x; depth < k; depth += (int)blockDim.x) {
        const int block = depth >> 7;
        const int warp_depth = depth - lane;
        const unsigned int* packed_words =
            (const unsigned int*)(packed + packed_row + (warp_depth >> 1));
        unsigned int packed_word = lane < 4 ? packed_words[lane] : 0;
        packed_word = __shfl_sync(__activemask(), packed_word, lane >> 3);
        const int quantized = (int)((packed_word >> ((lane & 7) << 2)) & 15);
        const unsigned char zp_byte = col_zp[block >> 1];
        const int zero_point = (block & 1) ? (zp_byte >> 4) : (zp_byte & 15);
        value += activation[depth] * ((float)quantized - (float)zero_point)
            * col_scales[block];
    }

    value = block_sum(value);
    if (threadIdx.x == 0) {
        output[column] = value + (bias ? bias[column] : 0.0f);
    }
}

// Per-K-block (block-32) int8 activation quantization. One warp (CUDA block) owns
// one K-block and emits that block's own int8 scale, matching ORT/MLAS CompInt8
// and the CPU native path. A single per-row scale is dominated by activation
// outliers and rounds small in-block magnitudes to zero, flipping argmaxes on
// outlier-heavy models (e.g. Phi-3.5); per-block scales track fp32 faithfully.
extern "C" __global__ void matmul_nbits_quantize_accuracy4_block32(
    const float* activation,
    signed char* quantized_activation,
    float* activation_scale_out,
    const int k,
    const int padded_k)
{
    (void)padded_k;
    const int block = (int)blockIdx.x;
    const int lane = (int)threadIdx.x;
    const int depth = block * 32 + lane;
    const float value = (depth < k) ? activation[depth] : 0.0f;

    float max_abs = fabsf(value);
    for (int offset = 16; offset > 0; offset >>= 1) {
        max_abs = fmaxf(max_abs,
            __shfl_down_sync(0xffffffffu, max_abs, offset));
    }
    max_abs = __shfl_sync(0xffffffffu, max_abs, 0);

    const float activation_scale = max_abs == 0.0f ? 0.0f : max_abs / 127.0f;
    const float inverse_scale =
        activation_scale == 0.0f ? 0.0f : 1.0f / activation_scale;
    if (lane == 0) {
        activation_scale_out[block] = activation_scale;
    }
    int quantized = 0;
    if (depth < k && activation_scale != 0.0f) {
        quantized = (int)roundf(fminf(127.0f, fmaxf(-127.0f,
            value * inverse_scale)));
    }
    quantized_activation[depth] = (signed char)quantized;
}

__device__ __forceinline__ int unpack_int4x4(unsigned int packed, int offset)
{
    const int w0 = (int)((packed >> (offset + 0)) & 15u) - 8;
    const int w1 = (int)((packed >> (offset + 4)) & 15u) - 8;
    const int w2 = (int)((packed >> (offset + 8)) & 15u) - 8;
    const int w3 = (int)((packed >> (offset + 12)) & 15u) - 8;
    return (w0 & 255) | ((w1 & 255) << 8) | ((w2 & 255) << 16)
        | ((w3 & 255) << 24);
}

__device__ __forceinline__ int dot_int8x4(int lhs, int rhs, int accumulator)
{
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 610
    return __dp4a(lhs, rhs, accumulator);
#else
#pragma unroll
    for (int byte = 0; byte < 4; ++byte) {
        int lhs_value = ((unsigned int)lhs >> (byte * 8)) & 255u;
        int rhs_value = ((unsigned int)rhs >> (byte * 8)) & 255u;
        lhs_value = lhs_value >= 128 ? lhs_value - 256 : lhs_value;
        rhs_value = rhs_value >= 128 ? rhs_value - 256 : rhs_value;
        accumulator += lhs_value * rhs_value;
    }
    return accumulator;
#endif
}

extern "C" __global__ void matmul_nbits_gemv_accuracy4_block32(
    const signed char* quantized_activation,
    const float* activation_scale_ptr,
    const unsigned char* packed,
    const float* scales,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int k_blocks)
{
    extern __shared__ signed char activation_tile[];
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int column = (int)blockIdx.x * 8 + warp;

    float value = 0.0f;
    for (int tile_block = 0; tile_block < k_blocks; tile_block += 32) {
        const int tile_blocks = min(32, k_blocks - tile_block);
        const int tile_depths = tile_blocks * 32;
        for (int depth = tid; depth < tile_depths; depth += (int)blockDim.x) {
            activation_tile[depth] =
                quantized_activation[tile_block * 32 + depth];
        }
        __syncthreads();

        const int block = tile_block + lane;
        if (column < n && block < k_blocks) {
            const long packed_start = ((long)column * k_blocks + block) * 16;
            const uint4 packed_weights =
                *reinterpret_cast<const uint4*>(packed + packed_start);
            const unsigned int words[4] = {
                packed_weights.x, packed_weights.y, packed_weights.z, packed_weights.w
            };
            const signed char* activation_block = activation_tile + lane * 32;
            int dot = 0;
#pragma unroll
            for (int word = 0; word < 4; ++word) {
                const int activation0 =
                    *reinterpret_cast<const int*>(activation_block + word * 8);
                const int activation1 =
                    *reinterpret_cast<const int*>(activation_block + word * 8 + 4);
                dot = dot_int8x4(activation0, unpack_int4x4(words[word], 0), dot);
                dot = dot_int8x4(activation1, unpack_int4x4(words[word], 16), dot);
            }
            // Per-block int8 activation scale times the per-block weight scale.
            const float block_scale = __fmul_rn(
                activation_scale_ptr[block],
                scales[(long)column * k_blocks + block]);
            value = __fadd_rn(value, __fmul_rn((float)dot, block_scale));
        }
        __syncthreads();
    }

    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = bias ? __fadd_rn(value, bias[column]) : value;
    }
}

extern "C" __global__ void matmul_nbits_gemv_accuracy4_block32_stage64(
    const signed char* quantized_activation,
    const float* activation_scale_ptr,
    const unsigned char* packed,
    const float* scales,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int k_blocks)
{
    extern __shared__ signed char activation_tile[];
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int column = (int)blockIdx.x * 8 + warp;

    float value = 0.0f;
    for (int tile_block = 0; tile_block < k_blocks; tile_block += 64) {
        const int tile_blocks = min(64, k_blocks - tile_block);
        const int tile_depths = tile_blocks * 32;
        for (int depth = tid; depth < tile_depths; depth += (int)blockDim.x) {
            activation_tile[depth] =
                quantized_activation[tile_block * 32 + depth];
        }
        __syncthreads();

        for (int tile_offset = lane; tile_offset < tile_blocks; tile_offset += 32) {
            const int block = tile_block + tile_offset;
            if (column >= n) {
                continue;
            }
            const long packed_start = ((long)column * k_blocks + block) * 16;
            const uint4 packed_weights =
                *reinterpret_cast<const uint4*>(packed + packed_start);
            const unsigned int words[4] = {
                packed_weights.x, packed_weights.y, packed_weights.z, packed_weights.w
            };
            const signed char* activation_block = activation_tile + tile_offset * 32;
            int dot = 0;
#pragma unroll
            for (int word = 0; word < 4; ++word) {
                const int activation0 =
                    *reinterpret_cast<const int*>(activation_block + word * 8);
                const int activation1 =
                    *reinterpret_cast<const int*>(activation_block + word * 8 + 4);
                dot = dot_int8x4(activation0, unpack_int4x4(words[word], 0), dot);
                dot = dot_int8x4(activation1, unpack_int4x4(words[word], 16), dot);
            }
            const float block_scale = __fmul_rn(
                activation_scale_ptr[block],
                scales[(long)column * k_blocks + block]);
            value = __fadd_rn(value, __fmul_rn((float)dot, block_scale));
        }
        __syncthreads();
    }

    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = bias ? __fadd_rn(value, bias[column]) : value;
    }
}

// Per-K-block int8 activation quantization for ANY power-of-two block_size. One
// warp (CUDA block) owns one K-block and emits that block's own int8 scale,
// exactly matching the per-block quantization the tiled `matmul_nbits_accuracy4`
// reference performs inline (block_max / 127, symmetric round-to-nearest). The
// block-32 entry above hard-codes 32 lanes == 32 depths; this generalization
// strides each of the 32 lanes across the block so a single warp covers
// block_size (e.g. 128) depths. Padded tail depths (depth >= k in a partial
// final block) quantize to zero so they contribute nothing to the GEMV.
extern "C" __global__ void matmul_nbits_quantize_accuracy4_blockwise(
    const float* activation,
    signed char* quantized_activation,
    float* activation_scale_out,
    const int k,
    const int block_size,
    const int padded_k)
{
    (void)padded_k;
    const int block = (int)blockIdx.x;
    const int lane = (int)threadIdx.x;
    const int begin = block * block_size;

    float max_abs = 0.0f;
    for (int within = lane; within < block_size; within += 32) {
        const int depth = begin + within;
        const float value = (depth < k) ? activation[depth] : 0.0f;
        max_abs = fmaxf(max_abs, fabsf(value));
    }
    for (int offset = 16; offset > 0; offset >>= 1) {
        max_abs = fmaxf(max_abs,
            __shfl_down_sync(0xffffffffu, max_abs, offset));
    }
    max_abs = __shfl_sync(0xffffffffu, max_abs, 0);

    const float activation_scale = max_abs == 0.0f ? 0.0f : max_abs / 127.0f;
    const float inverse_scale =
        activation_scale == 0.0f ? 0.0f : 1.0f / activation_scale;
    if (lane == 0) {
        activation_scale_out[block] = activation_scale;
    }
    for (int within = lane; within < block_size; within += 32) {
        const int depth = begin + within;
        int quantized = 0;
        if (depth < k && activation_scale != 0.0f) {
            quantized = (int)roundf(fminf(127.0f, fmaxf(-127.0f,
                activation[depth] * inverse_scale)));
        }
        quantized_activation[depth] = (signed char)quantized;
    }
}

// General-block-size int4 accuracy_level=4 decode GEMV over the pre-quantized
// int8 activation. One warp reduces one output column; the 32 lanes cooperate
// across the block_size depths of each K-block. The per-block integer dot is
// computed as sum(qa * qw) - zero_point * sum(qa), which is exactly the tiled
// reference's sum(qa * (qw - zero_point)). Block-128 uses two packed dp4a
// instructions per lane (one for each integer sum) on sm_61+, while older
// architectures and other block sizes retain the scalar loop. Padded tail
// activations are zero, so packed tail lanes remain exact no-ops. The fp32 block
// products are then accumulated by lane 0 in ascending block order with the same
// __fmul_rn / __fadd_rn rounding the tiled kernel uses, so the result is bit-for-bit
// identical. Symmetric int4 uses the default zero point 8; asymmetric int4
// reads the packed per-block nibble zero point. The grid width (warps per CTA)
// is chosen host-side from the device multiprocessor count so the launch fills
// consumer and datacenter GPUs alike.
extern "C" __global__ void matmul_nbits_gemv_accuracy4_blockwise(
    const signed char* quantized_activation,
    const float* activation_scale_ptr,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const int k,
    const int n,
    const int k_blocks,
    const int block_size,
    const int blob_size,
    const int zp_row_bytes)
{
    (void)k;
    const int lane = (int)threadIdx.x & 31;
    const int warp = (int)threadIdx.x >> 5;
    const int column = (int)blockIdx.x * (int)(blockDim.x >> 5) + warp;
    if (column >= n) {
        return;
    }

    float value = 0.0f;
    for (int block = 0; block < k_blocks; ++block) {
        const int begin = block * block_size;
        const long blob_base = ((long)column * k_blocks + block) * blob_size;
        int weighted = 0;
        int activation_sum = 0;
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 610
        if (block_size == 128) {
            const int within = lane * 4;
            const int activation_pack = *reinterpret_cast<const int*>(
                quantized_activation + begin + within);
            const unsigned int packed_weights =
                (unsigned int)*reinterpret_cast<const unsigned short*>(
                    packed + blob_base + (within >> 1));
            const unsigned int even_weights = packed_weights & 0x0f0fu;
            const unsigned int odd_weights = (packed_weights >> 4) & 0x0f0fu;
            const unsigned int weight_pack =
                __byte_perm(even_weights, odd_weights, 0x5140);
            weighted = dot_int8x4(
                activation_pack, (int)weight_pack, weighted);
            activation_sum = dot_int8x4(
                activation_pack, 0x01010101, activation_sum);
        } else
#endif
        {
            for (int within = lane; within < block_size; within += 32) {
                const int quantized_activation_value =
                    (int)quantized_activation[begin + within];
                const unsigned char byte = packed[blob_base + (within >> 1)];
                const int quantized_weight =
                    (within & 1) ? (byte >> 4) : (byte & 15);
                weighted += quantized_activation_value * quantized_weight;
                activation_sum += quantized_activation_value;
            }
        }
        for (int offset = 16; offset > 0; offset >>= 1) {
            weighted += __shfl_down_sync(0xffffffffu, weighted, offset);
            activation_sum +=
                __shfl_down_sync(0xffffffffu, activation_sum, offset);
        }
        if (lane == 0) {
            int zero_point = 8;
            if (zero_points) {
                const unsigned char zp =
                    zero_points[(long)column * zp_row_bytes + (block >> 1)];
                zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
            }
            const int dot = weighted - zero_point * activation_sum;
            const float combined_scale = __fmul_rn(
                activation_scale_ptr[block],
                scales[(long)column * k_blocks + block]);
            value = __fadd_rn(value, __fmul_rn((float)dot, combined_scale));
        }
    }
    if (lane == 0) {
        output[column] = bias ? __fadd_rn(value, bias[column]) : value;
    }
}
"#;

const ACCURACY4_SRC: &str = r#"
extern "C" __global__ void matmul_nbits_accuracy4(
    const float* a,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* y,
    const int m,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    const long total = (long)m * n;
    for (long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;
         idx < total; idx += (long)gridDim.x * blockDim.x) {
        const int row = (int)(idx / n);
        const int output = (int)(idx % n);
        const float* activation = a + (long)row * k;

        // Per-K-block int8 activation quantization (block scale == the weight
        // block granularity), matching ORT/MLAS CompInt8 and the CPU native
        // path. A single per-row scale is dominated by activation outliers and
        // collapses small in-block magnitudes to zero, which flips argmaxes on
        // outlier-heavy models (e.g. Phi-3.5); per-block scales avoid that.
        float value = 0.0f;
        for (int block = 0; block < k_blocks; ++block) {
            const int begin = block * block_size;
            const int end = min(begin + block_size, k);
            float block_max = 0.0f;
            for (int depth = begin; depth < end; ++depth) {
                block_max = fmaxf(block_max, fabsf(activation[depth]));
            }
            if (block_max == 0.0f) {
                continue;
            }
            const float activation_scale = block_max / 127.0f;
            const float inverse_scale = 1.0f / activation_scale;
            int zero_point = 8;
            if (zero_points) {
                const unsigned char zp =
                    zero_points[(long)output * zp_row_bytes + block / 2];
                zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
            }
            int dot = 0;
            for (int depth = begin; depth < end; ++depth) {
                int quantized_activation =
                    (int)roundf(fminf(127.0f, fmaxf(-127.0f,
                        activation[depth] * inverse_scale)));
                const int within = depth - begin;
                const unsigned char byte =
                    packed[((long)output * k_blocks + block) * blob_size + within / 2];
                const int quantized_weight =
                    (within & 1) ? (byte >> 4) : (byte & 15);
                dot += quantized_activation * (quantized_weight - zero_point);
            }
            const float combined_scale = __fmul_rn(
                activation_scale,
                scales[(long)output * k_blocks + block]);
            value = __fadd_rn(value, __fmul_rn((float)dot, combined_scale));
        }
        y[idx] = bias ? __fadd_rn(value, bias[output]) : value;
    }
}
"#;

// Direct fp16-activation x packed-int4 GEMV (decode M=1). Unlike the
// accuracy_level=4 path this performs NO separate int8 activation-quantization
// pass. Packed nibbles are converted in registers and multiplied by fp16
// activations directly. The common fp16-scale path uses half2 accumulation,
// matching the storage precision before an fp32 warp reduction; f32 scales use
// fp32 block accumulation. Both paths round once more to fp16 on write.
const GEMV_F16_SRC: &str = r#"
#include <cuda_fp16.h>
#include <cuda_bf16.h>

// Narrowing store shared by the GEMV epilogues that can write their result
// straight into a bf16 consumer buffer instead of an fp16 staging buffer.
//
// `out_bf16` is a launch-uniform flag, so the branch costs one predicated
// select on the single lane that stores. The bf16 arm deliberately rounds
// fp32 -> fp16 -> bf16 rather than fp32 -> bf16 directly: the staging path it
// replaces rounds to fp16 in the GEMV and then casts that fp16 to bf16, and
// reproducing the double rounding is what keeps greedy decoding bit-identical.
__device__ __forceinline__ void matmul_nbits_store_narrowed(
    void* __restrict__ output, const int index, const __half value,
    const int out_bf16)
{
    if (out_bf16) {
        ((__nv_bfloat16*)output)[index] = __float2bfloat16(__half2float(value));
    } else {
        ((__half*)output)[index] = value;
    }
}

__device__ __forceinline__ float warp_sum(float value)
{
    for (int offset = 16; offset > 0; offset >>= 1) {
        value += __shfl_down_sync(0xffffffffu, value, offset);
    }
    return value;
}

// Fp16 GEMV bias epilogue. The fp32 accumulator is always rounded to fp16 for
// the base output. When a bias is present:
//   * `bias_post_round == 0` (native MatMulNBits bias): add in fp32 and round
//     once — `fp16(acc + bias)` — matching an ORT-style fused epilogue.
//   * `bias_post_round != 0` (a folded standalone `Add`): round the accumulator
//     to fp16 first, then add the fp16 bias with a second fp16 round —
//     `fp16(fp16(acc) + bias)` — reproducing the original two-op path so greedy
//     tokens stay byte-identical.
__device__ __forceinline__ __half fold_bias_f16(
    const float value,
    const __half* __restrict__ bias,
    const int column,
    const int bias_post_round)
{
    const __half rounded = __float2half(value);
    if (!bias) {
        return rounded;
    }
    const float b = __half2float(bias[column]);
    if (bias_post_round) {
        return __float2half(__half2float(rounded) + b);
    }
    return __float2half(value + b);
}

// One warp per output column. Block-32 INT8 stores one unsigned quantized
// weight byte per K element and one optional uint8 zero point per block.
extern "C" __global__ void matmul_nbits_gemv_int8_f16(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int scales_fp16,
    const int bias_post_round)
{
    // Mirrors the int4 `matmul_nbits_gemv_f16` work split: four adjacent lanes
    // cooperate on one block-32 column, eight blocks are consumed per warp step.
    // Each lane issues one aligned 8-byte packed-int8 load (uint2) and one 16-byte
    // activation load (uint4), then a four-lane shuffle reduction reconstructs the
    // block dot product before its scale is applied. This replaces the previous
    // one-byte-per-lane scalar walk that only advanced 32 K per warp step.
    const int lane = (int)threadIdx.x & 31;
    const int warp = (int)threadIdx.x >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;

    float value = 0.0f;
    if (column < n) {
        const int quarter = lane & 3;
        for (int block_base = 0; block_base < k_blocks; block_base += 8) {
            const int block = block_base + (lane >> 2);
            float block_partial = 0.0f;
            if (block < k_blocks) {
                const int zero_point =
                    zero_points ? (int)zero_points[(long)column * k_blocks + block] : 128;
                const int depth = block * 32 + quarter * 8;
                const long packed_start =
                    ((long)column * k_blocks + block) * 32 + quarter * 8;
                if (depth + 8 <= k) {
                    const uint2 packed_word =
                        *reinterpret_cast<const uint2*>(packed + packed_start);
                    const unsigned char* bytes =
                        reinterpret_cast<const unsigned char*>(&packed_word);
                    const uint4 act = *reinterpret_cast<const uint4*>(activation + depth);
                    const __half* acth = reinterpret_cast<const __half*>(&act);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        block_partial += ((float)(int)bytes[i] - (float)zero_point)
                            * __half2float(acth[i]);
                    }
                } else if (depth < k) {
                    const int valid = min(8, k - depth);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid) {
                            const int quantized = (int)packed[packed_start + i];
                            block_partial += ((float)quantized - (float)zero_point)
                                * __half2float(activation[depth + i]);
                        }
                    }
                }
            }
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 2, 4);
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 1, 4);
            if (quarter == 0 && block < k_blocks) {
                const float scale = scales_fp16
                    ? __half2float(reinterpret_cast<const __half*>(scales_raw)
                        [(long)column * k_blocks + block])
                    : reinterpret_cast<const float*>(scales_raw)
                        [(long)column * k_blocks + block];
                value += block_partial * scale;
            }
        }
    }
    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

// Split-K standalone int8 GEMV: K_SPLIT warps cooperate on one output column,
// each reducing a strided subset of the 8-block (256-wide) K steps, then summing
// their fp32 partials through shared memory. The launch grid is K_SPLIT x larger
// than the single-warp kernel, which fills the SMs on the grid-starved
// (~0.48 waves/SM) Phi int8 down-projection decode GEMV. This kernel has no
// serial prologue, so the added grid parallelism directly hides the
// Long-Scoreboard latency (unlike the fused RMSNorm-prologue int8 kernel, whose
// serial full-vector prologue caps any split-K benefit). The fp32 partial sum is
// a new block-sum association, so results are near-equal (not byte-identical) to
// the single-warp kernel; asymmetric-zp parity is validated against a dequant
// reference to tolerance. Requires K % 256 == 0 (whole steps, no divergent tail)
// — the launch only routes here in that case.
extern "C" __global__ void matmul_nbits_gemv_int8_f16_splitk(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int scales_fp16,
    const int bias_post_round)
{
    constexpr int K_SPLIT = 2;
    const int lane = (int)threadIdx.x & 31;
    const int warp = (int)threadIdx.x >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int cols_per_block = warps_per_block / K_SPLIT;
    const int col_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const int column = (int)blockIdx.x * cols_per_block + col_local;

    __shared__ float partials[8][K_SPLIT];

    float value = 0.0f;
    if (column < n) {
        const int quarter = lane & 3;
        for (int block_base = ks * 8; block_base < k_blocks;
             block_base += K_SPLIT * 8) {
            const int block = block_base + (lane >> 2);
            float block_partial = 0.0f;
            if (block < k_blocks) {
                const int zero_point =
                    zero_points ? (int)zero_points[(long)column * k_blocks + block] : 128;
                const int depth = block * 32 + quarter * 8;
                const long packed_start =
                    ((long)column * k_blocks + block) * 32 + quarter * 8;
                if (depth + 8 <= k) {
                    const uint2 packed_word =
                        *reinterpret_cast<const uint2*>(packed + packed_start);
                    const unsigned char* bytes =
                        reinterpret_cast<const unsigned char*>(&packed_word);
                    const uint4 act = *reinterpret_cast<const uint4*>(activation + depth);
                    const __half* acth = reinterpret_cast<const __half*>(&act);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        block_partial += ((float)(int)bytes[i] - (float)zero_point)
                            * __half2float(acth[i]);
                    }
                } else if (depth < k) {
                    const int valid = min(8, k - depth);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid) {
                            const int quantized = (int)packed[packed_start + i];
                            block_partial += ((float)quantized - (float)zero_point)
                                * __half2float(activation[depth + i]);
                        }
                    }
                }
            }
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 2, 4);
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 1, 4);
            if (quarter == 0 && block < k_blocks) {
                const float scale = scales_fp16
                    ? __half2float(reinterpret_cast<const __half*>(scales_raw)
                        [(long)column * k_blocks + block])
                    : reinterpret_cast<const float*>(scales_raw)
                        [(long)column * k_blocks + block];
                value += block_partial * scale;
            }
        }
    }
    value = warp_sum(value);
    if (lane == 0) {
        partials[col_local][ks] = (column < n) ? value : 0.0f;
    }
    __syncthreads();
    if (ks == 0 && lane == 0 && column < n) {
        float acc = 0.0f;
#pragma unroll
        for (int s = 0; s < K_SPLIT; ++s) {
            acc += partials[col_local][s];
        }
        output[column] = fold_bias_f16(acc, bias, column, bias_post_round);
    }
}
// block-32 activation/weight tile, so each packed weight is reused by up to 16
// prompt rows and each activation by up to 16 output columns. It deliberately
// uses only ordinary shared memory, fp32 arithmetic, and __half conversion:
// no tensor-core, async-copy, or architecture-specific PTX requirement.
extern "C" __global__ void matmul_nbits_gemm_f16(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int m,
    const int k,
    const int n,
    const int k_blocks,
    const int bits,
    const int scales_fp16,
    const int bias_post_round,
    const int bias_row_stride)
{
    __shared__ float activation_tile[16][32];
    __shared__ float weight_tile[32][16];
    const int tid = (int)threadIdx.y * 16 + (int)threadIdx.x;
    const int row = (int)blockIdx.y * 16 + (int)threadIdx.y;
    const int column = (int)blockIdx.x * 16 + (int)threadIdx.x;
    float value = 0.0f;

    for (int block = 0; block < k_blocks; ++block) {
#pragma unroll
        for (int load = tid; load < 16 * 32; load += 16 * 16) {
            const int tile_row = load >> 5;
            const int within = load & 31;
            const int depth = block * 32 + within;
            const int global_row = (int)blockIdx.y * 16 + tile_row;
            activation_tile[tile_row][within] =
                global_row < m && depth < k
                    ? __half2float(activation[(long)global_row * k + depth])
                    : 0.0f;
        }
#pragma unroll
        for (int load = tid; load < 32 * 16; load += 16 * 16) {
            const int tile_column = load >> 5;
            const int within = load & 31;
            const int global_column = (int)blockIdx.x * 16 + tile_column;
            const int depth = block * 32 + within;
            float weight = 0.0f;
            if (global_column < n && depth < k) {
                const long scale_index = (long)global_column * k_blocks + block;
                const float scale = scales_fp16
                    ? __half2float(
                        reinterpret_cast<const __half*>(scales_raw)[scale_index])
                    : reinterpret_cast<const float*>(scales_raw)[scale_index];
                int quantized;
                int zero_point;
                if (bits == 8) {
                    quantized = (int)packed[scale_index * 32 + within];
                    zero_point = zero_points ? (int)zero_points[scale_index] : 128;
                } else {
                    const unsigned char byte =
                        packed[scale_index * 16 + (within >> 1)];
                    quantized = (within & 1) ? (byte >> 4) : (byte & 15);
                    zero_point = 8;
                    if (zero_points) {
                        const int zp_row_bytes = (k_blocks + 1) >> 1;
                        const unsigned char zp =
                            zero_points[(long)global_column * zp_row_bytes + (block >> 1)];
                        zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
                    }
                }
                weight = ((float)quantized - (float)zero_point) * scale;
            }
            weight_tile[within][tile_column] = weight;
        }
        __syncthreads();

        if (row < m && column < n) {
#pragma unroll
            for (int within = 0; within < 32; ++within) {
                value += activation_tile[threadIdx.y][within]
                    * weight_tile[within][threadIdx.x];
            }
        }
        __syncthreads();
    }

    if (row < m && column < n) {
        // A folded residual epilogue binds a per-token residual (row stride N)
        // into the bias slot; a genuine broadcast bias keeps stride 0.
        const __half* row_bias = bias ? bias + (long)row * bias_row_stride : bias;
        output[(long)row * n + column] =
            fold_bias_f16(value, row_bias, column, bias_post_round);
    }
}

__device__ __forceinline__ void int4x8_to_half2x4_sub(
    const unsigned int packed,
    __half2* values,
    const unsigned int sub2)
{
    unsigned int* h = reinterpret_cast<unsigned int*>(values);
    constexpr unsigned int bottom_mask = 0x000f000f;
    constexpr unsigned int top_mask = 0x00f000f0;
    constexpr unsigned int fp16_magic = 0x64006400;
    constexpr unsigned int lop3_lut = (0xf0 & 0xcc) | 0xaa;
    const unsigned int top = packed >> 8;
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[0])
                 : "r"(packed), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[1])
                 : "r"(packed), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[2])
                 : "r"(top), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[3])
                 : "r"(top), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));

    constexpr unsigned int fp16_1024 = 0x64006400;
    constexpr unsigned int fp16_one_sixteenth = 0x2c002c00;
    constexpr unsigned int fp16_neg64 = 0xd400d400;
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[0]) : "r"(h[0]), "r"(fp16_1024));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[1])
                 : "r"(h[1]), "r"(fp16_one_sixteenth), "r"(fp16_neg64));
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[2]) : "r"(h[2]), "r"(fp16_1024));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[3])
                 : "r"(h[3]), "r"(fp16_one_sixteenth), "r"(fp16_neg64));
    // Center each nibble by subtracting the block zero point. A symmetric int4
    // weight uses the implicit `sub2 == 8` (fp16 0x48004800), which reproduces
    // the previous fixed `- 8` byte-for-byte; an asymmetric weight passes its
    // per-block zero point instead so the dequant is `(code - zp)`.
#pragma unroll
    for (int i = 0; i < 4; ++i) {
        asm volatile("sub.f16x2 %0, %1, %2;\n"
                     : "=r"(h[i]) : "r"(h[i]), "r"(sub2));
    }
}

// Symmetric int4 dequant: `(code - 8)` in fp16, byte-identical to the historical
// hard-coded `- 8` path (the `sub2` register just carries fp16 8.0).
__device__ __forceinline__ void int4x8_to_half2x4(
    const unsigned int packed,
    __half2* values)
{
    constexpr unsigned int fp16_eight = 0x48004800;
    int4x8_to_half2x4_sub(packed, values, fp16_eight);
}

// Fused symmetric int4 dequant: `(code - 8)` in fp16, emitting FOUR fewer
// `f16x2` ALU ops per packed word than [`int4x8_to_half2x4`] by folding the
// symmetric zero point (`- 8`) into the magic-bias-removal constants instead of
// issuing it as a separate trailing `sub.f16x2` per element pair.
//
// BYTE-IDENTICAL to `int4x8_to_half2x4` (the `- 8` path): every intermediate is
// an exactly-representable fp16 integer, so folding the two constant
// subtractions into one changes no rounding:
//   * bottom nibbles decode to `1024 + code` (exact in [1024, 1039]); the
//     original does `(x - 1024) - 8`, this does `x - 1032` — `1032 = 0x6408` is
//     exact and `(1024 + code) - 1032 = code - 8` with no intermediate rounding.
//   * top nibbles decode to `1024 + 16*code`; the original fma `x*(1/16) - 64`
//     yields the exact integer `code`, then `- 8`; this fuses to
//     `x*(1/16) - 72` (`72 = 0xD480` exact). `x*(1/16)` is an exact power-of-two
//     scale, so the single fma rounding lands on `code - 8` identically.
// This is a pure instruction-count reduction for the issue-bound symmetric
// paired gate/up decode GEMV — no reassociation, no math change.
__device__ __forceinline__ void int4x8_to_half2x4_sym8(
    const unsigned int packed,
    __half2* values)
{
    unsigned int* h = reinterpret_cast<unsigned int*>(values);
    constexpr unsigned int bottom_mask = 0x000f000f;
    constexpr unsigned int top_mask = 0x00f000f0;
    constexpr unsigned int fp16_magic = 0x64006400;
    constexpr unsigned int lop3_lut = (0xf0 & 0xcc) | 0xaa;
    const unsigned int top = packed >> 8;
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[0])
                 : "r"(packed), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[1])
                 : "r"(packed), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[2])
                 : "r"(top), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[3])
                 : "r"(top), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));

    // 1032 = 1024 (magic bias) + 8 (symmetric zero point); -72 = -64 - 8.
    constexpr unsigned int fp16_1032 = 0x64086408;
    constexpr unsigned int fp16_one_sixteenth = 0x2c002c00;
    constexpr unsigned int fp16_neg72 = 0xd480d480;
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[0]) : "r"(h[0]), "r"(fp16_1032));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[1])
                 : "r"(h[1]), "r"(fp16_one_sixteenth), "r"(fp16_neg72));
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[2]) : "r"(h[2]), "r"(fp16_1032));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[3])
                 : "r"(h[3]), "r"(fp16_one_sixteenth), "r"(fp16_neg72));
}

// Pack a scalar block zero point (nibble in [0, 15]) into an fp16x2 subtrahend
// for [`int4x8_to_half2x4_sub`].
__device__ __forceinline__ unsigned int int4_zero_point_sub2(const int zero_point)
{
    const __half zp = __float2half((float)zero_point);
    const __half2 zp2 = __halves2half2(zp, zp);
    return *reinterpret_cast<const unsigned int*>(&zp2);
}

// Load the block zero point for `column`/`block` from the packed nibble layout,
// or the symmetric default (8) when the weight carries no zero points.
__device__ __forceinline__ int int4_block_zero_point(
    const unsigned char* __restrict__ zero_points,
    const long column,
    const int block,
    const int zp_row_bytes)
{
    if (!zero_points) {
        return 8;
    }
    const unsigned char zp = zero_points[column * zp_row_bytes + (block >> 1)];
    return (block & 1) ? (zp >> 4) : (zp & 15);
}

// Compile-time-specialized per-block subtrahend for the vectorized int4 GEMVs.
// `HasZp == false` (symmetric weights) folds to the constant fp16 `8.0`
// subtrahend with no memory traffic, so the compiler emits the exact
// pre-zero-point instruction stream; `HasZp == true` reads the per-block
// asymmetric zero point. Keying off the template parameter — never the runtime
// pointer — keeps the symmetric decode path byte-identical and register-light.
template <bool HasZp>
__device__ __forceinline__ unsigned int block_sub2(
    const unsigned char* __restrict__ zero_points,
    const long column,
    const int block,
    const int zp_row_bytes)
{
    if (!HasZp) {
        return 0x48004800u;
    }
    return int4_zero_point_sub2(
        int4_block_zero_point(zero_points, column, block, zp_row_bytes));
}

// Scalar counterpart of [`block_sub2`] for the partial-block tail. `HasZp ==
// false` returns the symmetric default (8) with no load.
template <bool HasZp>
__device__ __forceinline__ int block_zp(
    const unsigned char* __restrict__ zero_points,
    const long column,
    const int block,
    const int zp_row_bytes)
{
    if (!HasZp) {
        return 8;
    }
    return int4_block_zero_point(zero_points, column, block, zp_row_bytes);
}

__device__ __forceinline__ float dot_int4x8_f16(
    const unsigned int packed,
    const __half* __restrict__ activation)
{
    const uint4 a = *reinterpret_cast<const uint4*>(activation);
    constexpr unsigned int low_halves = 0x5410;
    constexpr unsigned int high_halves = 0x7632;
    uint4 permuted;
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.x) : "r"(a.x), "r"(a.z), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.y) : "r"(a.x), "r"(a.z), "r"(high_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.z) : "r"(a.y), "r"(a.w), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.w) : "r"(a.y), "r"(a.w), "r"(high_halves));

    __half2 q[4];
    int4x8_to_half2x4(packed, q);
    const float2 q04 = __half22float2(q[0]);
    const float2 q15 = __half22float2(q[1]);
    const float2 q26 = __half22float2(q[2]);
    const float2 q37 = __half22float2(q[3]);
    const float2 a04 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.x));
    const float2 a15 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.y));
    const float2 a26 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.z));
    const float2 a37 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.w));
    float dot = q04.x * a04.x;
    dot += q15.x * a15.x;
    dot += q26.x * a26.x;
    dot += q37.x * a37.x;
    dot += q04.y * a04.y;
    dot += q15.y * a15.y;
    dot += q26.y * a26.y;
    dot += q37.y * a37.y;
    return dot;
}

// Zero-point-aware [`dot_int4x8_f16`]. `sub2` is the fp16x2 subtrahend for this
// block (the packed zero point, or fp16 8.0 for symmetric weights). Because the
// centered code `(code - zp)` is an exact fp16 integer in [-15, 15], converting
// each `q` to float and accumulating the eight products in fp32 in ascending
// element order reproduces the scalar `(float)(code - zp) * __half2float(act)`
// path byte-for-byte — the LOP3 unpack only changes *how* the nibbles are
// decoded, not the arithmetic that follows. With `sub2 == 0x48004800` this is
// identical to [`dot_int4x8_f16`].
__device__ __forceinline__ float dot_int4x8_f16_sub(
    const unsigned int packed,
    const __half* __restrict__ activation,
    const unsigned int sub2)
{
    const uint4 a = *reinterpret_cast<const uint4*>(activation);
    constexpr unsigned int low_halves = 0x5410;
    constexpr unsigned int high_halves = 0x7632;
    uint4 permuted;
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.x) : "r"(a.x), "r"(a.z), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.y) : "r"(a.x), "r"(a.z), "r"(high_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.z) : "r"(a.y), "r"(a.w), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.w) : "r"(a.y), "r"(a.w), "r"(high_halves));

    __half2 q[4];
    int4x8_to_half2x4_sub(packed, q, sub2);
    const float2 q04 = __half22float2(q[0]);
    const float2 q15 = __half22float2(q[1]);
    const float2 q26 = __half22float2(q[2]);
    const float2 q37 = __half22float2(q[3]);
    const float2 a04 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.x));
    const float2 a15 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.y));
    const float2 a26 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.z));
    const float2 a37 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.w));
    float dot = q04.x * a04.x;
    dot += q15.x * a15.x;
    dot += q26.x * a26.x;
    dot += q37.x * a37.x;
    dot += q04.y * a04.y;
    dot += q15.y * a15.y;
    dot += q26.y * a26.y;
    dot += q37.y * a37.y;
    return dot;
}

// Split of `dot_int4x8_f16_sub` into an activation-decode half and a
// weight-dot half so the decoded activation can be REUSED across several output
// columns (column register-blocking). `decode_activation8` converts the eight
// contiguous fp16 activations at `activation` into fp32, laid out in the exact
// summation order `dot_int4x8_f16_sub` consumes them (a04.x, a15.x, a26.x,
// a37.x, a04.y, a15.y, a26.y, a37.y). `dot_int4x8_f16_sub_act` then reproduces
// the identical 8-term fp32 dot for one weight sub-word. Because the fp16->fp32
// conversions and the add order are unchanged, the result is BIT-IDENTICAL to
// `dot_int4x8_f16_sub`; the only difference is the activation is decoded once
// and shared by all columns instead of re-loaded per column.
__device__ __forceinline__ void decode_activation8(
    const __half* __restrict__ activation,
    float* __restrict__ a /* [8] */)
{
    const uint4 av = *reinterpret_cast<const uint4*>(activation);
    constexpr unsigned int low_halves = 0x5410;
    constexpr unsigned int high_halves = 0x7632;
    uint4 permuted;
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.x) : "r"(av.x), "r"(av.z), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.y) : "r"(av.x), "r"(av.z), "r"(high_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.z) : "r"(av.y), "r"(av.w), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.w) : "r"(av.y), "r"(av.w), "r"(high_halves));
    const float2 a04 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.x));
    const float2 a15 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.y));
    const float2 a26 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.z));
    const float2 a37 = __half22float2(*reinterpret_cast<const __half2*>(&permuted.w));
    a[0] = a04.x;
    a[1] = a15.x;
    a[2] = a26.x;
    a[3] = a37.x;
    a[4] = a04.y;
    a[5] = a15.y;
    a[6] = a26.y;
    a[7] = a37.y;
}

__device__ __forceinline__ float dot_int4x8_f16_sub_act(
    const unsigned int packed,
    const float* __restrict__ a /* [8] */,
    const unsigned int sub2)
{
    __half2 q[4];
    int4x8_to_half2x4_sub(packed, q, sub2);
    const float2 q04 = __half22float2(q[0]);
    const float2 q15 = __half22float2(q[1]);
    const float2 q26 = __half22float2(q[2]);
    const float2 q37 = __half22float2(q[3]);
    float dot = q04.x * a[0];
    dot += q15.x * a[1];
    dot += q26.x * a[2];
    dot += q37.x * a[3];
    dot += q04.y * a[4];
    dot += q15.y * a[5];
    dot += q26.y * a[6];
    dot += q37.y * a[7];
    return dot;
}

// ---------------------------------------------------------------------------
// TRT-LLM-style interleaved + biased int4 -> fp16 decode (OPT-IN, symmetric).
//
// This is the runtime half of the `ONNX_GENAI_INTERLEAVE_DEQUANT` lever. It
// consumes weights that were **offline-interleaved** (nibbles of each 32-bit
// word rearranged from natural [e7 e6 e5 e4 | e3 e2 e1 e0] to the TRT-LLM
// [e7 e5 e3 e1 | e6 e4 e2 e0] order — even elements in the low four nibble
// slots, odd in the high four) by the host-side interleave pass. Given that
// layout, the SAME 4x LOP3 unpack that `int4x8_to_half2x4_sub` uses now emits
// the eight fp16 codes in NATURAL element order `{e0,e1},{e2,e3},{e4,e5},
// {e6,e7}`, so no `prmt.b32` activation reorder is needed downstream (the
// activation is consumed straight as contiguous __half2 pairs).
//
// It also folds the symmetric `-8` bias directly into the LOP3 magic-removal
// constants: the even lanes subtract 1032 (0x64086408 = 1024 + 8) and the odd
// lanes fma by 1/16 then subtract 72 (0xd480 = -(64 + 8)), so the converter
// yields `(code - 8)` in fp16 with NO trailing `sub.f16x2` loop. Total is
// 1 shift + 4 LOP3 + 2 sub.f16x2 + 2 fma.f16x2 = 9 instructions / 8 values.
//
// Correctness: for symmetric weights the previous path produces `(code - 8)` in
// fp16 via magic-removal followed by a `- 8` subtract; `(code - 8)` is an exact
// fp16 integer in [-8, 7], so this single-step form yields the byte-identical
// fp16 value. Because the eight products are then accumulated in fp32 in the
// same ascending element order (e0*a0, e1*a1, ..., e7*a7), the dot is
// BIT-IDENTICAL to `dot_int4x8_f16_sub` with `sub2 == fp16 8.0`.
__device__ __forceinline__ void int4x8_to_half2x4_interleaved_biased(
    const unsigned int packed,
    __half2* values)
{
    unsigned int* h = reinterpret_cast<unsigned int*>(values);
    constexpr unsigned int bottom_mask = 0x000f000f;
    constexpr unsigned int top_mask = 0x00f000f0;
    constexpr unsigned int fp16_magic = 0x64006400;
    constexpr unsigned int lop3_lut = (0xf0 & 0xcc) | 0xaa;
    const unsigned int top = packed >> 8;
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[0])
                 : "r"(packed), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[1])
                 : "r"(packed), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[2])
                 : "r"(top), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[3])
                 : "r"(top), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));

    // Fold the symmetric -8 bias into the magic-removal: even lanes hold
    // (1024 + code) and subtract 1032; odd lanes hold (1024 + 16*code) and
    // fma (*1/16 - 72), both yielding (code - 8) directly.
    constexpr unsigned int fp16_1032 = 0x64086408;
    constexpr unsigned int fp16_one_sixteenth = 0x2c002c00;
    constexpr unsigned int fp16_neg72 = 0xd480d480;
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[0]) : "r"(h[0]), "r"(fp16_1032));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[1])
                 : "r"(h[1]), "r"(fp16_one_sixteenth), "r"(fp16_neg72));
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[2]) : "r"(h[2]), "r"(fp16_1032));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[3])
                 : "r"(h[3]), "r"(fp16_one_sixteenth), "r"(fp16_neg72));
}

// Natural-order activation decode for the interleaved dequant path: the eight
// contiguous fp16 activations are converted to fp32 in ascending order with no
// `prmt.b32` reorder (the interleaved converter already emits the weights in
// natural element order). `a[i] == float(activation[i])`, matching the layout
// `decode_activation8` produces for the non-interleaved path.
__device__ __forceinline__ void decode_activation8_natural(
    const __half* __restrict__ activation,
    float* __restrict__ a /* [8] */)
{
    const uint4 av = *reinterpret_cast<const uint4*>(activation);
    const float2 a01 = __half22float2(*reinterpret_cast<const __half2*>(&av.x));
    const float2 a23 = __half22float2(*reinterpret_cast<const __half2*>(&av.y));
    const float2 a45 = __half22float2(*reinterpret_cast<const __half2*>(&av.z));
    const float2 a67 = __half22float2(*reinterpret_cast<const __half2*>(&av.w));
    a[0] = a01.x;
    a[1] = a01.y;
    a[2] = a23.x;
    a[3] = a23.y;
    a[4] = a45.x;
    a[5] = a45.y;
    a[6] = a67.x;
    a[7] = a67.y;
}

// Interleaved-weight sibling of `dot_int4x8_f16_sub_act`: the pre-decoded
// natural-order activation `a[8]` is dotted with the eight `(code - 8)` fp16
// weights from the biased interleaved converter, accumulated in fp32 in
// ascending element order. Bit-identical to `dot_int4x8_f16_sub_act` with
// `sub2 == fp16 8.0` on the non-interleaved layout of the same logical weights.
__device__ __forceinline__ float dot_int4x8_f16_interleaved_act(
    const unsigned int packed,
    const float* __restrict__ a /* [8] */)
{
    __half2 q[4];
    int4x8_to_half2x4_interleaved_biased(packed, q);
    const float2 q01 = __half22float2(q[0]);
    const float2 q23 = __half22float2(q[1]);
    const float2 q45 = __half22float2(q[2]);
    const float2 q67 = __half22float2(q[3]);
    float dot = q01.x * a[0];
    dot += q01.y * a[1];
    dot += q23.x * a[2];
    dot += q23.y * a[3];
    dot += q45.x * a[4];
    dot += q45.y * a[5];
    dot += q67.x * a[6];
    dot += q67.y * a[7];
    return dot;
}

// Interleaved-weight sibling of `dot_int4x8_f16_sub` (scalar-tail helper): loads
// the eight contiguous fp16 activations itself, then dots as above.
__device__ __forceinline__ float dot_int4x8_f16_interleaved(
    const unsigned int packed,
    const __half* __restrict__ activation)
{
    float a[8];
    decode_activation8_natural(activation, a);
    return dot_int4x8_f16_interleaved_act(packed, a);
}

// ---------------------------------------------------------------------------
// High-memory-level-parallelism (wide-load) int4 decode GEMV.
//
// The single-warp `..._general_bs` loop loads ONE 32-bit weight word (8 nibbles)
// per lane per step and immediately dequant+FMAs it — a dependent
// load->dequant->FMA chain that keeps ~1 weight load in flight per lane, so at
// M=1 (where the weight stream is the entire DRAM traffic) DRAM tops out ~19%
// while the SM pipe saturates on narrow-load issue. A head-to-head ncu of ORT's
// `MatMulFloatInt4Kernel` on the identical gate_up matrix showed it streams the
// same weights at 2.42 TB/s (50% DRAM) vs our 0.92 TB/s at the SAME grid/block/
// registers/occupancy — a pure memory-level-parallelism gap, not a math or
// tiling difference.
//
// This helper closes that gap: each lane owns 32 CONTIGUOUS nibbles per step and
// loads them with ONE 128-bit `uint4` weight load (4x fewer load instructions,
// 4x bytes/instruction), and the next step's `uint4` is issued BEFORE the
// current step's dequant/FMA so >=2 wide loads are always in flight to hide the
// ~10-cycle Long-Scoreboard global-load latency. It reuses the byte-tested LOP3
// dequant (`dot_int4x8_f16_sub`) on the four 8-nibble sub-words, so the
// per-element arithmetic is unchanged. NOT cp.async (pure issue overhead at M=1,
// proven regressing) and NOT a scalar `#pragma unroll` of the LOP3 body
// (register bloat -> occupancy cliff, proven regressing) — just wider
// synchronous vector loads at ~constant register footprint, the mechanism ORT
// uses.
//
// Numerics: the 32-wide lane interleave (vs the 8-wide single-warp interleave)
// regroups the fp32 partial sums, so the result is near-equal, NOT byte-
// identical, to `..._general_bs` — exactly the K-slice reassociation the split-K
// entries already ship by default. Each 32-nibble chunk lies inside ONE block
// (guarded to `block_size % 32 == 0`, i.e. glm block-128 and qwen block-32; the
// rare block-16 export falls back to the narrow kernel), so a single scale and
// zero point cover the chunk and the `uint4` load is 16-byte aligned.
//
// Returns this lane's fp32 partial (pre warp-reduction) for the weight column
// `column`, walking chunk starts `depth0, depth0+warp_stride, ...`.
// Read logical element `i` (0..7) from an INTERLEAVED 32-bit weight word. The
// offline interleave stores physical nibble slots as [e0,e2,e4,e6,e1,e3,e5,e7],
// so logical i maps to physical slot (i even ? i/2 : 4 + i/2). Used only by the
// interleaved GEMV's scalar tail; the main loop reads whole words via the LOP3
// converter.
__device__ __forceinline__ int interleaved_nibble(const unsigned int word, const int i)
{
    const int slot = (i & 1) ? (4 + (i >> 1)) : (i >> 1);
    return (int)((word >> (slot * 4)) & 15u);
}

__device__ __forceinline__ float gemv_int4_wide_lane_dot(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const int k,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const long column,
    const int depth0,
    const int warp_stride)
{
    const long col_kb = column * (long)k_blocks;

    float value = 0.0f;
    int depth = depth0;
    bool have = (depth + 32 <= k);
    uint4 w;
    if (have) {
        const int block = depth / block_size;
        const long blob_base = (col_kb + block) * (long)blob_size;
        const int within = depth - block * block_size;
        w = *reinterpret_cast<const uint4*>(packed + blob_base + (within >> 1));
    }
    while (have) {
        const int ndepth = depth + warp_stride;
        const bool have_next = (ndepth + 32 <= k);
        uint4 wn;
        if (have_next) {
            // Issue the next wide weight load before consuming the current one,
            // so two 128-bit loads are in flight across the dequant/FMA below.
            const int nblock = ndepth / block_size;
            const long nblob = (col_kb + nblock) * (long)blob_size;
            const int nwithin = ndepth - nblock * block_size;
            wn = *reinterpret_cast<const uint4*>(packed + nblob + (nwithin >> 1));
        }
        // `depth` is 32-aligned and `block_size % 32 == 0`, so `[depth, depth+32)`
        // is inside a single block: one scale + one zero point cover the chunk.
        const int block = depth / block_size;
        float scale;
        if (scales_fp16) {
            scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb + block]);
        } else {
            scale = reinterpret_cast<const float*>(scales)[col_kb + block];
        }
        const unsigned int sub2 =
            int4_zero_point_sub2(int4_block_zero_point(zero_points, column, block, zp_row_bytes));
        value += scale * dot_int4x8_f16_sub(w.x, activation + depth, sub2);
        value += scale * dot_int4x8_f16_sub(w.y, activation + depth + 8, sub2);
        value += scale * dot_int4x8_f16_sub(w.z, activation + depth + 16, sub2);
        value += scale * dot_int4x8_f16_sub(w.w, activation + depth + 24, sub2);
        depth = ndepth;
        w = wn;
        have = have_next;
    }

    // Partial trailing chunk for this lane (`depth < k < depth + 32`): decode the
    // valid 8-nibble sub-words, matching the narrow kernel's tail arithmetic.
    if (depth < k) {
        const int block = depth / block_size;
        float scale;
        if (scales_fp16) {
            scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb + block]);
        } else {
            scale = reinterpret_cast<const float*>(scales)[col_kb + block];
        }
        const int zero_point = int4_block_zero_point(zero_points, column, block, zp_row_bytes);
        const unsigned int sub2 = int4_zero_point_sub2(zero_point);
        const long blob_base = (col_kb + block) * (long)blob_size;
        for (int off = 0; off < 32 && depth + off < k; off += 8) {
            const int d = depth + off;
            const int within = d - block * block_size;
            const int valid = min(8, k - d);
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
            if (valid == 8) {
                value += scale * dot_int4x8_f16_sub(packed_word, activation + d, sub2);
            } else {
                float partial = 0.0f;
#pragma unroll
                for (int i = 0; i < 8; ++i) {
                    if (i < valid) {
                        const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                        partial += (float)q * __half2float(activation[d + i]);
                    }
                }
                value += partial * scale;
            }
        }
    }
    return value;
}

// Interleaved + biased (symmetric-only) sibling of `gemv_int4_wide_lane_dot`.
// Single-column wide-load lane dot that consumes offline-interleaved weights and
// folds the fixed symmetric `-8` bias inside the LOP3 converter (no per-block
// zero point, no `prmt.b32` activation reorder). The depth-2 software pipeline,
// the ascending sub-word order (w.x, w.y, w.z, w.w), and the fp32 accumulation
// order are byte-for-byte identical to `gemv_int4_wide_lane_dot` on symmetric
// weights, so each lane's fp32 partial is BIT-IDENTICAL. Used by the split-K
// wide interleaved kernel (the split-K partials therefore reduce to the same
// value as the non-interleaved split-K wide kernel).
__device__ __forceinline__ float gemv_int4_wide_lane_dot_interleaved(
   const __half* __restrict__ activation,
   const unsigned char* __restrict__ packed,
   const void* __restrict__ scales,
   const int k,
   const int block_size,
   const int k_blocks,
   const int blob_size,
   const int scales_fp16,
   const long column,
   const int depth0,
   const int warp_stride)
{
   const long col_kb = column * (long)k_blocks;

   float value = 0.0f;
   int depth = depth0;
   bool have = (depth + 32 <= k);
   uint4 w;
   if (have) {
       const int block = depth / block_size;
       const long blob_base = (col_kb + block) * (long)blob_size;
       const int within = depth - block * block_size;
       w = *reinterpret_cast<const uint4*>(packed + blob_base + (within >> 1));
   }
   while (have) {
       const int ndepth = depth + warp_stride;
       const bool have_next = (ndepth + 32 <= k);
       uint4 wn;
       if (have_next) {
           const int nblock = ndepth / block_size;
           const long nblob = (col_kb + nblock) * (long)blob_size;
           const int nwithin = ndepth - nblock * block_size;
           wn = *reinterpret_cast<const uint4*>(packed + nblob + (nwithin >> 1));
       }
       const int block = depth / block_size;
       float scale;
       if (scales_fp16) {
           scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb + block]);
       } else {
           scale = reinterpret_cast<const float*>(scales)[col_kb + block];
       }
       value += scale * dot_int4x8_f16_interleaved(w.x, activation + depth);
       value += scale * dot_int4x8_f16_interleaved(w.y, activation + depth + 8);
       value += scale * dot_int4x8_f16_interleaved(w.z, activation + depth + 16);
       value += scale * dot_int4x8_f16_interleaved(w.w, activation + depth + 24);
       depth = ndepth;
       w = wn;
       have = have_next;
   }

   if (depth < k) {
       const int block = depth / block_size;
       float scale;
       if (scales_fp16) {
           scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb + block]);
       } else {
           scale = reinterpret_cast<const float*>(scales)[col_kb + block];
       }
       const long blob_base = (col_kb + block) * (long)blob_size;
       for (int off = 0; off < 32 && depth + off < k; off += 8) {
           const int d = depth + off;
           const int within = d - block * block_size;
           const int valid = min(8, k - d);
           const unsigned int packed_word =
               *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
           if (valid == 8) {
               value += scale * dot_int4x8_f16_interleaved(packed_word, activation + d);
           } else {
               float partial = 0.0f;
#pragma unroll
               for (int i = 0; i < 8; ++i) {
                   if (i < valid) {
                       const int q = interleaved_nibble(packed_word, i) - 8;
                       partial += (float)q * __half2float(activation[d + i]);
                   }
               }
               value += partial * scale;
           }
       }
   }
   return value;
}

// Column register-blocked wide lane-dot: one warp accumulates WIDE_NC output
// columns at once. Each 8-element activation sub-word is decoded to fp32 ONCE
// (`decode_activation8`) and reused across all WIDE_NC columns, cutting the
// redundant activation L1 traffic (the head-to-head ncu limiter on the wide
// gate_up kernel was L1/TEX throughput, not DRAM) by ~WIDE_NC x, while the
// WIDE_NC independent 128-bit weight loads per chunk supply the memory-level
// parallelism that hides the Long-Scoreboard latency (replacing the depth-2
// software pipeline of the single-column `gemv_int4_wide_lane_dot`). The
// per-column `values[c] += scale * dot(sub-word)` sequence is byte-for-byte the
// same order as `gemv_int4_wide_lane_dot`, so each column's fp32 result is
// BIT-IDENTICAL to the single-column wide kernel (hence to the narrow kernel it
// already matches). `col_base` is this warp's first column; columns
// `col_base + c` beyond `n` are skipped.
#define WIDE_NC 4
__device__ __forceinline__ void gemv_int4_wide_lane_dot_multicol(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const int k,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const long col_base,
    const int n,
    const int depth0,
    const int warp_stride,
    float* __restrict__ values /* [WIDE_NC] */)
{
    bool valid[WIDE_NC];
    long col_kb[WIDE_NC];
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        values[c] = 0.0f;
        const long column = col_base + c;
        valid[c] = (column < n);
        col_kb[c] = column * (long)k_blocks;
    }

    int depth = depth0;
    while (depth + 32 <= k) {
        const int block = depth / block_size;
        const int within = depth - block * block_size;

        // Issue all WIDE_NC independent 128-bit weight loads up front so they are
        // in flight together (the load-level parallelism that hides load latency).
        uint4 w[WIDE_NC];
        float scale[WIDE_NC];
        unsigned int sub2[WIDE_NC];
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            const long base = (col_kb[c] + block) * (long)blob_size;
            w[c] = *reinterpret_cast<const uint4*>(packed + base + (within >> 1));
            if (scales_fp16) {
                scale[c] = __half2float(reinterpret_cast<const __half*>(scales)[col_kb[c] + block]);
            } else {
                scale[c] = reinterpret_cast<const float*>(scales)[col_kb[c] + block];
            }
            sub2[c] = int4_zero_point_sub2(
                int4_block_zero_point(zero_points, col_base + c, block, zp_row_bytes));
        }

        // Decode each 8-element activation sub-word once, reuse across columns.
        // Sub-word order 0..3 preserves the ascending-K accumulation of the
        // single-column kernel (w.x, w.y, w.z, w.w).
        float a8[8];
#pragma unroll
        for (int s = 0; s < 4; ++s) {
            decode_activation8(activation + depth + s * 8, a8);
#pragma unroll
            for (int c = 0; c < WIDE_NC; ++c) {
                if (!valid[c]) {
                    continue;
                }
                const unsigned int word =
                    (s == 0) ? w[c].x : (s == 1) ? w[c].y : (s == 2) ? w[c].z : w[c].w;
                values[c] += scale[c] * dot_int4x8_f16_sub_act(word, a8, sub2[c]);
            }
        }
        depth += warp_stride;
    }

    // Partial trailing chunk (`depth < k < depth + 32`): replicate the
    // single-column tail arithmetic per column.
    if (depth < k) {
        const int block = depth / block_size;
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            float scale;
            if (scales_fp16) {
                scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb[c] + block]);
            } else {
                scale = reinterpret_cast<const float*>(scales)[col_kb[c] + block];
            }
            const int zero_point =
                int4_block_zero_point(zero_points, col_base + c, block, zp_row_bytes);
            const unsigned int sub2 = int4_zero_point_sub2(zero_point);
            const long blob_base = (col_kb[c] + block) * (long)blob_size;
            for (int off = 0; off < 32 && depth + off < k; off += 8) {
                const int d = depth + off;
                const int within = d - block * block_size;
                const int valid_n = min(8, k - d);
                const unsigned int packed_word =
                    *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
                if (valid_n == 8) {
                    values[c] += scale * dot_int4x8_f16_sub(packed_word, activation + d, sub2);
                } else {
                    float partial = 0.0f;
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid_n) {
                            const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                            partial += (float)q * __half2float(activation[d + i]);
                        }
                    }
                    values[c] += partial * scale;
                }
            }
        }
    }
}

// Interleaved + biased (symmetric-only) sibling of
// `gemv_int4_wide_lane_dot_multicol`. Consumes offline-interleaved weights and
// applies the fixed symmetric `-8` bias inside the LOP3 converter, so there is
// no per-block zero point and no `prmt.b32` activation reorder. Every column's
// fp32 accumulation order is unchanged (ascending element order, sub-word order
// w.x, w.y, w.z, w.w), so each column result is BIT-IDENTICAL to
// `gemv_int4_wide_lane_dot_multicol` on symmetric weights.
__device__ __forceinline__ void gemv_int4_wide_lane_dot_multicol_interleaved(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const int k,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int scales_fp16,
    const long col_base,
    const int n,
    const int depth0,
    const int warp_stride,
    float* __restrict__ values /* [WIDE_NC] */)
{
    bool valid[WIDE_NC];
    long col_kb[WIDE_NC];
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        values[c] = 0.0f;
        const long column = col_base + c;
        valid[c] = (column < n);
        col_kb[c] = column * (long)k_blocks;
    }

    int depth = depth0;
    while (depth + 32 <= k) {
        const int block = depth / block_size;
        const int within = depth - block * block_size;

        uint4 w[WIDE_NC];
        float scale[WIDE_NC];
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            const long base = (col_kb[c] + block) * (long)blob_size;
            w[c] = *reinterpret_cast<const uint4*>(packed + base + (within >> 1));
            if (scales_fp16) {
                scale[c] = __half2float(reinterpret_cast<const __half*>(scales)[col_kb[c] + block]);
            } else {
                scale[c] = reinterpret_cast<const float*>(scales)[col_kb[c] + block];
            }
        }

        float a8[8];
#pragma unroll
        for (int s = 0; s < 4; ++s) {
            decode_activation8_natural(activation + depth + s * 8, a8);
#pragma unroll
            for (int c = 0; c < WIDE_NC; ++c) {
                if (!valid[c]) {
                    continue;
                }
                const unsigned int word =
                    (s == 0) ? w[c].x : (s == 1) ? w[c].y : (s == 2) ? w[c].z : w[c].w;
                values[c] += scale[c] * dot_int4x8_f16_interleaved_act(word, a8);
            }
        }
        depth += warp_stride;
    }

    if (depth < k) {
        const int block = depth / block_size;
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            float scale;
            if (scales_fp16) {
                scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb[c] + block]);
            } else {
                scale = reinterpret_cast<const float*>(scales)[col_kb[c] + block];
            }
            const long blob_base = (col_kb[c] + block) * (long)blob_size;
            for (int off = 0; off < 32 && depth + off < k; off += 8) {
                const int d = depth + off;
                const int within = d - block * block_size;
                const int valid_n = min(8, k - d);
                const unsigned int packed_word =
                    *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
                if (valid_n == 8) {
                    values[c] += scale * dot_int4x8_f16_interleaved(packed_word, activation + d);
                } else {
                    float partial = 0.0f;
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid_n) {
                            const int q = interleaved_nibble(packed_word, i) - 8;
                            partial += (float)q * __half2float(activation[d + i]);
                        }
                    }
                    values[c] += partial * scale;
                }
            }
        }
    }
}

// Decode eight contiguous fp16 activations into four `__half2` lanes laid out in
// the SAME element pairing that `int4x8_to_half2x4_sub` produces for the weights
// (`ah[i] = (a_i, a_{i+4})`), so `__hfma2(q[i], ah[i], acc)` multiplies matching
// (weight, activation) pairs. This is the fp16 sibling of `decode_activation8`:
// it stops at the permute step and keeps the halves packed (NO fp16->fp32
// conversion), because the fp16-mixed kernel consumes them directly in half2
// fused multiply-adds.
__device__ __forceinline__ void decode_activation8_h2(
    const __half* __restrict__ activation,
    __half2* __restrict__ ah /* [4] */)
{
    const uint4 av = *reinterpret_cast<const uint4*>(activation);
    constexpr unsigned int low_halves = 0x5410;
    constexpr unsigned int high_halves = 0x7632;
    uint4 permuted;
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.x) : "r"(av.x), "r"(av.z), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.y) : "r"(av.x), "r"(av.z), "r"(high_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.z) : "r"(av.y), "r"(av.w), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.w) : "r"(av.y), "r"(av.w), "r"(high_halves));
    ah[0] = *reinterpret_cast<const __half2*>(&permuted.x);
    ah[1] = *reinterpret_cast<const __half2*>(&permuted.y);
    ah[2] = *reinterpret_cast<const __half2*>(&permuted.z);
    ah[3] = *reinterpret_cast<const __half2*>(&permuted.w);
}

// ---------------------------------------------------------------------------
// fp16 mixed-precision column register-blocked wide GEMV.
//
// Identical column-register-blocking + wide-load structure as
// `gemv_int4_wide_lane_dot_multicol`, but the inner multiply-accumulate runs in
// fp16 `__hfma2` (two fused MACs per instruction) instead of fp32 FFMA. This is
// the ONLY way to actually cut the dequant/MAC ALU that limits the multicol
// kernel (fp32 FFMA is already one fused op, so a "fp16-multiply then
// fp32-add-every-product" scheme is strictly MORE ops and cannot win). ORT's
// `MatMulFloatInt4Kernel` is fp16 for exactly this reason, so this is the
// fp16-vs-fp16 equal-conditions path.
//
// PRECISION CONTRACT (matches ORT's `MatMulFloat4BitsKernelM1` exactly): the
// per-lane K reduction runs entirely in fp16 __half2 accumulators — each 32-term
// chunk is summed in fp16, its per-block scale is folded in with __hfma2, and the
// result accumulates into a per-column fp16 running `total`. fp32 is used ONLY in
// the final cross-lane `warp_sum` (the 5-step shuffle). This is safe because the
// fp16 accumulation is a WIDE, SHALLOW tree: with 32 lanes striding K by 32, each
// lane folds only ~K/1024 chunks (≈4 for K=4096, ≈13 for K=13696), and inside a
// chunk the __half2 holds two 16-deep lanes — a total fp16 depth of tens, not
// thousands, so mantissa loss is negligible. (A NAIVE deep single-accumulator
// fp16 sum of all K *does* lose mantissa and flip tokens — that is the trap this
// wide-tree layout avoids, and why ORT accumulates in fp16 throughout.) Because
// the arithmetic mirrors ORT's, the f64-oracle error lands in ORT's own error
// class; it is NOT byte-identical to the fp32 path, so it ships gated on accuracy
// (error <= ORT vs the f64 oracle), not on bit-identity.
__device__ __forceinline__ void gemv_int4_fp16_lane_dot_multicol(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const int k,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const long col_base,
    const int n,
    const int depth0,
    const int warp_stride,
    float* __restrict__ values /* [WIDE_NC] */)
{
    bool valid[WIDE_NC];
    long col_kb[WIDE_NC];
    // Per-column fp16 running total across the lane's chunks (ORT-style): the
    // per-block scale is folded into this __half2 accumulator with __hfma2, so
    // the entire per-lane K reduction stays in fp16 and only the final
    // cross-lane `warp_sum` runs in fp32. Matching ORT's arithmetic exactly puts
    // this kernel in the same error class as ORT's own int4 M=1 kernel. A single
    // fp16 accumulator is a *wide, shallow* reduction tree — each lane folds only
    // a handful of chunks (K / (32 lanes * 32) ≈ 4 for K=4096, ≈13 for K=13696),
    // so almost no mantissa is lost (this is why full-fp16 accumulate is
    // production-safe here, unlike a naive deep single-accumulator fp16 sum).
    __half2 total[WIDE_NC];
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        values[c] = 0.0f;
        total[c] = __float2half2_rn(0.0f);
        const long column = col_base + c;
        valid[c] = (column < n);
        col_kb[c] = column * (long)k_blocks;
    }

    int depth = depth0;
    while (depth + 32 <= k) {
        const int block = depth / block_size;
        const int within = depth - block * block_size;

        uint4 w[WIDE_NC];
        __half2 scale2[WIDE_NC];
        unsigned int sub2[WIDE_NC];
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            const long base = (col_kb[c] + block) * (long)blob_size;
            w[c] = *reinterpret_cast<const uint4*>(packed + base + (within >> 1));
            // Splat the per-block scale into both half lanes so it can be folded
            // into the fp16 accumulator with a single __hfma2.
            if (scales_fp16) {
                scale2[c] = __half2half2(reinterpret_cast<const __half*>(scales)[col_kb[c] + block]);
            } else {
                scale2[c] = __float2half2_rn(reinterpret_cast<const float*>(scales)[col_kb[c] + block]);
            }
            sub2[c] = int4_zero_point_sub2(
                int4_block_zero_point(zero_points, col_base + c, block, zp_row_bytes));
        }

        // fp16 accumulators for this chunk's 32 (unscaled) products, one per col.
        __half2 acc[WIDE_NC];
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            acc[c] = __float2half2_rn(0.0f);
        }

        // Decode each 8-element activation sub-word to half2 once, reuse across
        // columns (the multicol L1-traffic win), and fold it into every column's
        // fp16 accumulator with __hfma2 (2 fused MACs/instruction).
#pragma unroll
        for (int s = 0; s < 4; ++s) {
            __half2 ah[4];
            decode_activation8_h2(activation + depth + s * 8, ah);
#pragma unroll
            for (int c = 0; c < WIDE_NC; ++c) {
                if (!valid[c]) {
                    continue;
                }
                const unsigned int word =
                    (s == 0) ? w[c].x : (s == 1) ? w[c].y : (s == 2) ? w[c].z : w[c].w;
                __half2 q[4];
                int4x8_to_half2x4_sub(word, q, sub2[c]);
#pragma unroll
                for (int i = 0; i < 4; ++i) {
                    acc[c] = __hfma2(q[i], ah[i], acc[c]);
                }
            }
        }

        // Scale this chunk's fp16 partial by the block scale and fold it into the
        // fp16 running total (one __hfma2 per column) — fp32 is deferred to the
        // final cross-lane reduction.
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            total[c] = __hfma2(acc[c], scale2[c], total[c]);
        }
        depth += warp_stride;
    }

    // Collapse each column's fp16 running total to fp32 (the two half lanes are
    // the two halves of the dot product). The tail below adds into this in fp32.
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        values[c] = __low2float(total[c]) + __high2float(total[c]);
    }

    // Partial trailing chunk: compute in fp32 exactly like the fp32 multicol tail
    // so the K-tail stays precise (negligible perf, avoids fp16 edge cases).
    if (depth < k) {
        const int block = depth / block_size;
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            if (!valid[c]) {
                continue;
            }
            float scale;
            if (scales_fp16) {
                scale = __half2float(reinterpret_cast<const __half*>(scales)[col_kb[c] + block]);
            } else {
                scale = reinterpret_cast<const float*>(scales)[col_kb[c] + block];
            }
            const int zero_point =
                int4_block_zero_point(zero_points, col_base + c, block, zp_row_bytes);
            const unsigned int sub2 = int4_zero_point_sub2(zero_point);
            const long blob_base = (col_kb[c] + block) * (long)blob_size;
            for (int off = 0; off < 32 && depth + off < k; off += 8) {
                const int d = depth + off;
                const int within = d - block * block_size;
                const int valid_n = min(8, k - d);
                const unsigned int packed_word =
                    *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
                if (valid_n == 8) {
                    values[c] += scale * dot_int4x8_f16_sub(packed_word, activation + d, sub2);
                } else {
                    float partial = 0.0f;
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid_n) {
                            const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                            partial += (float)q * __half2float(activation[d + i]);
                        }
                    }
                    values[c] += partial * scale;
                }
            }
        }
    }
}

__device__ __forceinline__ uint4 permute_activation_f16x8(
    const __half* __restrict__ activation)
{
    const uint4 a = *reinterpret_cast<const uint4*>(activation);
    constexpr unsigned int low_halves = 0x5410;
    constexpr unsigned int high_halves = 0x7632;
    uint4 permuted;
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.x) : "r"(a.x), "r"(a.z), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.y) : "r"(a.x), "r"(a.z), "r"(high_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.z) : "r"(a.y), "r"(a.w), "r"(low_halves));
    asm volatile("prmt.b32 %0, %1, %2, %3;\n"
                 : "=r"(permuted.w) : "r"(a.y), "r"(a.w), "r"(high_halves));
    return permuted;
}

__device__ __forceinline__ void accumulate_int4x8_f16_permuted(
    const unsigned int packed,
    const uint4& activation,
    const __half scale,
    __half2& sum0,
    __half2& sum1,
    __half2& sum2,
    __half2& sum3)
{
    __half2 q[4];
    int4x8_to_half2x4(packed, q);
    const __half2 scale2 = __halves2half2(scale, scale);
    sum0 = __hfma2(
        __hmul2(q[0], scale2),
        *reinterpret_cast<const __half2*>(&activation.x),
        sum0);
    sum1 = __hfma2(
        __hmul2(q[1], scale2),
        *reinterpret_cast<const __half2*>(&activation.y),
        sum1);
    sum2 = __hfma2(
        __hmul2(q[2], scale2),
        *reinterpret_cast<const __half2*>(&activation.z),
        sum2);
    sum3 = __hfma2(
        __hmul2(q[3], scale2),
        *reinterpret_cast<const __half2*>(&activation.w),
        sum3);
}

// Zero-point-aware [`accumulate_int4x8_f16_permuted`]: `sub2` centers each
// nibble by the block zero point (fp16 8.0 for symmetric weights, giving a
// byte-identical result). Used by the paired gate/up kernels, which permute the
// shared activation once and dequant each projection with its own zero point.
__device__ __forceinline__ void accumulate_int4x8_f16_permuted_zp(
    const unsigned int packed,
    const uint4& activation,
    const __half scale,
    const unsigned int sub2,
    __half2& sum0,
    __half2& sum1,
    __half2& sum2,
    __half2& sum3)
{
    __half2 q[4];
    int4x8_to_half2x4_sub(packed, q, sub2);
    const __half2 scale2 = __halves2half2(scale, scale);
    sum0 = __hfma2(__hmul2(q[0], scale2),
                   *reinterpret_cast<const __half2*>(&activation.x), sum0);
    sum1 = __hfma2(__hmul2(q[1], scale2),
                   *reinterpret_cast<const __half2*>(&activation.y), sum1);
    sum2 = __hfma2(__hmul2(q[2], scale2),
                   *reinterpret_cast<const __half2*>(&activation.z), sum2);
    sum3 = __hfma2(__hmul2(q[3], scale2),
                   *reinterpret_cast<const __half2*>(&activation.w), sum3);
}

// Fused-symmetric [`accumulate_int4x8_f16_permuted_zp`]: identical multiply-add
// (same permuted activation, same `q * scale` fp16 FMA order into `sum0..3`) but
// dequants with [`int4x8_to_half2x4_sym8`], which folds the `- 8` symmetric zero
// point into the bias constants. The `q[i]` values are byte-identical to the
// `sub2 == 8` path, so the accumulation is bit-for-bit the same while issuing
// four fewer `f16x2` ops per word — the instruction-count win for the
// issue-bound paired gate/up decode GEMV.
__device__ __forceinline__ void accumulate_int4x8_f16_permuted_sym8(
    const unsigned int packed,
    const uint4& activation,
    const __half scale,
    __half2& sum0,
    __half2& sum1,
    __half2& sum2,
    __half2& sum3)
{
    __half2 q[4];
    int4x8_to_half2x4_sym8(packed, q);
    const __half2 scale2 = __halves2half2(scale, scale);
    sum0 = __hfma2(__hmul2(q[0], scale2),
                   *reinterpret_cast<const __half2*>(&activation.x), sum0);
    sum1 = __hfma2(__hmul2(q[1], scale2),
                   *reinterpret_cast<const __half2*>(&activation.y), sum1);
    sum2 = __hfma2(__hmul2(q[2], scale2),
                   *reinterpret_cast<const __half2*>(&activation.z), sum2);
    sum3 = __hfma2(__hmul2(q[3], scale2),
                   *reinterpret_cast<const __half2*>(&activation.w), sum3);
}

__device__ __forceinline__ void accumulate_int4x8_dot_f16(
    const unsigned int packed,
    const uint4& activation,
    const __half2 scale2,
    __half2& sum)
{
    __half2 q[4];
    int4x8_to_half2x4(packed, q);
    sum = __hfma2(
        __hmul2(q[0], scale2),
        *reinterpret_cast<const __half2*>(&activation.x),
        sum);
    sum = __hfma2(
        __hmul2(q[1], scale2),
        *reinterpret_cast<const __half2*>(&activation.y),
        sum);
    sum = __hfma2(
        __hmul2(q[2], scale2),
        *reinterpret_cast<const __half2*>(&activation.z),
        sum);
    sum = __hfma2(
        __hmul2(q[3], scale2),
        *reinterpret_cast<const __half2*>(&activation.w),
        sum);
}

__device__ __forceinline__ float dot_int4x32_f16_permuted_scaled(
    const uint4& packed,
    const uint4& activation0,
    const uint4& activation1,
    const uint4& activation2,
    const uint4& activation3,
    const __half scale)
{
    const __half2 scale2 = __halves2half2(scale, scale);
    __half2 sum0 = __float2half2_rn(0.0f);
    __half2 sum1 = __float2half2_rn(0.0f);
    __half2 sum2 = __float2half2_rn(0.0f);
    __half2 sum3 = __float2half2_rn(0.0f);
    accumulate_int4x8_dot_f16(packed.x, activation0, scale2, sum0);
    accumulate_int4x8_dot_f16(packed.y, activation1, scale2, sum1);
    accumulate_int4x8_dot_f16(packed.z, activation2, scale2, sum2);
    accumulate_int4x8_dot_f16(packed.w, activation3, scale2, sum3);
    const float2 value0 = __half22float2(sum0);
    const float2 value1 = __half22float2(sum1);
    const float2 value2 = __half22float2(sum2);
    const float2 value3 = __half22float2(sum3);
    float value = value0.x;
    value += value1.x;
    value += value2.x;
    value += value3.x;
    value += value0.y;
    value += value1.y;
    value += value2.y;
    value += value3.y;
    return value;
}

__device__ __forceinline__ void accumulate_int4x8_f16(
    const unsigned int packed,
    const __half* __restrict__ activation,
    const __half scale,
    __half2& sum0,
    __half2& sum1,
    __half2& sum2,
    __half2& sum3)
{
    const uint4 permuted = permute_activation_f16x8(activation);
    accumulate_int4x8_f16_permuted(
        packed, permuted, scale, sum0, sum1, sum2, sum3);
}

// Zero-point-aware variant of [`accumulate_int4x8_f16`]: `sub2` is the fp16x2
// subtrahend for this block (the packed zero point, or fp16 8.0 for symmetric
// weights). With the symmetric default this is byte-identical to the plain
// accumulate, so callers can route both symmetric and asymmetric weights here.
__device__ __forceinline__ void accumulate_int4x8_f16_zp(
    const unsigned int packed,
    const __half* __restrict__ activation,
    const __half scale,
    const unsigned int sub2,
    __half2& sum0,
    __half2& sum1,
    __half2& sum2,
    __half2& sum3)
{
    const uint4 permuted = permute_activation_f16x8(activation);
    __half2 q[4];
    int4x8_to_half2x4_sub(packed, q, sub2);
    const __half2 scale2 = __halves2half2(scale, scale);
    sum0 = __hfma2(__hmul2(q[0], scale2),
                   *reinterpret_cast<const __half2*>(&permuted.x), sum0);
    sum1 = __hfma2(__hmul2(q[1], scale2),
                   *reinterpret_cast<const __half2*>(&permuted.y), sum1);
    sum2 = __hfma2(__hmul2(q[2], scale2),
                   *reinterpret_cast<const __half2*>(&permuted.z), sum2);
    sum3 = __hfma2(__hmul2(q[3], scale2),
                   *reinterpret_cast<const __half2*>(&permuted.w), sum3);
}

// Debias-then-scale int4 dequant (fold-scale). Recovers the exact integer code
// in fp16 (the same 1024/64 lop3-bias removal as `int4x8_to_half2x4_sub`, which
// is fp16-exact for codes 0..15 so there is no catastrophic cancellation), then
// folds the per-block scale AND zero point into ONE `fma` per pair:
// `(code - zp) * scale = fma(code, scale2, neg_zp_scale2)`. This lets the MAC
// drop its separate `__hmul2(q, scale)`, removing 4 fp16x2 multiplies per 8
// weights on the ALU-co-bound (measured 65% pipe) M=1 decode GEMV.
__device__ __forceinline__ void int4x8_to_half2x4_scaledsub(
    const unsigned int packed,
    __half2* values,
    const unsigned int scale2,
    const unsigned int neg_zp_scale2)
{
    unsigned int* h = reinterpret_cast<unsigned int*>(values);
    constexpr unsigned int bottom_mask = 0x000f000f;
    constexpr unsigned int top_mask = 0x00f000f0;
    constexpr unsigned int fp16_magic = 0x64006400;
    constexpr unsigned int lop3_lut = (0xf0 & 0xcc) | 0xaa;
    const unsigned int top = packed >> 8;
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[0])
                 : "r"(packed), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[1])
                 : "r"(packed), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[2])
                 : "r"(top), "n"(bottom_mask), "n"(fp16_magic), "n"(lop3_lut));
    asm volatile("lop3.b32 %0, %1, %2, %3, %4;\n"
                 : "=r"(h[3])
                 : "r"(top), "n"(top_mask), "n"(fp16_magic), "n"(lop3_lut));
    constexpr unsigned int fp16_1024 = 0x64006400;
    constexpr unsigned int fp16_one_sixteenth = 0x2c002c00;
    constexpr unsigned int fp16_neg64 = 0xd400d400;
    // Debias to the exact integer code first (fp16-exact for 0..15).
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[0]) : "r"(h[0]), "r"(fp16_1024));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[1])
                 : "r"(h[1]), "r"(fp16_one_sixteenth), "r"(fp16_neg64));
    asm volatile("sub.f16x2 %0, %1, %2;\n"
                 : "=r"(h[2]) : "r"(h[2]), "r"(fp16_1024));
    asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                 : "=r"(h[3])
                 : "r"(h[3]), "r"(fp16_one_sixteenth), "r"(fp16_neg64));
    // Fold `(code - zp) * scale` into one fma per pair (replaces the standalone
    // zp-subtract here and the `__hmul2(q, scale)` in the MAC).
#pragma unroll
    for (int i = 0; i < 4; ++i) {
        asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n"
                     : "=r"(h[i]) : "r"(h[i]), "r"(scale2), "r"(neg_zp_scale2));
    }
}

// per CTA. Four adjacent lanes split each block-32 weight blob into aligned
// uint32 loads, so every warp issues contiguous 128-byte packed-weight
// transactions. Each lane also reads eight activations with one uint4 load.
// Register-only nibble conversion and four-lane shuffle reduction reconstruct
// each block dot product before applying its scale.
extern "C" __global__ void matmul_nbits_gemv_f16(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;

    float value = 0.0f;
    if (column < n) {
        const int quarter = lane & 3;
        for (int block_base = 0; block_base < k_blocks; block_base += 8) {
            const int block = block_base + (lane >> 2);
            float block_partial = 0.0f;
            if (block < k_blocks) {
                const int depth = block * block_size + quarter * 8;
                const long packed_start =
                    ((long)column * k_blocks + block) * blob_size + quarter * 4;
                const unsigned int packed_word =
                    *reinterpret_cast<const unsigned int*>(packed + packed_start);
                int zero_point = 8;
                if (zero_points) {
                    const unsigned char zp =
                        zero_points[(long)column * zp_row_bytes + block / 2];
                    zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
                }
                if (depth + 8 <= k) {
                    if (zero_points) {
#pragma unroll
                        for (int i = 0; i < 8; ++i) {
                            const int q =
                                (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                            block_partial +=
                                (float)q * __half2float(activation[depth + i]);
                        }
                    } else {
                        block_partial = dot_int4x8_f16(packed_word, activation + depth);
                    }
                } else if (depth < k) {
                    const int valid = min(8, k - depth);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid) {
                            const int q =
                                (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                            block_partial +=
                                (float)q * __half2float(activation[depth + i]);
                        }
                    }
                }
            }
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 2, 4);
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 1, 4);
            if (quarter == 0 && block < k_blocks) {
                float scale;
                if (scales_fp16) {
                    scale = __half2float(
                        reinterpret_cast<const __half*>(scales)[(long)column * k_blocks + block]);
                } else {
                    scale =
                        reinterpret_cast<const float*>(scales)[(long)column * k_blocks + block];
                }
                value += block_partial * scale;
            }
        }
    }

    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

template <bool HasZp>
__device__ __forceinline__ void matmul_nbits_gemv_f16_scales_f16_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    (void)block_size;
    (void)scales_fp16;
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column_base = (int)blockIdx.x * columns_per_block;
    const int column = column_base + warp;

    __half2 sum0 = __float2half2_rn(0.0f);
    __half2 sum1 = __float2half2_rn(0.0f);
    __half2 sum2 = __float2half2_rn(0.0f);
    __half2 sum3 = __float2half2_rn(0.0f);
    float tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        const __half* activation_ptr = activation + lane_depth;
        const unsigned char* packed_ptr =
            packed + (long)column * k_blocks * blob_size + lane * 4;
        const __half* scale_ptr =
            scales + (long)column * k_blocks + (lane >> 2);
        int depth_base = 0;
        for (; depth_base + lane_depth + 8 <= k; depth_base += 256) {
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed_ptr);
            // block == depth/32; each lane's 8 nibbles all sit in one block.
            const int block = (depth_base >> 5) + (lane >> 2);
            const unsigned int sub2 =
                block_sub2<HasZp>(zero_points, column, block, zp_row_bytes);
            accumulate_int4x8_f16_zp(
                packed_word,
                activation_ptr,
                *scale_ptr,
                sub2,
                sum0,
                sum1,
                sum2,
                sum3);
            activation_ptr += 256;
            packed_ptr += 128;
            scale_ptr += 8;
        }
        const int tail_depth = depth_base + lane_depth;
        if (tail_depth < k) {
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed_ptr);
            const float scale = __half2float(*scale_ptr);
            const int tail_block = (depth_base >> 5) + (lane >> 2);
            const int zero_point =
                block_zp<HasZp>(zero_points, column, tail_block, zp_row_bytes);
            const int valid = min(8, k - tail_depth);
#pragma unroll
            for (int i = 0; i < 8; ++i) {
                if (i < valid) {
                    const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                    tail += (float)q * __half2float(activation_ptr[i]) * scale;
                }
            }
        }
    }
    const float2 value04 = __half22float2(sum0);
    const float2 value15 = __half22float2(sum1);
    const float2 value26 = __half22float2(sum2);
    const float2 value37 = __half22float2(sum3);
    float value = tail + value04.x;
    value += value15.x;
    value += value26.x;
    value += value37.x;
    value += value04.y;
    value += value15.y;
    value += value26.y;
    value += value37.y;
    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    matmul_nbits_gemv_f16_scales_f16_tpl<false>(activation, packed, scales_raw, zero_points, bias, output, k, n, block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16, bias_post_round);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    matmul_nbits_gemv_f16_scales_f16_tpl<true>(activation, packed, scales_raw, zero_points, bias, output, k, n, block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16, bias_post_round);
}


// Prefetch-pipelined sibling of `matmul_nbits_gemv_f16_scales_f16_tpl`.
// The single-warp scales-fp16 GEMV is Long-Scoreboard bound: ncu on qwen2.5-14b
// q/o (N=5120) shows ~8.9 active warps/scheduler but only ~0.97 eligible, with
// ~75% of warp cycles stalled waiting for the one in-flight 32-bit weight load.
// The math is not the bottleneck (SM ~41%, DRAM ~24% of an H200's 4.8 TB/s).
//
// This variant keeps the EXACT same lane->nibble mapping (lane owns 8 contiguous
// nibbles at stride 256), the same fp16 `accumulate_int4x8_f16_zp` calls, and the
// same accumulation order — so its output is BYTE-IDENTICAL to the single-warp
// kernel. The only change is memory-level parallelism: a depth-PF register shift
// register holds PF prefetched weight words so PF independent global loads are in
// flight per lane, hiding the ~13-cycle load latency instead of stalling on it.
// Register-resident (manual rotation, no dynamic-indexed array -> no local spill).
template <bool HasZp>
__device__ __forceinline__ void matmul_nbits_gemv_f16_scales_f16_pipe_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    (void)block_size;
    (void)scales_fp16;
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column_base = (int)blockIdx.x * columns_per_block;
    const int column = column_base + warp;

    __half2 sum0 = __float2half2_rn(0.0f);
    __half2 sum1 = __float2half2_rn(0.0f);
    __half2 sum2 = __float2half2_rn(0.0f);
    __half2 sum3 = __float2half2_rn(0.0f);
    float tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        const __half* activation_ptr = activation + lane_depth;
        const unsigned char* packed_ptr =
            packed + (long)column * k_blocks * blob_size + lane * 4;
        const __half* scale_ptr =
            scales + (long)column * k_blocks + (lane >> 2);
        // Number of full 8-nibble steps this lane walks (step s is valid iff
        // s * 256 + lane_depth + 8 <= k), identical to the scalar loop bound.
        const int nfull = (lane_depth + 8 <= k) ? ((k - lane_depth - 8) / 256 + 1) : 0;

        // Load the k-th step's weight word (step stride is 128 packed bytes).
        auto load_step = [&](int s) -> unsigned int {
            return *reinterpret_cast<const unsigned int*>(packed_ptr + (long)s * 128);
        };
        // Prime the shift register with the first PF steps' words (independent
        // loads -> they pipeline). Out-of-range slots are zero (never consumed).
        // The array is `#pragma unroll`-rotated with a compile-time `PF`, so it
        // stays fully in registers (no dynamic indexing -> no local spill).
        constexpr int PF = 2;  // prefetch depth (weight words in flight per lane)
        unsigned int wbuf[PF];
#pragma unroll
        for (int s = 0; s < PF; ++s) {
            wbuf[s] = (s < nfull) ? load_step(s) : 0u;
        }

        int depth_base = 0;
        for (int i = 0; i < nfull; ++i, depth_base += 256) {
            const unsigned int packed_word = wbuf[0];
            // Rotate the shift register and issue the load PF steps ahead BEFORE
            // consuming the current word, so PF loads stay in flight.
            const int pf = i + PF;
#pragma unroll
            for (int s = 0; s < PF - 1; ++s) {
                wbuf[s] = wbuf[s + 1];
            }
            wbuf[PF - 1] = (pf < nfull) ? load_step(pf) : 0u;

            const int block = (depth_base >> 5) + (lane >> 2);
            const unsigned int sub2 =
                block_sub2<HasZp>(zero_points, column, block, zp_row_bytes);
            accumulate_int4x8_f16_zp(
                packed_word, activation_ptr, *scale_ptr, sub2, sum0, sum1, sum2, sum3);
            activation_ptr += 256;
            scale_ptr += 8;
        }
        const int tail_depth = depth_base + lane_depth;
        if (tail_depth < k) {
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed_ptr + (long)nfull * 128);
            const float scale = __half2float(*scale_ptr);
            const int tail_block = (depth_base >> 5) + (lane >> 2);
            const int zero_point =
                block_zp<HasZp>(zero_points, column, tail_block, zp_row_bytes);
            const int valid = min(8, k - tail_depth);
#pragma unroll
            for (int i = 0; i < 8; ++i) {
                if (i < valid) {
                    const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                    tail += (float)q * __half2float(activation_ptr[i]) * scale;
                }
            }
        }
    }
    const float2 value04 = __half22float2(sum0);
    const float2 value15 = __half22float2(sum1);
    const float2 value26 = __half22float2(sum2);
    const float2 value37 = __half22float2(sum3);
    float value = tail + value04.x;
    value += value15.x;
    value += value26.x;
    value += value37.x;
    value += value04.y;
    value += value15.y;
    value += value26.y;
    value += value37.y;
    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_pipe(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    matmul_nbits_gemv_f16_scales_f16_pipe_tpl<false>(activation, packed, scales_raw, zero_points, bias, output, k, n, block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16, bias_post_round);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_zp_pipe(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    matmul_nbits_gemv_f16_scales_f16_pipe_tpl<true>(activation, packed, scales_raw, zero_points, bias, output, k, n, block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16, bias_post_round);
}
// each reducing a strided subset of the 256-wide K steps, then summing their
// fp32 partials through shared memory. The launch grid is K_SPLIT x larger than
// the single-warp `_zp` kernel, which fills the SMs on this grid-starved,
// latency-bound decode GEMV. The fp32 partial sum is a new block-sum
// association, so results are near-equal (not byte-identical) to the
// single-warp kernel.
template <bool HasZp, int K_SPLIT>
__device__ __forceinline__ void matmul_nbits_gemv_f16_scales_f16_splitk_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    (void)block_size;
    (void)scales_fp16;
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int cols_per_block = warps_per_block / K_SPLIT;
    const int col_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const int column = (int)blockIdx.x * cols_per_block + col_local;

    __shared__ float partials[8][K_SPLIT];

    __half2 sum0 = __float2half2_rn(0.0f);
    __half2 sum1 = __float2half2_rn(0.0f);
    __half2 sum2 = __float2half2_rn(0.0f);
    __half2 sum3 = __float2half2_rn(0.0f);
    float tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        int depth_base = ks * 256;
        const __half* activation_ptr = activation + depth_base + lane_depth;
        const unsigned char* packed_ptr =
            packed + (long)column * k_blocks * blob_size +
            (long)(depth_base >> 5) * blob_size + lane * 4;
        const __half* scale_ptr =
            scales + (long)column * k_blocks + (depth_base >> 5) + (lane >> 2);
        for (; depth_base < k; depth_base += K_SPLIT * 256) {
            const int depth = depth_base + lane_depth;
            if (depth >= k) {
                activation_ptr += K_SPLIT * 256;
                packed_ptr += K_SPLIT * 128;
                scale_ptr += K_SPLIT * 8;
                continue;
            }
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed_ptr);
            const int block = (depth_base >> 5) + (lane >> 2);
            const unsigned int sub2 =
                block_sub2<HasZp>(zero_points, column, block, zp_row_bytes);
            if (depth + 8 <= k) {
                accumulate_int4x8_f16_zp(
                    packed_word, activation_ptr, *scale_ptr, sub2, sum0, sum1, sum2, sum3);
            } else {
                const float scale = __half2float(*scale_ptr);
                const int zero_point =
                    block_zp<HasZp>(zero_points, column, block, zp_row_bytes);
                const int valid = k - depth;
#pragma unroll
                for (int i = 0; i < 8; ++i) {
                    if (i < valid) {
                        const int q =
                            (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                        tail += (float)q * __half2float(activation_ptr[i]) * scale;
                    }
                }
            }
            activation_ptr += K_SPLIT * 256;
            packed_ptr += K_SPLIT * 128;
            scale_ptr += K_SPLIT * 8;
        }
    }
    const float2 value04 = __half22float2(sum0);
    const float2 value15 = __half22float2(sum1);
    const float2 value26 = __half22float2(sum2);
    const float2 value37 = __half22float2(sum3);
    float value = tail + value04.x;
    value += value15.x;
    value += value26.x;
    value += value37.x;
    value += value04.y;
    value += value15.y;
    value += value26.y;
    value += value37.y;
    value = warp_sum(value);
    if (lane == 0) {
        partials[col_local][ks] = (column < n) ? value : 0.0f;
    }
    __syncthreads();
    if (ks == 0 && lane == 0 && column < n) {
        float acc = 0.0f;
#pragma unroll
        for (int s = 0; s < K_SPLIT; ++s) {
            acc += partials[col_local][s];
        }
        matmul_nbits_store_narrowed(
            output, column, fold_bias_f16(acc, bias, column, bias_post_round),
            out_bf16);
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_splitk(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    matmul_nbits_gemv_f16_scales_f16_splitk_tpl<false, 2>(
        activation, packed, scales_raw, zero_points, bias, output, k, n,
        block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16,
        bias_post_round, out_bf16);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_zp_splitk(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    matmul_nbits_gemv_f16_scales_f16_splitk_tpl<true, 2>(
        activation, packed, scales_raw, zero_points, bias, output, k, n,
        block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16,
        bias_post_round, out_bf16);
}

// Deep-split sibling of `matmul_nbits_gemv_f16_scales_f16_zp_splitk` for output
// widths so narrow that K_SPLIT=2 still leaves the device under one wave. The
// GQA k/v projection is the case: N=256 at 8 warps/CTA and K_SPLIT=2 covers 4
// columns per block, so the whole launch is 64 blocks on a 108-SM A100 and the
// kernel runs at latency rather than at bandwidth. Measured 28 GB/s there — the
// same K at N=4096 moved 16x the bytes in 21% LESS time, which no bandwidth
// explanation survives. K_SPLIT=8 makes each CTA cover one column, taking that
// launch to 256 blocks. Same accumulation as the K_SPLIT=2 entry, one more level
// of fp32 partial summing.
extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_zp_splitk8(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    matmul_nbits_gemv_f16_scales_f16_splitk_tpl<true, 8>(
        activation, packed, scales_raw, zero_points, bias, output, k, n,
        block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16,
        bias_post_round, out_bf16);
}

// Prefetch-pipelined sibling of `matmul_nbits_gemv_f16_scales_f16_splitk_tpl`.
// The split-K kernel fills idle SMs and adds per-COLUMN memory-level parallelism
// (K_SPLIT warps per column), but each lane still walks its weight-word chain
// with a single 32-bit global load in flight -> a load->accumulate->load
// dependency that stalls on the ~Long-Scoreboard weight-load latency the pipe
// kernel diagnosed (DRAM ~24% of an H200's 4.8 TB/s, math not the bottleneck).
// This variant adds per-LANE MLP on top of split-K by holding PF prefetched
// weight words in a register-resident shift register (manual rotation, no
// dynamic-indexed array -> no local spill), so PF independent global loads stay
// in flight per lane while the fp16 dequant/FMA of the current word proceeds.
//
// The lane->nibble mapping, the `accumulate_int4x8_f16_zp` calls, the per-split
// accumulation order and the shared-mem cross-split reduction are UNCHANGED, so
// the output is bit-identical to `matmul_nbits_gemv_f16_scales_f16_splitk_tpl`
// (which is already near-equal, not byte-identical, to the single-warp pipe
// entry). Only the timing of the weight loads changes.
template <bool HasZp, int K_SPLIT>
__device__ __forceinline__ void matmul_nbits_gemv_f16_scales_f16_splitk_pf_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    (void)block_size;
    (void)scales_fp16;
    constexpr int PF = 3;  // weight words in flight per lane
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int cols_per_block = warps_per_block / K_SPLIT;
    const int col_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const int column = (int)blockIdx.x * cols_per_block + col_local;

    __shared__ float partials[8][K_SPLIT];

    __half2 sum0 = __float2half2_rn(0.0f);
    __half2 sum1 = __float2half2_rn(0.0f);
    __half2 sum2 = __float2half2_rn(0.0f);
    __half2 sum3 = __float2half2_rn(0.0f);
    float tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        // Depth this (lane, split) touches at step i is
        // `depth_start + i * K_SPLIT * 256`; the weight word stride is
        // `K_SPLIT * 128` packed bytes (256 depth = 128 bytes for block-32 int4).
        const int depth_start = ks * 256 + lane_depth;
        const unsigned char* packed_base =
            packed + (long)column * k_blocks * blob_size +
            (long)((ks * 256) >> 5) * blob_size + lane * 4;
        // Full 8-nibble steps this (lane, split) walks (step i valid iff
        // `depth_start + i*K_SPLIT*256 + 8 <= k`), identical to the scalar bound.
        const int nfull =
            (depth_start + 8 <= k) ? ((k - depth_start - 8) / (K_SPLIT * 256) + 1) : 0;
        auto load_step = [&](int s) -> unsigned int {
            return *reinterpret_cast<const unsigned int*>(
                packed_base + (long)s * (K_SPLIT * 128));
        };
        // Prime the shift register; out-of-range slots are zero (never consumed).
        unsigned int wbuf[PF];
#pragma unroll
        for (int s = 0; s < PF; ++s) {
            wbuf[s] = (s < nfull) ? load_step(s) : 0u;
        }

        const __half* activation_ptr = activation + depth_start;
        const __half* scale_ptr =
            scales + (long)column * k_blocks + ((ks * 256) >> 5) + (lane >> 2);
        int block = (int)(((ks * 256) >> 5) + (lane >> 2));
        for (int i = 0; i < nfull; ++i) {
            const unsigned int packed_word = wbuf[0];
            // Rotate and issue the load PF steps ahead BEFORE consuming, so PF
            // independent loads stay in flight.
            const int pf = i + PF;
#pragma unroll
            for (int s = 0; s < PF - 1; ++s) {
                wbuf[s] = wbuf[s + 1];
            }
            wbuf[PF - 1] = (pf < nfull) ? load_step(pf) : 0u;

            const unsigned int sub2 =
                block_sub2<HasZp>(zero_points, column, block, zp_row_bytes);
            accumulate_int4x8_f16_zp(
                packed_word, activation_ptr, *scale_ptr, sub2, sum0, sum1, sum2, sum3);
            activation_ptr += K_SPLIT * 256;
            scale_ptr += K_SPLIT * 8;
            block += K_SPLIT * 8;
        }
        const int tail_depth = depth_start + nfull * (K_SPLIT * 256);
        if (tail_depth < k) {
            const unsigned int packed_word = load_step(nfull);
            const float scale = __half2float(*scale_ptr);
            const int zero_point =
                block_zp<HasZp>(zero_points, column, block, zp_row_bytes);
            const int valid = k - tail_depth;
#pragma unroll
            for (int i = 0; i < 8; ++i) {
                if (i < valid) {
                    const int q =
                        (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                    tail += (float)q * __half2float(activation_ptr[i]) * scale;
                }
            }
        }
    }
    const float2 value04 = __half22float2(sum0);
    const float2 value15 = __half22float2(sum1);
    const float2 value26 = __half22float2(sum2);
    const float2 value37 = __half22float2(sum3);
    float value = tail + value04.x;
    value += value15.x;
    value += value26.x;
    value += value37.x;
    value += value04.y;
    value += value15.y;
    value += value26.y;
    value += value37.y;
    value = warp_sum(value);
    if (lane == 0) {
        partials[col_local][ks] = (column < n) ? value : 0.0f;
    }
    __syncthreads();
    if (ks == 0 && lane == 0 && column < n) {
        float acc = 0.0f;
#pragma unroll
        for (int s = 0; s < K_SPLIT; ++s) {
            acc += partials[col_local][s];
        }
        matmul_nbits_store_narrowed(
            output, column, fold_bias_f16(acc, bias, column, bias_post_round),
            out_bf16);
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_splitk_pf(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    matmul_nbits_gemv_f16_scales_f16_splitk_pf_tpl<false, 2>(
        activation, packed, scales_raw, zero_points, bias, output, k, n,
        block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16,
        bias_post_round, out_bf16);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_zp_splitk_pf(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    matmul_nbits_gemv_f16_scales_f16_splitk_pf_tpl<true, 2>(
        activation, packed, scales_raw, zero_points, bias, output, k, n,
        block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16,
        bias_post_round, out_bf16);
}

// Prefetch-pipelined sibling of the K_SPLIT=8 deep-split GQA k/v entry
// (`matmul_nbits_gemv_f16_scales_f16_zp_splitk8`). Same PF register shift-
// register transform as the K_SPLIT=2 `_pf` entries, just a deeper split, so it
// stays bit-identical to the plain `_splitk8` entry while hiding the per-lane
// weight-load latency that persists even after the grid is deepened.
extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_zp_splitk8_pf(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    void* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int out_bf16)
{
    matmul_nbits_gemv_f16_scales_f16_splitk_pf_tpl<true, 8>(
        activation, packed, scales_raw, zero_points, bias, output, k, n,
        block_size, k_blocks, blob_size, zp_row_bytes, scales_fp16,
        bias_post_round, out_bf16);
}

// Half4 view matching `skip_rmsnorm_f16_warp_half4` so the fused prologue below
// reduces the activation with the exact same chunking and rounding.
union MatMulNBitsSkipHalf4 {
    unsigned long long raw;
    __half2 pair[2];
};

// Scalar RMS-norm gamma load matching `skip_rmsnorm_f16_warp_half4`: gamma is
// only ever a final multiplicand (never part of the fp32 variance
// accumulation), so an fp32 gamma is read at full precision while an fp16 gamma
// keeps the half round-trip. This lets decoders that export gamma in fp32 (e.g.
// Phi-4-mini) take the fused RMS-norm-prologue GEMV path bit-identically to the
// standalone norm + GEMV pair.
__device__ __forceinline__ float load_rmsnorm_gamma(
    const void* __restrict__ gamma,
    const int gamma_is_half,
    const int index)
{
    return gamma_is_half
        ? __half2float(reinterpret_cast<const __half*>(gamma)[index])
        : reinterpret_cast<const float*>(gamma)[index];
}

// General fp16/fp16-scales GEMV with a fused RMS-normalization prologue. The
// preceding GEMV's residual epilogue already produced the byte-identical
// residual sum that `SkipSimplifiedLayerNormalization` would emit as its
// residual output, so this kernel only has to (1) reduce that sum exactly as
// `skip_rmsnorm_f16_warp_half4` does, (2) write the normalized activation into
// shared memory with the same rounding, and (3) run the standard `scales_f16`
// int4 dot over that staged, normalized activation. Every arithmetic step
// mirrors the standalone norm + GEMV pair, so tokens stay bit-for-bit identical
// while the separate normalization kernel is removed from the decode graph.
template <bool HasZp, bool SplitK = false>
__device__ __forceinline__ void matmul_nbits_gemv_f16_scales_f16_rmsnorm_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    // Normalized activation, staged 16-byte aligned so the dot below can reuse
    // the `scales_f16` `uint4` activation loads unchanged.
    extern __shared__ __align__(16) __half staged_activation[];
    __shared__ float shared_inv_std;
    __shared__ float partials[8][2];

    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;

    // --- RMS reduction, byte-identical to `skip_rmsnorm_f16_warp_half4`. ---
    if (warp == 0) {
        const int chunks_per_lane = k / (32 * 4);
        const unsigned long long* activation4 =
            reinterpret_cast<const unsigned long long*>(activation);
        float ss0 = 0.0f;
        float ss1 = 0.0f;
        float ss2 = 0.0f;
        float ss3 = 0.0f;
        for (int item = 0; item < chunks_per_lane; ++item) {
            const int chunk = lane + item * 32;
            MatMulNBitsSkipHalf4 residual;
            residual.raw = activation4[chunk];
            const float2 rounded0 = __half22float2(residual.pair[0]);
            const float2 rounded1 = __half22float2(residual.pair[1]);
            ss0 += rounded0.x * rounded0.x;
            ss1 += rounded0.y * rounded0.y;
            ss2 += rounded1.x * rounded1.x;
            ss3 += rounded1.y * rounded1.y;
        }
        float ss = (ss0 + ss1) + (ss2 + ss3);
        for (int off = 16; off > 0; off >>= 1) {
            ss += __shfl_down_sync(0xffffffffu, ss, off);
        }
        if (lane == 0) {
            shared_inv_std = 1.0f / sqrtf(ss / (float)k + epsilon);
        }
    }
    __syncthreads();
    const float inv_std = shared_inv_std;

    // --- Normalized activation, matching the norm kernel's rounded output. ---
    for (int j = tid; j < k; j += (int)blockDim.x) {
        const float residual = __half2float(activation[j]);
        const float scale = load_rmsnorm_gamma(gamma, gamma_is_half, j);
        staged_activation[j] = __float2half((residual * inv_std) * scale);
    }
    __syncthreads();

    // --- Standard `scales_f16` int4 dot over the staged, normalized input. ---
    const int warps_per_block = (int)blockDim.x >> 5;
    const int columns_per_block = SplitK ? warps_per_block / 2 : warps_per_block;
    const int column_local = SplitK ? warp / 2 : warp;
    const int k_split = SplitK ? warp & 1 : 0;
    const int column = (int)blockIdx.x * columns_per_block + column_local;
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);

    __half2 sum0 = __float2half2_rn(0.0f);
    __half2 sum1 = __float2half2_rn(0.0f);
    __half2 sum2 = __float2half2_rn(0.0f);
    __half2 sum3 = __float2half2_rn(0.0f);
    float tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        int depth_base = k_split * 256;
        const __half* activation_ptr = staged_activation + depth_base + lane_depth;
        const unsigned char* packed_ptr =
            packed + (long)column * k_blocks * blob_size
                + (long)(depth_base >> 5) * blob_size + lane * 4;
        const __half* scale_ptr =
            scales + (long)column * k_blocks + (depth_base >> 5) + (lane >> 2);
        const int depth_step = SplitK ? 512 : 256;
        for (; depth_base + lane_depth + 8 <= k; depth_base += depth_step) {
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed_ptr);
            const int block = (depth_base >> 5) + (lane >> 2);
            const unsigned int sub2 =
                block_sub2<HasZp>(zero_points, column, block, zp_row_bytes);
            accumulate_int4x8_f16_zp(
                packed_word,
                activation_ptr,
                *scale_ptr,
                sub2,
                sum0,
                sum1,
                sum2,
                sum3);
            activation_ptr += depth_step;
            packed_ptr += depth_step / 2;
            scale_ptr += depth_step / 32;
        }
        const int tail_depth = depth_base + lane_depth;
        if (tail_depth < k) {
            const unsigned int packed_word =
                *reinterpret_cast<const unsigned int*>(packed_ptr);
            const float scale = __half2float(*scale_ptr);
            const int tail_block = (depth_base >> 5) + (lane >> 2);
            const int zero_point =
                block_zp<HasZp>(zero_points, column, tail_block, zp_row_bytes);
            const int valid = min(8, k - tail_depth);
#pragma unroll
            for (int i = 0; i < 8; ++i) {
                if (i < valid) {
                    const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                    tail += (float)q * __half2float(activation_ptr[i]) * scale;
                }
            }
        }
    }
    const float2 value04 = __half22float2(sum0);
    const float2 value15 = __half22float2(sum1);
    const float2 value26 = __half22float2(sum2);
    const float2 value37 = __half22float2(sum3);
    float value = tail + value04.x;
    value += value15.x;
    value += value26.x;
    value += value37.x;
    value += value04.y;
    value += value15.y;
    value += value26.y;
    value += value37.y;
    value = warp_sum(value);
    if constexpr (SplitK) {
        if (lane == 0) {
            partials[column_local][k_split] = column < n ? value : 0.0f;
        }
        __syncthreads();
        if (k_split == 0 && lane == 0 && column < n) {
            output[column] = fold_bias_f16(
                partials[column_local][0] + partials[column_local][1],
                bias,
                column,
                bias_post_round);
        }
    } else if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_rmsnorm(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_scales_f16_rmsnorm_tpl<false>(activation, packed, scales_raw, zero_points, gamma, bias, output, k, n, k_blocks, blob_size, zp_row_bytes, bias_post_round, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_rmsnorm_splitk(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_scales_f16_rmsnorm_tpl<false, true>(activation, packed, scales_raw, zero_points, gamma, bias, output, k, n, k_blocks, blob_size, zp_row_bytes, bias_post_round, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_rmsnorm_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_scales_f16_rmsnorm_tpl<true>(activation, packed, scales_raw, zero_points, gamma, bias, output, k, n, k_blocks, blob_size, zp_row_bytes, bias_post_round, gamma_is_half, epsilon);
}

// Compile-time-specialized per-block int8 zero point. `HasZp == false`
// (symmetric int8) folds to the constant 128 with no load — mirroring the int4
// `block_zp` helper — so a future symmetric-int8 model keeps the constant
// subtrahend and never pays the per-block occupancy cost the int4 path shed.
template <bool HasZp>
__device__ __forceinline__ int block_zp_int8(
    const unsigned char* __restrict__ zero_points,
    const long column,
    const int block,
    const int k_blocks)
{
    if (!HasZp) {
        return 128;
    }
    return (int)zero_points[column * k_blocks + block];
}

// INT8 sibling of `matmul_nbits_gemv_f16_scales_f16_rmsnorm`. The RMS reduction
// and normalized-activation staging are byte-identical to the int4 fused kernel
// (and to the standalone `skip_rmsnorm_f16_warp_half4`); only the quantized dot
// differs, reusing the exact block-32 int8 dequant work split from
// `matmul_nbits_gemv_int8_f16` (one byte per weight, per-block uint8 zero point
// defaulting to 128, fp32 accumulation). Specialized on `HasZp` like the int4
// sibling so the symmetric case emits no per-block zero-point load.
template <bool HasZp>
__device__ __forceinline__ void matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    extern __shared__ __align__(16) __half staged_activation[];
    __shared__ float shared_inv_std;

    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;

    // --- RMS reduction, byte-identical to `skip_rmsnorm_f16_warp_half4`. ---
    if (warp == 0) {
        const int chunks_per_lane = k / (32 * 4);
        const unsigned long long* activation4 =
            reinterpret_cast<const unsigned long long*>(activation);
        float ss0 = 0.0f;
        float ss1 = 0.0f;
        float ss2 = 0.0f;
        float ss3 = 0.0f;
        for (int item = 0; item < chunks_per_lane; ++item) {
            const int chunk = lane + item * 32;
            MatMulNBitsSkipHalf4 residual;
            residual.raw = activation4[chunk];
            const float2 rounded0 = __half22float2(residual.pair[0]);
            const float2 rounded1 = __half22float2(residual.pair[1]);
            ss0 += rounded0.x * rounded0.x;
            ss1 += rounded0.y * rounded0.y;
            ss2 += rounded1.x * rounded1.x;
            ss3 += rounded1.y * rounded1.y;
        }
        float ss = (ss0 + ss1) + (ss2 + ss3);
        for (int off = 16; off > 0; off >>= 1) {
            ss += __shfl_down_sync(0xffffffffu, ss, off);
        }
        if (lane == 0) {
            shared_inv_std = 1.0f / sqrtf(ss / (float)k + epsilon);
        }
    }
    __syncthreads();
    const float inv_std = shared_inv_std;

    // --- Normalized activation, matching the norm kernel's rounded output. ---
    for (int j = tid; j < k; j += (int)blockDim.x) {
        const float residual = __half2float(activation[j]);
        const float scale = load_rmsnorm_gamma(gamma, gamma_is_half, j);
        staged_activation[j] = __float2half((residual * inv_std) * scale);
    }
    __syncthreads();

    // --- INT8 dot over the staged, normalized input (mirrors the non-fused
    //     `matmul_nbits_gemv_int8_f16` work split, fp32 accumulation). ---
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);

    float value = 0.0f;
    if (column < n) {
        const int quarter = lane & 3;
        for (int block_base = 0; block_base < k_blocks; block_base += 8) {
            const int block = block_base + (lane >> 2);
            float block_partial = 0.0f;
            if (block < k_blocks) {
                const int zero_point =
                    block_zp_int8<HasZp>(zero_points, column, block, k_blocks);
                const int depth = block * 32 + quarter * 8;
                const long packed_start =
                    ((long)column * k_blocks + block) * 32 + quarter * 8;
                if (depth + 8 <= k) {
                    const uint2 packed_word =
                        *reinterpret_cast<const uint2*>(packed + packed_start);
                    const unsigned char* bytes =
                        reinterpret_cast<const unsigned char*>(&packed_word);
                    const uint4 act =
                        *reinterpret_cast<const uint4*>(staged_activation + depth);
                    const __half* acth = reinterpret_cast<const __half*>(&act);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        block_partial += ((float)(int)bytes[i] - (float)zero_point)
                            * __half2float(acth[i]);
                    }
                } else if (depth < k) {
                    const int valid = min(8, k - depth);
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid) {
                            const int quantized = (int)packed[packed_start + i];
                            block_partial += ((float)quantized - (float)zero_point)
                                * __half2float(staged_activation[depth + i]);
                        }
                    }
                }
            }
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 2, 4);
            block_partial += __shfl_down_sync(0xffffffffu, block_partial, 1, 4);
            if (quarter == 0 && block < k_blocks) {
                const float scale =
                    __half2float(scales[(long)column * k_blocks + block]);
                value += block_partial * scale;
            }
        }
    }
    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

extern "C" __global__ void matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm_tpl<false>(activation, packed, scales_raw, zero_points, gamma, bias, output, k, n, k_blocks, bias_post_round, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const void* __restrict__ gamma,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int bias_post_round,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_int8_f16_scales_f16_rmsnorm_tpl<true>(activation, packed, scales_raw, zero_points, gamma, bias, output, k, n, k_blocks, bias_post_round, gamma_is_half, epsilon);
}

// Standalone RMS-normalization prologue for the M>1 prefill path of the fused
// GEMV. It reproduces `skip_rmsnorm_f16_warp_half4` (minus the residual add,
// which the preceding GEMV's epilogue already applied) bit-for-bit: identical
// half4 chunking, identical `(ss0+ss1)+(ss2+ss3)` reduction, identical warp
// shuffle, and identical `__floats2half2_rn` output rounding. One warp
// normalizes one token row into `normalized`, which the portable tiled GEMM
// then consumes exactly as it would the standalone norm's fp16 output.
extern "C" __global__ void matmul_nbits_rmsnorm_f16_warp_half4(
    const __half* __restrict__ activation,
    const void* __restrict__ gamma,
    __half* __restrict__ normalized,
    const int norm_size,
    const int num_groups,
    const int gamma_is_half,
    const float epsilon)
{
    const int g = (int)blockIdx.x;
    if (g >= num_groups) return;
    const long base = (long)g * norm_size;
    const int lane = (int)threadIdx.x;
    const int chunks_per_lane = norm_size / (32 * 4);
    const unsigned long long* activation4 =
        reinterpret_cast<const unsigned long long*>(activation + base);
    const unsigned long long* gamma4 =
        reinterpret_cast<const unsigned long long*>(gamma);
    unsigned long long* normalized4 =
        reinterpret_cast<unsigned long long*>(normalized + base);
    float ss0 = 0.0f;
    float ss1 = 0.0f;
    float ss2 = 0.0f;
    float ss3 = 0.0f;
    for (int item = 0; item < chunks_per_lane; ++item) {
        const int chunk = lane + item * 32;
        MatMulNBitsSkipHalf4 residual;
        residual.raw = activation4[chunk];
        const float2 rounded0 = __half22float2(residual.pair[0]);
        const float2 rounded1 = __half22float2(residual.pair[1]);
        ss0 += rounded0.x * rounded0.x;
        ss1 += rounded0.y * rounded0.y;
        ss2 += rounded1.x * rounded1.x;
        ss3 += rounded1.y * rounded1.y;
    }
    float ss = (ss0 + ss1) + (ss2 + ss3);
    for (int off = 16; off > 0; off >>= 1) {
        ss += __shfl_down_sync(0xffffffffu, ss, off);
    }
    float inv_std = 0.0f;
    if (lane == 0) {
        inv_std = 1.0f / sqrtf(ss / (float)norm_size + epsilon);
    }
    inv_std = __shfl_sync(0xffffffffu, inv_std, 0);
    for (int item = 0; item < chunks_per_lane; ++item) {
        const int chunk = lane + item * 32;
        MatMulNBitsSkipHalf4 residual;
        MatMulNBitsSkipHalf4 output;
        residual.raw = activation4[chunk];
        const float2 value0 = __half22float2(residual.pair[0]);
        const float2 value1 = __half22float2(residual.pair[1]);
        // gamma is only a final multiplicand: an fp16 gamma keeps the wide
        // half4 load, an fp32 gamma is read at full precision (matching the
        // standalone `skip_rmsnorm_f16_warp_half4`), so fp32-gamma decoders fuse.
        float scale0x, scale0y, scale1x, scale1y;
        if (gamma_is_half) {
            MatMulNBitsSkipHalf4 scale;
            scale.raw = gamma4[chunk];
            const float2 scale0 = __half22float2(scale.pair[0]);
            const float2 scale1 = __half22float2(scale.pair[1]);
            scale0x = scale0.x;
            scale0y = scale0.y;
            scale1x = scale1.x;
            scale1y = scale1.y;
        } else {
            const int j = chunk << 2;
            const float* gamma_f = reinterpret_cast<const float*>(gamma);
            scale0x = gamma_f[j];
            scale0y = gamma_f[j + 1];
            scale1x = gamma_f[j + 2];
            scale1y = gamma_f[j + 3];
        }
        output.pair[0] = __floats2half2_rn(
            value0.x * inv_std * scale0x,
            value0.y * inv_std * scale0y);
        output.pair[1] = __floats2half2_rn(
            value1.x * inv_std * scale1x,
            value1.y * inv_std * scale1y);
        normalized4[chunk] = output.raw;
    }
}

// SwiGLU activation, byte-identical to the standalone `op_silu` in the
// elementwise kernels: silu(x) = x * sigmoid(x), evaluated in the same
// rounding-stable form so the paired epilogue reproduces the two-op tokens.
__device__ __forceinline__ float gate_up_silu_f32(float x)
{
    if (x >= 0.0f) {
        const float denominator = __fadd_rn(1.0f, (float)exp((double)-x));
        return __fdiv_rn(x, denominator);
    }

    const float e = (float)exp((double)x);
    const float numerator = __fmul_rn(x, e);
    return __fdiv_rn(numerator, __fadd_rn(1.0f, e));
}

__device__ __forceinline__ float gate_up_decomposed_silu_f32(float x)
{
    float sigmoid;
    if (x >= 0.0f) {
        sigmoid = 1.0f / (1.0f + (float)exp((double)-x));
    } else {
        const float e = (float)exp((double)x);
        sigmoid = e / (1.0f + e);
    }
    const float sigmoid_h = __half2float(__float2half_rn(sigmoid));
    return __half2float(__float2half_rn(__fmul_rn(x, sigmoid_h)));
}

// Paired gate/up projection + SwiGLU. One warp computes column `column` of BOTH
// the gate and up projections (which share the same activation and the block-32
// fp16 layout of `matmul_nbits_gemv_f16_scales_f16`), then writes
// silu(gate)*up directly. The activation is permuted once per K-tile and reused
// by both accumulators, so the two GEMVs read the activation from registers
// exactly once. The epilogue reproduces the standalone two-op numerics
// (`fp16(gate_acc)`, `fp16(up_acc)`, then `fp16(silu(gate_h)*up_h)`) so greedy
// decoding stays byte-identical. Register-only + warp shuffles: no shared
// memory, so it is portable to sm_53+ and safe on small SMs (no >48KB opt-in).
template <bool HasZp, bool Decomposed, bool FusedSym = false>
__device__ __forceinline__ void matmul_nbits_gemv_f16_gate_up_swiglu_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;

    __half2 g0 = __float2half2_rn(0.0f);
    __half2 g1 = __float2half2_rn(0.0f);
    __half2 g2 = __float2half2_rn(0.0f);
    __half2 g3 = __float2half2_rn(0.0f);
    __half2 u0 = __float2half2_rn(0.0f);
    __half2 u1 = __float2half2_rn(0.0f);
    __half2 u2 = __float2half2_rn(0.0f);
    __half2 u3 = __float2half2_rn(0.0f);
    float gate_tail = 0.0f;
    float up_tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        const __half* activation_ptr = activation + lane_depth;
        const unsigned char* packed_gate_ptr =
            packed_gate + (long)column * k_blocks * blob_size + lane * 4;
        const unsigned char* packed_up_ptr =
            packed_up + (long)column * k_blocks * blob_size + lane * 4;
        const __half* scale_gate_ptr =
            scales_gate + (long)column * k_blocks + (lane >> 2);
        const __half* scale_up_ptr =
            scales_up + (long)column * k_blocks + (lane >> 2);
        int depth_base = 0;
        for (; depth_base + lane_depth + 8 <= k; depth_base += 256) {
            // Permute the shared activation once; both projections reuse it.
            const uint4 permuted = permute_activation_f16x8(activation_ptr);
            const int block = (depth_base >> 5) + (lane >> 2);
            const unsigned int gate_sub2 =
                block_sub2<HasZp>(zero_points_gate, column, block, zp_row_bytes);
            const unsigned int up_sub2 =
                block_sub2<HasZp>(zero_points_up, column, block, zp_row_bytes);
            const unsigned int gate_word =
                *reinterpret_cast<const unsigned int*>(packed_gate_ptr);
            const unsigned int up_word =
                *reinterpret_cast<const unsigned int*>(packed_up_ptr);
            if constexpr (FusedSym && !HasZp) {
                // Symmetric fast dequant: fold `- 8` into the bias constants
                // (byte-identical, four fewer f16x2 ops/word). `gate_sub2`/
                // `up_sub2` are the constant 8 here and go unused.
                accumulate_int4x8_f16_permuted_sym8(
                    gate_word, permuted, *scale_gate_ptr, g0, g1, g2, g3);
                accumulate_int4x8_f16_permuted_sym8(
                    up_word, permuted, *scale_up_ptr, u0, u1, u2, u3);
            } else {
                accumulate_int4x8_f16_permuted_zp(
                    gate_word, permuted, *scale_gate_ptr, gate_sub2, g0, g1, g2, g3);
                accumulate_int4x8_f16_permuted_zp(
                    up_word, permuted, *scale_up_ptr, up_sub2, u0, u1, u2, u3);
            }
            activation_ptr += 256;
            packed_gate_ptr += 128;
            packed_up_ptr += 128;
            scale_gate_ptr += 8;
            scale_up_ptr += 8;
        }
        const int tail_depth = depth_base + lane_depth;
        if (tail_depth < k) {
            const unsigned int gate_word =
                *reinterpret_cast<const unsigned int*>(packed_gate_ptr);
            const unsigned int up_word =
                *reinterpret_cast<const unsigned int*>(packed_up_ptr);
            const float gate_scale = __half2float(*scale_gate_ptr);
            const float up_scale = __half2float(*scale_up_ptr);
            const int tail_block = (depth_base >> 5) + (lane >> 2);
            const int gate_zp =
                block_zp<HasZp>(zero_points_gate, column, tail_block, zp_row_bytes);
            const int up_zp =
                block_zp<HasZp>(zero_points_up, column, tail_block, zp_row_bytes);
            const int valid = min(8, k - tail_depth);
#pragma unroll
            for (int i = 0; i < 8; ++i) {
                if (i < valid) {
                    const float a = __half2float(activation_ptr[i]);
                    const int qg = (int)((gate_word >> (i * 4)) & 15u) - gate_zp;
                    const int qu = (int)((up_word >> (i * 4)) & 15u) - up_zp;
                    gate_tail += (float)qg * a * gate_scale;
                    up_tail += (float)qu * a * up_scale;
                }
            }
        }
    }
    // Reduce each accumulator in the exact term order of the standalone
    // `matmul_nbits_gemv_f16_scales_f16` epilogue so the pre-round sums match.
    const float2 g04 = __half22float2(g0);
    const float2 g15 = __half22float2(g1);
    const float2 g26 = __half22float2(g2);
    const float2 g37 = __half22float2(g3);
    float gate_value = gate_tail + g04.x;
    gate_value += g15.x;
    gate_value += g26.x;
    gate_value += g37.x;
    gate_value += g04.y;
    gate_value += g15.y;
    gate_value += g26.y;
    gate_value += g37.y;
    gate_value = warp_sum(gate_value);

    const float2 u04 = __half22float2(u0);
    const float2 u15 = __half22float2(u1);
    const float2 u26 = __half22float2(u2);
    const float2 u37 = __half22float2(u3);
    float up_value = up_tail + u04.x;
    up_value += u15.x;
    up_value += u26.x;
    up_value += u37.x;
    up_value += u04.y;
    up_value += u15.y;
    up_value += u26.y;
    up_value += u37.y;
    up_value = warp_sum(up_value);

    if (lane == 0 && column < n) {
        // Round each projection to fp16 first (matching the separate GEMV
        // stores), then compute silu(gate)*up and round once — identical to the
        // standalone silu_mul_f16 kernel fed by the two GEMV outputs.
        const float gate_h = __half2float(__float2half(gate_value));
        const float up_h = __half2float(__float2half(up_value));
        const float silu_h = Decomposed
            ? gate_up_decomposed_silu_f32(gate_h)
            : gate_up_silu_f32(gate_h);
        output[column] = __float2half_rn(__fmul_rn(silu_h, up_h));
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_swiglu(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_tpl<false, false>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, output, k, n, k_blocks, blob_size, zp_row_bytes);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_decomposed_swiglu(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_tpl<false, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, output, k, n, k_blocks, blob_size, zp_row_bytes);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_swiglu_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_tpl<true, false>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, output, k, n, k_blocks, blob_size, zp_row_bytes);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_tpl<true, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, output, k, n, k_blocks, blob_size, zp_row_bytes);
}

// Fused-symmetric (`ONNX_GENAI_GATEUP_VEC`) siblings of the two SYMMETRIC
// gate/up SwiGLU entries above. Byte-identical — only the dequant folds the
// `- 8` symmetric zero point into the bias constants (see
// `int4x8_to_half2x4_sym8`), issuing four fewer f16x2 ops per weight word to
// relieve the issue-bound decode GEMV. No asymmetric `_vec` variant: the `_zp`
// entries carry a per-block zero point that cannot be folded to a constant.
extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_swiglu_vec(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_tpl<false, false, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, output, k, n, k_blocks, blob_size, zp_row_bytes);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_vec(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_tpl<false, true, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, output, k, n, k_blocks, blob_size, zp_row_bytes);
}
// This is `matmul_nbits_gemv_f16_gate_up_swiglu` preceded by the exact prologue
// of `matmul_nbits_gemv_f16_scales_f16_rmsnorm`: the block reduces the shared
// activation (the residual sum the preceding GEMV epilogue already produced)
// once, stages the normalized activation into shared memory with the same
// rounding, and then both the gate and up GEMVs read that single staged,
// normalized activation. Doing the reduction once — rather than once per
// following GEMV — is the whole point of routing the fan-out-2 post-attention
// `SkipSimplifiedLayerNormalization` through the paired kernel. Every arithmetic
// step mirrors the standalone norm followed by the two-op gate/up SwiGLU, so
// greedy tokens stay bit-for-bit identical.
template <bool HasZp, bool Decomposed, bool FusedSym = false>
__device__ __forceinline__ void matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    extern __shared__ __align__(16) __half staged_activation[];
    __shared__ float shared_inv_std;

    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;

    // --- RMS reduction, byte-identical to `skip_rmsnorm_f16_warp_half4`. ---
    if (warp == 0) {
        const int chunks_per_lane = k / (32 * 4);
        const unsigned long long* activation4 =
            reinterpret_cast<const unsigned long long*>(activation);
        float ss0 = 0.0f;
        float ss1 = 0.0f;
        float ss2 = 0.0f;
        float ss3 = 0.0f;
        for (int item = 0; item < chunks_per_lane; ++item) {
            const int chunk = lane + item * 32;
            MatMulNBitsSkipHalf4 residual;
            residual.raw = activation4[chunk];
            const float2 rounded0 = __half22float2(residual.pair[0]);
            const float2 rounded1 = __half22float2(residual.pair[1]);
            ss0 += rounded0.x * rounded0.x;
            ss1 += rounded0.y * rounded0.y;
            ss2 += rounded1.x * rounded1.x;
            ss3 += rounded1.y * rounded1.y;
        }
        float ss = (ss0 + ss1) + (ss2 + ss3);
        for (int off = 16; off > 0; off >>= 1) {
            ss += __shfl_down_sync(0xffffffffu, ss, off);
        }
        if (lane == 0) {
            shared_inv_std = 1.0f / sqrtf(ss / (float)k + epsilon);
        }
    }
    __syncthreads();
    const float inv_std = shared_inv_std;

    // --- Normalized activation, matching the norm kernel's rounded output. ---
    for (int j = tid; j < k; j += (int)blockDim.x) {
        const float residual = __half2float(activation[j]);
        const float scale = load_rmsnorm_gamma(gamma, gamma_is_half, j);
        staged_activation[j] = __float2half((residual * inv_std) * scale);
    }
    __syncthreads();

    // --- Paired gate/up int4 dot over the staged, normalized activation. ---
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;

    __half2 g0 = __float2half2_rn(0.0f);
    __half2 g1 = __float2half2_rn(0.0f);
    __half2 g2 = __float2half2_rn(0.0f);
    __half2 g3 = __float2half2_rn(0.0f);
    __half2 u0 = __float2half2_rn(0.0f);
    __half2 u1 = __float2half2_rn(0.0f);
    __half2 u2 = __float2half2_rn(0.0f);
    __half2 u3 = __float2half2_rn(0.0f);
    float gate_tail = 0.0f;
    float up_tail = 0.0f;
    if (column < n) {
        const int lane_depth = lane * 8;
        const __half* activation_ptr = staged_activation + lane_depth;
        const unsigned char* packed_gate_ptr =
            packed_gate + (long)column * k_blocks * blob_size + lane * 4;
        const unsigned char* packed_up_ptr =
            packed_up + (long)column * k_blocks * blob_size + lane * 4;
        const __half* scale_gate_ptr =
            scales_gate + (long)column * k_blocks + (lane >> 2);
        const __half* scale_up_ptr =
            scales_up + (long)column * k_blocks + (lane >> 2);
        int depth_base = 0;
        if constexpr (HasZp) {
            // Asymmetric (zero-point) path — the dominant Phi decode kernel, which
            // ncu shows is Long-Scoreboard/global-load-latency bound. Software-
            // pipeline the int4 gate/up weight loads: issue the next iteration's
            // two 128-byte weight words before consuming the current ones so the
            // load latency overlaps this iteration's compute. Pure scheduling
            // change (identical accumulation order/ops) → bit-identical to the
            // non-prefetched loop. Only the weight words are prefetched; also
            // prefetching the small (L1/L2-resident) scales and per-block zero
            // points pushed registers 48->56 and the occupancy loss erased the
            // latency win. The symmetric (`HasZp == false`) path below keeps its
            // exact original instruction stream so Qwen stays byte-identical with
            // no register/occupancy change.
            unsigned int gate_word_next =
                *reinterpret_cast<const unsigned int*>(packed_gate_ptr);
            unsigned int up_word_next =
                *reinterpret_cast<const unsigned int*>(packed_up_ptr);
            for (; depth_base + lane_depth + 8 <= k; depth_base += 256) {
                const uint4 permuted = permute_activation_f16x8(activation_ptr);
                const int block = (depth_base >> 5) + (lane >> 2);
                const unsigned int gate_sub2 =
                    block_sub2<HasZp>(zero_points_gate, column, block, zp_row_bytes);
                const unsigned int up_sub2 =
                    block_sub2<HasZp>(zero_points_up, column, block, zp_row_bytes);
                const unsigned int gate_word = gate_word_next;
                const unsigned int up_word = up_word_next;
                if (depth_base + 256 + lane_depth + 8 <= k) {
                    gate_word_next = *reinterpret_cast<const unsigned int*>(
                        packed_gate_ptr + 128);
                    up_word_next = *reinterpret_cast<const unsigned int*>(
                        packed_up_ptr + 128);
                }
                accumulate_int4x8_f16_permuted_zp(
                    gate_word, permuted, *scale_gate_ptr, gate_sub2, g0, g1, g2, g3);
                accumulate_int4x8_f16_permuted_zp(
                    up_word, permuted, *scale_up_ptr, up_sub2, u0, u1, u2, u3);
                activation_ptr += 256;
                packed_gate_ptr += 128;
                packed_up_ptr += 128;
                scale_gate_ptr += 8;
                scale_up_ptr += 8;
            }
        } else {
            for (; depth_base + lane_depth + 8 <= k; depth_base += 256) {
                const uint4 permuted = permute_activation_f16x8(activation_ptr);
                const int block = (depth_base >> 5) + (lane >> 2);
                const unsigned int gate_word =
                    *reinterpret_cast<const unsigned int*>(packed_gate_ptr);
                const unsigned int up_word =
                    *reinterpret_cast<const unsigned int*>(packed_up_ptr);
                if constexpr (FusedSym) {
                    // Symmetric fast dequant: fold `- 8` into the bias constants
                    // (byte-identical, four fewer f16x2 ops/word).
                    accumulate_int4x8_f16_permuted_sym8(
                        gate_word, permuted, *scale_gate_ptr, g0, g1, g2, g3);
                    accumulate_int4x8_f16_permuted_sym8(
                        up_word, permuted, *scale_up_ptr, u0, u1, u2, u3);
                } else {
                    const unsigned int gate_sub2 = block_sub2<HasZp>(
                        zero_points_gate, column, block, zp_row_bytes);
                    const unsigned int up_sub2 = block_sub2<HasZp>(
                        zero_points_up, column, block, zp_row_bytes);
                    accumulate_int4x8_f16_permuted_zp(
                        gate_word, permuted, *scale_gate_ptr, gate_sub2, g0, g1, g2, g3);
                    accumulate_int4x8_f16_permuted_zp(
                        up_word, permuted, *scale_up_ptr, up_sub2, u0, u1, u2, u3);
                }
                activation_ptr += 256;
                packed_gate_ptr += 128;
                packed_up_ptr += 128;
                scale_gate_ptr += 8;
                scale_up_ptr += 8;
            }
        }
        const int tail_depth = depth_base + lane_depth;
        if (tail_depth < k) {
            const unsigned int gate_word =
                *reinterpret_cast<const unsigned int*>(packed_gate_ptr);
            const unsigned int up_word =
                *reinterpret_cast<const unsigned int*>(packed_up_ptr);
            const float gate_scale = __half2float(*scale_gate_ptr);
            const float up_scale = __half2float(*scale_up_ptr);
            const int tail_block = (depth_base >> 5) + (lane >> 2);
            const int gate_zp =
                block_zp<HasZp>(zero_points_gate, column, tail_block, zp_row_bytes);
            const int up_zp =
                block_zp<HasZp>(zero_points_up, column, tail_block, zp_row_bytes);
            const int valid = min(8, k - tail_depth);
#pragma unroll
            for (int i = 0; i < 8; ++i) {
                if (i < valid) {
                    const float a = __half2float(activation_ptr[i]);
                    const int qg = (int)((gate_word >> (i * 4)) & 15u) - gate_zp;
                    const int qu = (int)((up_word >> (i * 4)) & 15u) - up_zp;
                    gate_tail += (float)qg * a * gate_scale;
                    up_tail += (float)qu * a * up_scale;
                }
            }
        }
    }
    const float2 g04 = __half22float2(g0);
    const float2 g15 = __half22float2(g1);
    const float2 g26 = __half22float2(g2);
    const float2 g37 = __half22float2(g3);
    float gate_value = gate_tail + g04.x;
    gate_value += g15.x;
    gate_value += g26.x;
    gate_value += g37.x;
    gate_value += g04.y;
    gate_value += g15.y;
    gate_value += g26.y;
    gate_value += g37.y;
    gate_value = warp_sum(gate_value);

    const float2 u04 = __half22float2(u0);
    const float2 u15 = __half22float2(u1);
    const float2 u26 = __half22float2(u2);
    const float2 u37 = __half22float2(u3);
    float up_value = up_tail + u04.x;
    up_value += u15.x;
    up_value += u26.x;
    up_value += u37.x;
    up_value += u04.y;
    up_value += u15.y;
    up_value += u26.y;
    up_value += u37.y;
    up_value = warp_sum(up_value);

    if (lane == 0 && column < n) {
        const float gate_h = __half2float(__float2half(gate_value));
        const float up_h = __half2float(__float2half(up_value));
        const float silu_h = Decomposed
            ? gate_up_decomposed_silu_f32(gate_h)
            : gate_up_silu_f32(gate_h);
        output[column] = __float2half_rn(__fmul_rn(silu_h, up_h));
    }
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<false, false>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<false, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

// Fused-symmetric (`ONNX_GENAI_GATEUP_VEC`) siblings of the two SYMMETRIC
// RMS-norm-fused gate/up SwiGLU entries — the dominant qwen2.5-14b decode
// kernel is `..decomposed_swiglu_rmsnorm`. Byte-identical (folds the `- 8`
// symmetric zero point into the dequant bias constants; see
// `int4x8_to_half2x4_sym8`), only the issued instruction count drops.
extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_vec(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<false, false, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm_vec(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<false, true, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

// Occupancy-raised (`ONNX_GENAI_GATEUP_OCC`) siblings of the two SYMMETRIC
// RMS-norm-fused `_vec` entries. IDENTICAL kernel body and math — the only
// change is `__launch_bounds__(256, 8)`, which caps the register allocation at
// 32 regs/thread so the SM can co-resident 8 blocks (100% theoretical vs 75%
// register-limited). The dominant qwen2.5-14b decode kernel
// (`..decomposed_swiglu_rmsnorm`) is Short-Scoreboard/shared-load-latency bound
// (~51% of stall cycles waiting on the staged-activation LDS); the extra
// resident warps hide that latency. `__launch_bounds__` only constrains
// register allocation — same instruction stream, same fp16 accumulate order,
// same RMS reduction — so it is BYTE-IDENTICAL to the `_vec` entries above.
extern "C" __global__ void __launch_bounds__(256, 8)
matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_vec_occ(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<false, false, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

extern "C" __global__ void __launch_bounds__(256, 8)
matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm_vec_occ(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<false, true, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<true, false>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

extern "C" __global__ void matmul_nbits_gemv_f16_gate_up_decomposed_swiglu_rmsnorm_zp(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed_gate,
    const __half* __restrict__ scales_gate,
    const unsigned char* __restrict__ packed_up,
    const __half* __restrict__ scales_up,
    const unsigned char* __restrict__ zero_points_gate,
    const unsigned char* __restrict__ zero_points_up,
    const void* __restrict__ gamma,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int gamma_is_half,
    const float epsilon)
{
    matmul_nbits_gemv_f16_gate_up_swiglu_rmsnorm_tpl<true, true>(activation, packed_gate, scales_gate, packed_up, scales_up, zero_points_gate, zero_points_up, gamma, output, k, n, k_blocks, blob_size, zp_row_bytes, gamma_is_half, epsilon);
}

// Down projection specialization: a 256-thread CTA (8 warps) computes `COLS`
// columns and parallelizes over block-32 K tiles. Each thread loads its assigned
// activation block directly into registers and reuses it across all `COLS`
// columns, then the 8 warps combine their per-column partials through shared
// memory.
//
// `COLS` is a pure grid-fill knob: every output column is still reduced
// *entirely within one CTA* by all 256 threads striding the same K tiles in the
// same order, so the fp32 accumulation is bit-identical regardless of `COLS` —
// only the CTA count (grid = ceil(N / COLS)) changes. Tall-skinny down/output
// projections have a small N, so on many-SM devices the default 8-column launch
// underfills the machine (e.g. Qwen2.5-7B down: N=3584 -> 448 CTAs, ~0.57
// waves/SM on an H200). Halving `COLS` doubles the grid to fill the idle SMs on
// this latency-bound M=1 GEMV without changing the numerics; the host picks
// `COLS` from the device multiprocessor count (see `select_down_columns`).
template <int COLS>
__device__ __forceinline__ void matmul_nbits_gemv_f16_scales_f16_down_tpl(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int n,
    const int k_blocks,
    const int blob_size,
    const int bias_post_round)
{
    __shared__ float warp_sums[8][COLS];
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int column_base = (int)blockIdx.x * COLS;

    float values[COLS];
#pragma unroll
    for (int i = 0; i < COLS; ++i) {
        values[i] = 0.0f;
    }
    for (int block = tid; block < k_blocks; block += (int)blockDim.x) {
        const __half* activation_block = activation + block * 32;
        const uint4 activation0 = permute_activation_f16x8(activation_block);
        const uint4 activation1 = permute_activation_f16x8(activation_block + 8);
        const uint4 activation2 = permute_activation_f16x8(activation_block + 16);
        const uint4 activation3 = permute_activation_f16x8(activation_block + 24);
#pragma unroll
        for (int tile_column = 0; tile_column < COLS; ++tile_column) {
            const int column = column_base + tile_column;
            if (column < n) {
                const long packed_start =
                    ((long)column * k_blocks + block) * blob_size;
                const uint4 packed_weights =
                    *reinterpret_cast<const uint4*>(packed + packed_start);
                const __half scale = scales[(long)column * k_blocks + block];
                values[tile_column] += dot_int4x32_f16_permuted_scaled(
                    packed_weights,
                    activation0,
                    activation1,
                    activation2,
                    activation3,
                    scale);
            }
        }
    }

#pragma unroll
    for (int tile_column = 0; tile_column < COLS; ++tile_column) {
        const float value = warp_sum(values[tile_column]);
        if (lane == 0) {
            warp_sums[warp][tile_column] = value;
        }
    }
    __syncthreads();

    if (warp == 0 && lane < COLS) {
        const int column = column_base + lane;
        float value = warp_sums[0][lane];
        value += warp_sums[1][lane];
        value += warp_sums[2][lane];
        value += warp_sums[3][lane];
        value += warp_sums[4][lane];
        value += warp_sums[5][lane];
        value += warp_sums[6][lane];
        value += warp_sums[7][lane];
        if (column < n) {
            output[column] = fold_bias_f16(value, bias, column, bias_post_round);
        }
    }
}

// Default 8-column down projection (grid = ceil(N/8)).
extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_down(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    (void)k;
    (void)block_size;
    (void)zero_points;
    (void)zp_row_bytes;
    (void)scales_fp16;
    matmul_nbits_gemv_f16_scales_f16_down_tpl<8>(
        activation, packed, scales_raw, bias, output, n, k_blocks, blob_size,
        bias_post_round);
}

// Grid-fill down projection variants: fewer columns per CTA -> proportionally
// larger grid, bit-identical output. Selected on grid-starved (small-N) down
// shapes to fill the multiprocessors on latency-bound decode.
extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_down_c4(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    (void)k;
    (void)block_size;
    (void)zero_points;
    (void)zp_row_bytes;
    (void)scales_fp16;
    matmul_nbits_gemv_f16_scales_f16_down_tpl<4>(
        activation, packed, scales_raw, bias, output, n, k_blocks, blob_size,
        bias_post_round);
}

extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_down_c2(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    (void)k;
    (void)block_size;
    (void)zero_points;
    (void)zp_row_bytes;
    (void)scales_fp16;
    matmul_nbits_gemv_f16_scales_f16_down_tpl<2>(
        activation, packed, scales_raw, bias, output, n, k_blocks, blob_size,
        bias_post_round);
}

// Model-agnostic fp16 int4/int8 decode GEMV supporting any power-of-two
// block_size. One warp per output column. Each lane owns contiguous 8-element K
// chunks and strides by 256 (= 32 lanes * 8) across the reduction. Unlike the
// tuned block-32 kernels, the scale / zero-point block index is derived from the
// real block_size (block = depth / block_size), so a lane's 8-element chunk
// always resolves to the block it belongs to for any block width that is a
// multiple of 8 (all supported power-of-two block sizes >= 16). The `bits`
// scalar selects the packed layout: int4 unpacks two nibbles per byte with an
// optional int4 zero point (default 8, packed two block-nibbles per byte); int8
// reads one unsigned byte per weight with an optional uint8 zero point (default
// 128, one per block) — byte-for-byte the tuned block-32 int8 layout generalized
// to any block width. fp32 accumulation is preserved; the kernel is
// register-only (capture-safe).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;

    float value = 0.0f;
    if (column < n) {
        for (int depth = lane * 8; depth < k; depth += 256) {
            const int block = depth / block_size;
            const int within = depth - block * block_size;
            const long blob_base = ((long)column * k_blocks + block) * blob_size;
            float scale;
            if (scales_fp16) {
                scale = __half2float(
                    reinterpret_cast<const __half*>(scales)[(long)column * k_blocks + block]);
            } else {
                scale =
                    reinterpret_cast<const float*>(scales)[(long)column * k_blocks + block];
            }
            const int valid = min(8, k - depth);
            float partial = 0.0f;
            if (bits == 8) {
                const int zero_point =
                    zero_points ? (int)zero_points[(long)column * k_blocks + block] : 128;
                const unsigned char* block_bytes = packed + blob_base + within;
#pragma unroll
                for (int i = 0; i < 8; ++i) {
                    if (i < valid) {
                        const int q = (int)block_bytes[i] - zero_point;
                        partial += (float)q * __half2float(activation[depth + i]);
                    }
                }
            } else {
                int zero_point = 8;
                if (zero_points) {
                    const unsigned char zp =
                        zero_points[(long)column * zp_row_bytes + (block >> 1)];
                    zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
                }
                const unsigned int packed_word =
                    *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
                if (valid == 8) {
                    // Fast path: LOP3 int4->fp16 dequant + 128-bit activation
                    // load. Byte-identical to the scalar loop below (same
                    // ascending-order fp32 products) but replaces the per-nibble
                    // shift/and/convert with 4 lop3 + f16x2 debias, cutting the
                    // dequant-ALU pressure that dominates the block!=32 GEMV.
                    const unsigned int sub2 = int4_zero_point_sub2(zero_point);
                    partial = dot_int4x8_f16_sub(packed_word, activation + depth, sub2);
                } else {
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid) {
                            const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                            partial += (float)q * __half2float(activation[depth + i]);
                        }
                    }
                }
            }
            value += partial * scale;
        }
    }

    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

// Split-K counterpart of `matmul_nbits_gemv_f16_general_bs`: K_SPLIT warps
// cooperate on one output column, each walking a strided subset of the 256-wide
// K steps, then summing their fp32 partials through shared memory. The launch
// grid is K_SPLIT x larger than the single-warp kernel, which fills the SMs on
// the grid-starved, latency-bound block!=32 decode GEMV (the medium
// projections run at ~0.5 waves/SM single-warp). Each warp keeps the same fp32
// LOP3 dequant loop as the single-warp kernel, so the only numeric difference
// is the new K-slice partial-sum association (near-equal, not byte-identical) —
// the same trade the block-32 split-K entries already ship by default.
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_splitk(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    constexpr int K_SPLIT = 4;  // must match Rust GENERAL_BS_SPLITK
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int cols_per_block = warps_per_block / K_SPLIT;
    const int col_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const int column = (int)blockIdx.x * cols_per_block + col_local;

    __shared__ float partials[8][K_SPLIT];

    float value = 0.0f;
    if (column < n) {
        for (int depth = ks * 256 + lane * 8; depth < k; depth += K_SPLIT * 256) {
            const int block = depth / block_size;
            const int within = depth - block * block_size;
            const long blob_base = ((long)column * k_blocks + block) * blob_size;
            float scale;
            if (scales_fp16) {
                scale = __half2float(
                    reinterpret_cast<const __half*>(scales)[(long)column * k_blocks + block]);
            } else {
                scale =
                    reinterpret_cast<const float*>(scales)[(long)column * k_blocks + block];
            }
            const int valid = min(8, k - depth);
            float partial = 0.0f;
            if (bits == 8) {
                const int zero_point =
                    zero_points ? (int)zero_points[(long)column * k_blocks + block] : 128;
                const unsigned char* block_bytes = packed + blob_base + within;
#pragma unroll
                for (int i = 0; i < 8; ++i) {
                    if (i < valid) {
                        const int q = (int)block_bytes[i] - zero_point;
                        partial += (float)q * __half2float(activation[depth + i]);
                    }
                }
            } else {
                int zero_point = 8;
                if (zero_points) {
                    const unsigned char zp =
                        zero_points[(long)column * zp_row_bytes + (block >> 1)];
                    zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
                }
                const unsigned int packed_word =
                    *reinterpret_cast<const unsigned int*>(packed + blob_base + (within >> 1));
                if (valid == 8) {
                    const unsigned int sub2 = int4_zero_point_sub2(zero_point);
                    partial = dot_int4x8_f16_sub(packed_word, activation + depth, sub2);
                } else {
#pragma unroll
                    for (int i = 0; i < 8; ++i) {
                        if (i < valid) {
                            const int q = (int)((packed_word >> (i * 4)) & 15u) - zero_point;
                            partial += (float)q * __half2float(activation[depth + i]);
                        }
                    }
                }
            }
            value += partial * scale;
        }
    }

    value = warp_sum(value);
    if (lane == 0) {
        partials[col_local][ks] = (column < n) ? value : 0.0f;
    }
    __syncthreads();
    if (ks == 0 && lane == 0 && column < n) {
        float acc = 0.0f;
#pragma unroll
        for (int s = 0; s < K_SPLIT; ++s) {
            acc += partials[col_local][s];
        }
        output[column] = fold_bias_f16(acc, bias, column, bias_post_round);
    }
}

// Wide-load counterpart of `matmul_nbits_gemv_f16_general_bs` (see
// `gemv_int4_wide_lane_dot`). Same launch geometry (one warp per output column,
// 8 columns per 256-thread CTA) and same fp32/warp-sum reduction, but each lane
// streams 32 nibbles/step via a pipelined 128-bit weight load to lift DRAM
// throughput toward ORT's on the wide (already occupancy-filled) gate_up shape.
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_wide(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int columns_per_block = (int)blockDim.x >> 5;
    const int column = (int)blockIdx.x * columns_per_block + warp;

    float value = 0.0f;
    if (column < n) {
        value = gemv_int4_wide_lane_dot(
            activation, packed, scales, zero_points, k, block_size, k_blocks,
            blob_size, zp_row_bytes, scales_fp16, column, lane * 32, 32 * 32);
    }
    value = warp_sum(value);
    if (lane == 0 && column < n) {
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}

// Wide-load counterpart of `matmul_nbits_gemv_f16_general_bs_splitk`: K_SPLIT
// warps cooperate on one output column, each walking a `32 * K_SPLIT`-strided
// set of 32-nibble chunks with the pipelined 128-bit loads, then summing their
// fp32 partials through shared memory (same grid-fill as the narrow split-K).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_splitk_wide(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    constexpr int K_SPLIT = 4;  // must match Rust GENERAL_BS_SPLITK
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int cols_per_block = warps_per_block / K_SPLIT;
    const int col_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const int column = (int)blockIdx.x * cols_per_block + col_local;

    __shared__ float partials[8][K_SPLIT];

    float value = 0.0f;
    if (column < n) {
        value = gemv_int4_wide_lane_dot(
            activation, packed, scales, zero_points, k, block_size, k_blocks,
            blob_size, zp_row_bytes, scales_fp16, column, ks * 32 * 32 + lane * 32,
            K_SPLIT * 32 * 32);
    }
    value = warp_sum(value);
    if (lane == 0) {
        partials[col_local][ks] = (column < n) ? value : 0.0f;
    }
    __syncthreads();
    if (ks == 0 && lane == 0 && column < n) {
        float acc = 0.0f;
#pragma unroll
        for (int s = 0; s < K_SPLIT; ++s) {
            acc += partials[col_local][s];
        }
        output[column] = fold_bias_f16(acc, bias, column, bias_post_round);
    }
}

// Interleaved + biased (symmetric-only, OPT-IN) sibling of
// `matmul_nbits_gemv_f16_general_bs_splitk_wide`. Identical split-K geometry
// (K_SPLIT warps per column, shared-memory fp32 partial reduction), but consumes
// offline-interleaved weights and folds the symmetric -8 bias inside the LOP3
// converter. Because each lane's fp32 partial is bit-identical to the
// non-interleaved split-K wide kernel (see `gemv_int4_wide_lane_dot_interleaved`)
// and the K_SPLIT reduction order is unchanged, the output is byte-identical to
// `matmul_nbits_gemv_f16_general_bs_splitk_wide` on symmetric weights.
// `zero_points`/`zp_row_bytes`/`bits` are accepted for launch-signature parity
// but unused (the dispatch only routes symmetric int4 nodes here).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_splitk_wide_interleaved(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    (void)zero_points;
    (void)zp_row_bytes;
    (void)bits;
    constexpr int K_SPLIT = 4;  // must match Rust GENERAL_BS_SPLITK
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int cols_per_block = warps_per_block / K_SPLIT;
    const int col_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const int column = (int)blockIdx.x * cols_per_block + col_local;

    __shared__ float partials[8][K_SPLIT];

    float value = 0.0f;
    if (column < n) {
        value = gemv_int4_wide_lane_dot_interleaved(
            activation, packed, scales, k, block_size, k_blocks,
            blob_size, scales_fp16, column, ks * 32 * 32 + lane * 32,
            K_SPLIT * 32 * 32);
    }
    value = warp_sum(value);
    if (lane == 0) {
        partials[col_local][ks] = (column < n) ? value : 0.0f;
    }
    __syncthreads();
    if (ks == 0 && lane == 0 && column < n) {
        float acc = 0.0f;
#pragma unroll
        for (int s = 0; s < K_SPLIT; ++s) {
            acc += partials[col_local][s];
        }
        output[column] = fold_bias_f16(acc, bias, column, bias_post_round);
    }
}

// Multicol x split-K hybrid of `matmul_nbits_gemv_f16_general_bs_splitk_wide`.
// Combines the split-K grid-fill (K_SPLIT warps cooperate on one column group,
// summing their fp32 partials through shared memory) with the register-blocked
// wide-load multicol dot (each warp accumulates WIDE_NC output columns, issuing
// WIDE_NC independent 128-bit weight loads per chunk). The split-K path was
// picked for the grid-starved medium-N projections (down_proj N~4096, qkv/attn-
// out) *because* single-warp multicol under-fills the SMs there (~<1 wave); this
// hybrid restores the multicol memory-level parallelism (the lever that lifts the
// gate_up `wide_multicol` kernel to ~37% DRAM peak) WHILE keeping K_SPLIT so the
// grid still fills the device. Each lane's fp32 partial for (column, ks) uses the
// SAME depth0 (`ks*32*32 + lane*32`) and stride (`K_SPLIT*32*32`) as the
// single-column split-K wide kernel, the per-column accumulation order inside
// `gemv_int4_wide_lane_dot_multicol` is unchanged, and the K_SPLIT shared-memory
// reduction order is unchanged, so the output is BYTE-IDENTICAL to
// `matmul_nbits_gemv_f16_general_bs_splitk_wide`.
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    constexpr int K_SPLIT = 4;  // must match Rust GENERAL_BS_SPLITK_MULTICOL
    // 256-thread CTA (8 warps) => MAX_COL_GROUPS column groups per block.
    constexpr int MAX_COL_GROUPS = 8 / K_SPLIT;
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int col_groups_per_block = warps_per_block / K_SPLIT;
    const int group_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const long col_base =
        ((long)blockIdx.x * col_groups_per_block + group_local) * (long)WIDE_NC;

    __shared__ float partials[MAX_COL_GROUPS][WIDE_NC][K_SPLIT];

    float values[WIDE_NC];
    gemv_int4_wide_lane_dot_multicol(
        activation, packed, scales, zero_points, k, block_size, k_blocks,
        blob_size, zp_row_bytes, scales_fp16, col_base, n,
        ks * 32 * 32 + lane * 32, K_SPLIT * 32 * 32, values);
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        const float reduced = warp_sum(values[c]);
        if (lane == 0) {
            partials[group_local][c][ks] = reduced;
        }
    }
    __syncthreads();
    if (ks == 0 && lane == 0) {
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            const long column = col_base + c;
            if (column < n) {
                float acc = 0.0f;
#pragma unroll
                for (int s = 0; s < K_SPLIT; ++s) {
                    acc += partials[group_local][c][s];
                }
                output[column] = fold_bias_f16(acc, bias, column, bias_post_round);
            }
        }
    }
}

// Interleaved + biased (symmetric-only, OPT-IN) sibling of
// `matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol`. Same multicol x
// split-K geometry, but consumes offline nibble-interleaved weights and folds
// the symmetric -8 bias inside the LOP3 converter (dropping the per-block
// zero-point subtract and the `prmt.b32` activation reorder). Because each lane's
// fp32 partial is bit-identical to the non-interleaved multicol dot on symmetric
// weights and the K_SPLIT reduction order is unchanged, the output is
// byte-identical to `matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol`.
// `zero_points`/`zp_row_bytes`/`bits` are accepted for launch-signature parity
// but unused (the dispatch only routes symmetric int4 nodes here).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_splitk_wide_multicol_interleaved(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    (void)zero_points;
    (void)zp_row_bytes;
    (void)bits;
    constexpr int K_SPLIT = 4;  // must match Rust GENERAL_BS_SPLITK_MULTICOL
    constexpr int MAX_COL_GROUPS = 8 / K_SPLIT;
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const int col_groups_per_block = warps_per_block / K_SPLIT;
    const int group_local = warp / K_SPLIT;
    const int ks = warp % K_SPLIT;
    const long col_base =
        ((long)blockIdx.x * col_groups_per_block + group_local) * (long)WIDE_NC;

    __shared__ float partials[MAX_COL_GROUPS][WIDE_NC][K_SPLIT];

    float values[WIDE_NC];
    gemv_int4_wide_lane_dot_multicol_interleaved(
        activation, packed, scales, k, block_size, k_blocks,
        blob_size, scales_fp16, col_base, n,
        ks * 32 * 32 + lane * 32, K_SPLIT * 32 * 32, values);
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        const float reduced = warp_sum(values[c]);
        if (lane == 0) {
            partials[group_local][c][ks] = reduced;
        }
    }
    __syncthreads();
    if (ks == 0 && lane == 0) {
#pragma unroll
        for (int c = 0; c < WIDE_NC; ++c) {
            const long column = col_base + c;
            if (column < n) {
                float acc = 0.0f;
#pragma unroll
                for (int s = 0; s < K_SPLIT; ++s) {
                    acc += partials[group_local][c][s];
                }
                output[column] = fold_bias_f16(acc, bias, column, bias_post_round);
            }
        }
    }
}

// Column register-blocked wide-load GEMV (see `gemv_int4_wide_lane_dot_multicol`).
// Same launch geometry as `matmul_nbits_gemv_f16_general_bs_wide` (256-thread
// CTA, one warp per group), but every warp emits WIDE_NC output columns, so the
// grid covers `columns_per_block = 8 * WIDE_NC` columns per block. Decoding each
// activation sub-word once and reusing it across WIDE_NC columns relieves the
// L1/TEX-throughput limiter of the single-column wide kernel while staying
// byte-identical (per-column fp32 accumulation order unchanged).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_wide_multicol(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const long col_base =
        ((long)blockIdx.x * warps_per_block + warp) * (long)WIDE_NC;

    float values[WIDE_NC];
    gemv_int4_wide_lane_dot_multicol(
        activation, packed, scales, zero_points, k, block_size, k_blocks,
        blob_size, zp_row_bytes, scales_fp16, col_base, n, lane * 32, 32 * 32,
        values);
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        const float reduced = warp_sum(values[c]);
        const long column = col_base + c;
        if (lane == 0 && column < n) {
            output[column] = fold_bias_f16(reduced, bias, column, bias_post_round);
        }
    }
}

// Interleaved + biased (symmetric-only, OPT-IN) sibling of
// `matmul_nbits_gemv_f16_general_bs_wide_multicol`. Identical launch geometry
// and grid; consumes offline-interleaved weights and folds the symmetric -8
// bias inside the LOP3 converter, dropping the per-block zero-point subtract and
// the `prmt.b32` activation reorder. Byte-identical output to the fp32 multicol
// kernel on symmetric weights (see `gemv_int4_wide_lane_dot_multicol_interleaved`).
// `zero_points`/`zp_row_bytes` are accepted for launch-signature parity but
// unused (the dispatch only routes symmetric nodes here).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_wide_multicol_interleaved(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    (void)zero_points;
    (void)zp_row_bytes;
    (void)bits;
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const long col_base =
        ((long)blockIdx.x * warps_per_block + warp) * (long)WIDE_NC;

    float values[WIDE_NC];
    gemv_int4_wide_lane_dot_multicol_interleaved(
        activation, packed, scales, k, block_size, k_blocks,
        blob_size, scales_fp16, col_base, n, lane * 32, 32 * 32,
        values);
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        const float reduced = warp_sum(values[c]);
        const long column = col_base + c;
        if (lane == 0 && column < n) {
            output[column] = fold_bias_f16(reduced, bias, column, bias_post_round);
        }
    }
}

// Offline (once-per-weight) int4 nibble-interleave pass for the
// `ONNX_GENAI_INTERLEAVE_DEQUANT` lever. Reads the packed weight buffer as
// 32-bit words and rewrites each word from natural nibble order
// [e7 e6 e5 e4 | e3 e2 e1 e0] to TRT-LLM order [e7 e5 e3 e1 | e6 e4 e2 e0]
// (even elements to the low four nibble slots, odd to the high four). This is a
// pure per-word permutation, independent of block layout, so it applies to any
// int4 MatMulNBits weight whose byte count is a multiple of 4. Run once into a
// cached device buffer; the decode GEMV then reads the interleaved buffer.
extern "C" __global__ void matmul_nbits_interleave_int4(
    const unsigned int* __restrict__ src,
    unsigned int* __restrict__ dst,
    const unsigned long words)
{
    const unsigned long idx =
        (unsigned long)blockIdx.x * blockDim.x + threadIdx.x;
    if (idx >= words) {
        return;
    }
    const unsigned int w = src[idx];
    const unsigned int e0 = (w >> 0) & 0xfu;
    const unsigned int e1 = (w >> 4) & 0xfu;
    const unsigned int e2 = (w >> 8) & 0xfu;
    const unsigned int e3 = (w >> 12) & 0xfu;
    const unsigned int e4 = (w >> 16) & 0xfu;
    const unsigned int e5 = (w >> 20) & 0xfu;
    const unsigned int e6 = (w >> 24) & 0xfu;
    const unsigned int e7 = (w >> 28) & 0xfu;
    // Physical slots [n0..n7] = [e0,e2,e4,e6,e1,e3,e5,e7].
    dst[idx] = (e0 << 0) | (e2 << 4) | (e4 << 8) | (e6 << 12)
             | (e1 << 16) | (e3 << 20) | (e5 << 24) | (e7 << 28);
}

// fp16 mixed-precision sibling of `matmul_nbits_gemv_f16_general_bs_wide_multicol`
// (see `gemv_int4_fp16_lane_dot_multicol`). Same launch geometry and grid; the
// only difference is the per-chunk fp16 __hfma2 MAC. Opt-in (gated by
// `use_gemv_fp16`) and accuracy-gated (NOT byte-identical to the fp32 path).
extern "C" __global__ void matmul_nbits_gemv_f16_general_bs_wide_multicol_fp16(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round,
    const int bits)
{
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int warps_per_block = (int)blockDim.x >> 5;
    const long col_base =
        ((long)blockIdx.x * warps_per_block + warp) * (long)WIDE_NC;

    float values[WIDE_NC];
    gemv_int4_fp16_lane_dot_multicol(
        activation, packed, scales, zero_points, k, block_size, k_blocks,
        blob_size, zp_row_bytes, scales_fp16, col_base, n, lane * 32, 32 * 32,
        values);
#pragma unroll
    for (int c = 0; c < WIDE_NC; ++c) {
        const float reduced = warp_sum(values[c]);
        const long column = col_base + c;
        if (lane == 0 && column < n) {
            output[column] = fold_bias_f16(reduced, bias, column, bias_post_round);
        }
    }
}

// Model-agnostic fp16 int4/int8 prefill GEMM supporting any power-of-two
// block_size. Identical 16x16 tiling and fp32 accumulation as the tuned
// block-32 GEMM, but the reduction walks K in fixed 32-wide tiles and derives
// the block index from the real block_size (block = depth / block_size), so the
// K-tile width is decoupled from the block width. For block_size == 32 this is
// numerically identical to matmul_nbits_gemm_f16 (block == tile).
extern "C" __global__ void matmul_nbits_gemm_f16_general_bs(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int m,
    const int k,
    const int n,
    const int k_blocks,
    const int bits,
    const int scales_fp16,
    const int bias_post_round,
    const int bias_row_stride,
    const int block_size,
    const int blob_size)
{
    __shared__ float activation_tile[16][32];
    __shared__ float weight_tile[32][16];
    const int tid = (int)threadIdx.y * 16 + (int)threadIdx.x;
    const int row = (int)blockIdx.y * 16 + (int)threadIdx.y;
    const int column = (int)blockIdx.x * 16 + (int)threadIdx.x;
    float value = 0.0f;

    const int k_tiles = (k + 31) / 32;
    for (int tile = 0; tile < k_tiles; ++tile) {
#pragma unroll
        for (int load = tid; load < 16 * 32; load += 16 * 16) {
            const int tile_row = load >> 5;
            const int within = load & 31;
            const int depth = tile * 32 + within;
            const int global_row = (int)blockIdx.y * 16 + tile_row;
            activation_tile[tile_row][within] =
                global_row < m && depth < k
                    ? __half2float(activation[(long)global_row * k + depth])
                    : 0.0f;
        }
#pragma unroll
        for (int load = tid; load < 32 * 16; load += 16 * 16) {
            const int tile_column = load >> 5;
            const int within = load & 31;
            const int depth = tile * 32 + within;
            const int global_column = (int)blockIdx.x * 16 + tile_column;
            float weight = 0.0f;
            if (global_column < n && depth < k) {
                const int block = depth / block_size;
                const int within_block = depth - block * block_size;
                const long scale_index = (long)global_column * k_blocks + block;
                const float scale = scales_fp16
                    ? __half2float(
                        reinterpret_cast<const __half*>(scales_raw)[scale_index])
                    : reinterpret_cast<const float*>(scales_raw)[scale_index];
                const long blob_base =
                    ((long)global_column * k_blocks + block) * blob_size;
                int quantized;
                int zero_point;
                if (bits == 8) {
                    quantized = (int)packed[blob_base + within_block];
                    zero_point = zero_points ? (int)zero_points[scale_index] : 128;
                } else {
                    const unsigned char byte =
                        packed[blob_base + (within_block >> 1)];
                    quantized = (within_block & 1) ? (byte >> 4) : (byte & 15);
                    zero_point = 8;
                    if (zero_points) {
                        const int zp_row_bytes = (k_blocks + 1) >> 1;
                        const unsigned char zp =
                            zero_points[(long)global_column * zp_row_bytes + (block >> 1)];
                        zero_point = (block & 1) ? (zp >> 4) : (zp & 15);
                    }
                }
                weight = ((float)quantized - (float)zero_point) * scale;
            }
            weight_tile[within][tile_column] = weight;
        }
        __syncthreads();

        if (row < m && column < n) {
#pragma unroll
            for (int within = 0; within < 32; ++within) {
                value += activation_tile[threadIdx.y][within]
                    * weight_tile[within][threadIdx.x];
            }
        }
        __syncthreads();
    }

    if (row < m && column < n) {
        const __half* row_bias = bias ? bias + (long)row * bias_row_stride : bias;
        output[(long)row * n + column] =
            fold_bias_f16(value, row_bias, column, bias_post_round);
    }
}
"#;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum F16GemvVariant {
    General,
    DownProjection,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct F16GemvSelection {
    variant: F16GemvVariant,
    reason: &'static str,
}

/// Choose the fp16 int4 GEMV variant by **structural shape class + capability**,
/// never by a specific model's dimensions.
///
/// The specialized `DownProjection` tiling stages the entire activation in
/// shared memory once and reuses it across the 8 columns of a CTA while the full
/// 256-thread block cooperatively reduces along `K`. That wins on the
/// **tall-skinny** class — a `K > N` GEMV (reduction depth exceeds output width,
/// e.g. an MLP down-projection or attention output-projection) — where the long
/// reduction benefits from block-parallel accumulation and each thread reuses
/// its register-held activation block across the CTA's columns. It is only
/// *correct* under the tiling's
/// hard constraints, all derived from the kernel body:
///
/// * `scales_fp16` and 4-bit weights (this fp16 GEMV path is always 4-bit),
/// * no explicit zero-points (the specialized half2/down kernels encode zp=8),
/// * `block_size == 32` and `K % 32 == 0` (full K-blocks; the kernel has no
///   partial-block tail).
///
/// Every other shape (wide `N >= K` projections, non-block-32, non-multiple-of-32
/// `K`) falls back to the general per-warp GEMV. Selection is thus generic across
/// models: any architecture's down/output projection that fits the class is
/// accelerated, and nothing keys on a magic `K`/`N`.
fn select_f16_gemv_variant(
    k: usize,
    n: usize,
    block_size: usize,
    scales_fp16: bool,
    has_zero_points: bool,
) -> F16GemvSelection {
    let down_eligible = !has_zero_points
        && scales_fp16
        && block_size == GEMV_F16_DOWN_BLOCK_SIZE
        && k.is_multiple_of(GEMV_F16_DOWN_BLOCK_SIZE)
        && k > n;
    if down_eligible {
        F16GemvSelection {
            variant: F16GemvVariant::DownProjection,
            reason: "variant=down_projection;class=tall_skinny(K>N);block_size=32;\
                     scales=fp16;K%32==0",
        }
    } else {
        F16GemvSelection {
            variant: F16GemvVariant::General,
            reason: if has_zero_points {
                "variant=general;zero_points=explicit;down_projection requires symmetric zp=8"
            } else {
                "variant=general;class=not(tall_skinny K>N & block_size=32 & \
                 scales=fp16 & K%32==0)"
            },
        }
    }
}

/// Per-SM CTA target used to size the down-projection launch. The tuned down
/// kernel is register-limited to ~6 resident CTAs/SM on sm_90, so `SM_count * 6`
/// is roughly one wave. This latency-bound M=1 GEMV keeps improving past one
/// wave — more resident CTAs hide the dependent global-load latency — so we aim
/// for ~2 waves. Measured on Qwen2.5-7B down (K=18944, N=3584) on an H200 (132
/// SMs): 8 cols/CTA = 448 CTAs (~0.57 waves) = 301.9 tok/s; 4 cols = 896
/// (~1.1 waves) = 305.8; 2 cols = 1792 (~2.3 waves) = 308.5 (+2.2%); 1 col =
/// 3584 (~4.5 waves) fell back to ~302 as 8x activation re-reads and CTA
/// oversubscription cancelled the occupancy gain. So 2 waves is the sweet spot
/// and `COLS` is floored at 2.
const DOWN_FILL_CTAS_PER_SM: usize = 12;

/// Pick the down-projection columns-per-CTA (8, 4, or 2) and matching kernel
/// entry to fill the multiprocessors. The base 8-column launch emits `ceil(N/8)`
/// CTAs; on tall-skinny down/output projections `N` is small, so a many-SM
/// device is left grid-starved (well under one wave) on this latency-bound M=1
/// GEMV. Halving the columns-per-CTA doubles the grid with bit-identical
/// numerics (each column is still reduced entirely within one CTA in the same
/// order). We keep the largest `COLS` whose grid already meets the ~2-wave
/// per-SM CTA target, so wide down projections retain the cheaper 8-column
/// launch while narrow ones split just enough to fill; `COLS` never drops below
/// 2 (a 1-column launch over-subscribes and re-reads the activation 8x, erasing
/// the gain). Keys only on `N` and the SM count — no per-model magic — and
/// returns a launch-time constant that is stable across CUDA-graph replays.
fn select_down_columns(n: usize, multiprocessor_count: u32) -> (usize, &'static str) {
    let target = (multiprocessor_count.max(1) as usize).saturating_mul(DOWN_FILL_CTAS_PER_SM);
    for (cols, entry) in [
        (GEMV_F16_DOWN_COLUMNS_PER_BLOCK, GEMV_F16_DOWN_ENTRY),
        (4usize, GEMV_F16_DOWN_C4_ENTRY),
    ] {
        if n.div_ceil(cols) >= target {
            return (cols, entry);
        }
    }
    (2usize, GEMV_F16_DOWN_C2_ENTRY)
}

/// Per-SM CTA target for the fp32-activation accuracy_level=4 blockwise GEMV.
/// This is a dependent-global-load latency-bound M=1 GEMV, so — like the
/// down-projection launch — it keeps improving past one wave; aim for ~2 waves
/// of resident CTAs.
const ACCURACY4_GEMV_FILL_CTAS_PER_SM: usize = 12;
const F16_SYMMETRIC_SPLITK_TARGET_WARPS_PER_SM: usize = 16;

/// Per-SM CTA count at or above which a single-warp block-32 scales-fp16 int4
/// GEMV is considered WELL-OCCUPIED and routed to the lower-register plain entry
/// instead of the prefetch-pipelined one (see [`scales_f16_pipe_well_occupied`]).
/// The pipe kernel's deeper register footprint hides the Long-Scoreboard
/// weight-load latency on grid-starved (warp-capped) projections but only shaves
/// occupancy once the launch already has many resident waves — measured on the
/// qwen3.5-0.8b LM head (N=248320, grid=31040 ≈ 235 CTAs/SM on an H200): the
/// plain entry runs ~85.0 µs vs the pipe entry's ~98.8 µs (-14%), while the
/// grid-starved projections (N=4096, grid=512 ≈ 3.9 CTAs/SM) keep the pipe entry
/// (4.66 vs 4.79 µs). One resident wave of 8-warp CTAs is 8/SM on sm_90; the
/// crossover is far above that, so the threshold is set well clear of it.
const GEMV_F16_PIPE_WELL_OCCUPIED_CTAS_PER_SM: usize = 32;

/// Per-SM CTA target for the block!=32 general_bs split-K decode GEMV. The
/// single-warp `general_bs` launch emits one 256-thread (8-warp) CTA per 8
/// output columns, so a projection is grid-starved (leaves SMs idle, starving
/// the latency-bound global loads of in-flight work) when `ceil(N/8)` CTAs is
/// below ~2 waves of resident CTAs. glm-4-9b's medium projections (N=4096) sit
/// at ~0.5 waves single-warp; K_SPLIT=2 doubles the grid to ~1 wave. The fused
/// gate_up (N~27k) is already >3 waves and stays single-warp.
const GENERAL_BS_SPLITK_TARGET_CTAS_PER_SM: usize = 16;

/// Whether the block!=32 int4 decode GEMV should take the split-K entry
/// ([`GEMV_F16_GENERAL_BS_SPLITK_ENTRY`]) instead of the single-warp
/// [`GEMV_F16_GENERAL_BS_ENTRY`]. Enabled only for grid-starved int4
/// projections so the well-occupied wide GEMVs (fused gate_up) keep the
/// single-warp path. `ONNX_GENAI_GENERAL_SPLITK=0|1` forces off/on for A/B
/// measurement; unset uses the device-derived heuristic.
fn use_general_bs_splitk(k: usize, n: usize, bits: usize, multiprocessor_count: u32) -> bool {
    if let Some(forced) = general_bs_splitk_override() {
        return forced;
    }
    let single_warp_ctas = n.div_ceil((GEMV_F16_LARGE_THREADS / 32) as usize);
    bits == 4
        && k >= 512
        // Split-K needs >= K_SPLIT warps/block; the small-shape path uses only
        // 64 threads (2 warps) < K_SPLIT, so restrict to the 256-thread large
        // path (matches the block-32 split-K gating).
        && !(n <= GEMV_F16_SMALL_N_MAX && k <= GEMV_F16_SMALL_N_MAX)
        && single_warp_ctas
            < (multiprocessor_count.max(1) as usize)
                .saturating_mul(GENERAL_BS_SPLITK_TARGET_CTAS_PER_SM)
}

/// Developer override for the general_bs split-K decode GEMV: `1`/`true`/`on`
/// forces the split-K entry, `0`/`false`/`off` forces the single-warp entry,
/// and any other/unset value defers to the device-derived heuristic.
fn general_bs_splitk_override() -> Option<bool> {
    match std::env::var("ONNX_GENAI_GENERAL_SPLITK").ok().as_deref() {
        Some("1") | Some("true") | Some("on") => Some(true),
        Some("0") | Some("false") | Some("off") => Some(false),
        _ => None,
    }
}

/// Whether the block!=32 int4 decode GEMV should take the wide-load (128-bit
/// `uint4`, software-pipelined) entries ([`GEMV_F16_GENERAL_BS_WIDE_ENTRY`] /
/// [`GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY`]) instead of the 32-bit narrow-load
/// entries. Default-on (the wide load is portable — no SM80 intrinsic — and
/// raises DRAM bandwidth on the memory-latency-bound M=1 GEMV toward ORT's).
/// Restricted to int4 with `block_size % 32 == 0 && k % 32 == 0` so each lane's
/// 32-nibble `uint4` chunk lies inside a single block; other layouts fall back
/// to the narrow entry byte-for-byte. Only wired into the `block_size != 32`
/// general_bs dispatch arm (glm-class block-128 large-N GEMV, measured +35%
/// decode); the block-32 (`scales_f16` / fused gate_up) path was measured a
/// NO-GO — those kernels are compute/SM-bound, not DRAM-bound, so the wide
/// fp32 path is flat-to-negative there (see the decode decision drop), and they
/// keep their tuned fp16-accumulate narrow entries. `ONNX_GENAI_GEMV_WIDELOAD=0`
/// forces the narrow entry for A/B measurement, `1` forces wide where permitted.
fn use_gemv_wideload(bits: usize, block_size: usize, k: usize) -> bool {
    if bits != 4 || !block_size.is_multiple_of(32) || !k.is_multiple_of(32) {
        return false;
    }
    !matches!(
        std::env::var("ONNX_GENAI_GEMV_WIDELOAD").ok().as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Whether the non-split-K wide GEMV should take the column register-blocked
/// entry ([`GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY`]) instead of the
/// single-column [`GEMV_F16_GENERAL_BS_WIDE_ENTRY`]. Only consulted once
/// wide-load is already in effect (same int4 / `block_size % 32 == 0` /
/// `k % 32 == 0` preconditions, checked by the caller via [`use_gemv_wideload`]).
/// The multicol kernel decodes each activation sub-word once and reuses it
/// across [`GEMV_F16_WIDE_MULTICOL_NC`] columns; out-of-range columns are skipped
/// in-kernel, so any `n` is safe, and the result is byte-identical to the
/// single-column wide entry. `ONNX_GENAI_GEMV_WIDE_MULTICOL=0` forces the
/// single-column wide entry for A/B measurement.
fn use_gemv_wide_multicol() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_GEMV_WIDE_MULTICOL")
            .ok()
            .as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Whether the block!=32 general_bs split-K wide GEMV should take the multicol x
/// split-K hybrid entry ([`GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY`])
/// instead of the single-column split-K wide entry
/// ([`GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY`]). Only consulted once the split-K
/// wide path is already selected (`use_general_splitk && use_gemv_wideload`). The
/// hybrid register-blocks [`GEMV_F16_WIDE_MULTICOL_NC`] columns/warp to restore
/// the memory-level parallelism the single-column split-K kernel lacks, while
/// keeping K_SPLIT grid-fill; it is byte-identical to the single-column split-K
/// wide entry. Default-on; `ONNX_GENAI_GEMV_SPLITK_MULTICOL=0` forces the
/// single-column split-K wide entry for A/B measurement.
fn use_gemv_splitk_multicol() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_GEMV_SPLITK_MULTICOL")
            .ok()
            .as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Grid-fill override for the split-K wide path on GRID-STARVED narrow-N
/// projections (e.g. a GQA k/v projection: N = kv_heads * head_dim, ~256).
///
/// The multicol hybrid ([`GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY`])
/// register-blocks [`GEMV_F16_WIDE_MULTICOL_NC`] columns per warp group, so a
/// 256-thread (8-warp) CTA covers `(8 / GENERAL_BS_SPLITK_MULTICOL) *
/// GEMV_F16_WIDE_MULTICOL_NC` output columns and its launch grid is only
/// `ceil(N / cols_per_cta)`. That register blocking is a WIN on the medium/large
/// projections (down_proj / q / o at N~4096) where it lifts the memory-level
/// parallelism at ~1 wave, but on a narrow projection it collapses the grid so
/// far below the device SM count that most SMs sit idle (measured N=256 on GLM's
/// 2-kv-head GQA: grid=32 / ~0.06 waves / 2% DRAM / 6.1 us), starving the
/// latency-bound global loads of any in-flight parallelism to hide behind.
///
/// The single-column split-K wide entry
/// ([`GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY`]) covers only `8 /
/// GENERAL_BS_SPLITK` columns per CTA (4x fewer), so its grid is `4 *
/// GEMV_F16_WIDE_MULTICOL_NC` = 4x larger and fills those idle SMs. It is
/// BYTE-IDENTICAL to the multicol hybrid (same per-column depth0/stride, same
/// K_SPLIT reduction order — the only difference is how many columns a warp
/// register-blocks), so this is a pure occupancy swap, not a numeric change
/// (measured N=256: grid=32->128, 6.1->4.1 us / -33%). The medium/large
/// projections keep the multicol hybrid unchanged.
///
/// Returns true (prefer the single-column entry) when the multicol grid would
/// leave the device under-filled — `ceil(N / multicol_cols_per_cta) <
/// multiprocessor_count` — i.e. below ~1 CTA/SM from the column dimension. This
/// is shape/device-derived (narrow-N + SM count), not model-specific, so it
/// helps every GQA/MLA int4 model's narrow k/v projection. `unset` uses the
/// heuristic; `ONNX_GENAI_GEMV_SPLITK_SMALLN_SINGLECOL=0|1` forces off/on.
fn splitk_smalln_prefers_single_column(n: usize, multiprocessor_count: u32) -> bool {
    match std::env::var("ONNX_GENAI_GEMV_SPLITK_SMALLN_SINGLECOL")
        .ok()
        .as_deref()
    {
        Some("1") | Some("true") | Some("on") => return true,
        Some("0") | Some("false") | Some("off") => return false,
        _ => {}
    }
    // Columns covered by one 256-thread (8-warp) CTA of the multicol hybrid.
    let multicol_cols_per_cta = (8 / GENERAL_BS_SPLITK_MULTICOL) * GEMV_F16_WIDE_MULTICOL_NC;
    let multicol_grid = n.div_ceil(multicol_cols_per_cta.max(1));
    multicol_grid < multiprocessor_count.max(1) as usize
}

/// Whether the column register-blocked wide GEMV should take the fp16
/// mixed-precision entry ([`GEMV_F16_GENERAL_BS_WIDE_MULTICOL_FP16_ENTRY`])
/// instead of the fp32 [`GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY`]. Only
/// consulted once wide-load + multicol are already in effect. The fp16 kernel
/// runs the per-chunk MAC in `__hfma2` (matching ORT's fp16 arithmetic, the
/// equal-conditions fp16-vs-fp16 path) at the cost of NOT being byte-identical
/// to the fp32 path — so it is OPT-IN during the accuracy-validation phase via
/// `ONNX_GENAI_GEMV_FP16=1` and gated on accuracy (error <= ORT vs an f64
/// oracle), not bit-identity. It becomes default-on only after passing that gate.
fn use_gemv_fp16() -> bool {
    matches!(
        std::env::var("ONNX_GENAI_GEMV_FP16").ok().as_deref(),
        Some("1") | Some("true") | Some("on")
    )
}

/// Whether the M>1 half-precision path dequantizes to fp16 and runs the GEMM on
/// cuBLASLt tensor cores (`ONNX_GENAI_DEQUANT_F16_GEMM`, default ON).
///
/// Prefill on this shape is otherwise a choice between two slow kernels: the
/// `matmul_nbits_marlin_gemm_f16` int4 GEMM, which stages nothing in shared
/// memory and re-reads the whole A panel from global memory per warp, and the
/// f32 dequant fallback, which gives up tensor cores entirely. Materializing the
/// weights as fp16 and calling cuBLASLt costs one K*N pass over the weight and
/// then runs the matmul at the fp16 tensor-core rate.
///
/// Set to `0`/`false`/`off` to force the previous behaviour.
fn dequant_f16_gemm_enabled() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_DEQUANT_F16_GEMM").ok().as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Smallest M that takes the dequantize + fp16 cuBLASLt GEMM
/// (`ONNX_GENAI_DEQUANT_F16_GEMM_MIN_M`, default 8).
///
/// The dequantize pass costs a fixed K*N of bandwidth regardless of M, so it
/// only pays for itself once the GEMM has enough rows to amortize it. Below the
/// threshold the existing kernels, which read the weights in their packed form,
/// stay ahead.
fn dequant_f16_gemm_min_m() -> usize {
    std::env::var("ONNX_GENAI_DEQUANT_F16_GEMM_MIN_M")
        .ok()
        .and_then(|value| value.parse::<usize>().ok())
        .filter(|min_m| *min_m > 1)
        .unwrap_or(8)
}

/// Largest dequantized fp16 weight this path will materialize, in bytes
/// (`ONNX_GENAI_DEQUANT_F16_GEMM_MAX_SCRATCH`, default 1 GiB).
///
/// The scratch is transient, but a vocabulary projection is far larger than any
/// other node in the graph, and expanding one to fp16 would dwarf the GEMM it
/// feeds. Oversized nodes fall through rather than allocate.
fn dequant_f16_gemm_max_scratch_bytes() -> usize {
    std::env::var("ONNX_GENAI_DEQUANT_F16_GEMM_MAX_SCRATCH")
        .ok()
        .and_then(|value| value.parse::<usize>().ok())
        .unwrap_or(1 << 30)
}

/// Offer published by `run_bf16` for the duration of the staged fp16 call it
/// makes on this same thread.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Bf16DirectOut {
    /// fp16 staging buffer the fp16 path would otherwise write.
    staging: CUdeviceptr,
    /// Real bf16 destination the GEMV may write instead.
    dst: CUdeviceptr,
    /// Elements the caller's output holds. A launch may only accept the offer
    /// if it writes all of them: `run_f16` loops one single-row GEMV per row
    /// for `1 < m <= decode_gemv_loop_max_m()`, and row 0 of that loop starts
    /// at the staging pointer, so a pointer match alone would let row 0 claim
    /// the whole output and leave rows 1.. unwritten.
    elements: usize,
    /// Set once a GEMV has accepted the offer, so `run_bf16` knows to skip the
    /// narrowing cast and so a second GEMV in the same call cannot take it.
    taken: bool,
}

thread_local! {
    /// Thread-local rather than a field on the op: `run_bf16` calls the fp16
    /// path synchronously on the calling thread, so the offer cannot outlive
    /// that call or be observed by a concurrent session executing the same
    /// node. Acceptance additionally requires an exact match on the staging
    /// pointer, so an unrelated fp16 node can never claim it.
    static BF16_DIRECT_OUT: std::cell::Cell<Option<Bf16DirectOut>> =
        const { std::cell::Cell::new(None) };
}

thread_local! {
    /// Count of GEMV launches that narrowed straight into a bf16 output. Tests
    /// assert this moves, so a routing change that silently reverts to the
    /// staged cast fails loudly instead of passing on an unexercised equality.
    /// Thread-local like the offer itself, so tests running in parallel cannot
    /// perturb each other's deltas.
    static BF16_DIRECT_OUT_STORES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

/// Accept the pending bf16 direct-store offer if it targets `staging`.
fn take_bf16_direct_out(staging: CUdeviceptr, elements: usize) -> Option<CUdeviceptr> {
    BF16_DIRECT_OUT.with(|cell| match cell.get() {
        Some(mut offer)
            if !offer.taken && offer.staging == staging && offer.elements == elements =>
        {
            offer.taken = true;
            cell.set(Some(offer));
            BF16_DIRECT_OUT_STORES.with(|count| count.set(count.get() + 1));
            Some(offer.dst)
        }
        _ => None,
    })
}

/// Opt-in gate for the TRT-LLM-style interleaved + biased int4 decode dequant
/// (`ONNX_GENAI_INTERLEAVE_DEQUANT`). Default OFF: the lever bakes an offline
/// nibble-interleave into the packed weights and folds the symmetric `-8` bias
/// into the LOP3 converter, dropping the per-block zero-point `sub.f16x2` and the
/// `prmt.b32` activation reorder from the decode inner loop. Byte-identical to the
/// fp32 multicol path on symmetric weights. Only routes symmetric (no zero-point)
/// block!=32 int4 nodes that already qualify for the wide-load multicol kernel;
/// every other node is untouched.
///
/// It stays opt-in because the speedup is bought with memory, not for free:
/// [`ensure_interleaved`] allocates a SECOND copy of every routed weight and
/// keys the cache off the ORIGINAL packed pointer, which ORT owns and does not
/// free while the session runs. So the routed int4 weights are resident TWICE
/// for the life of the runtime that built them, which is what releases them
/// (see [`crate::interleave_cache`]). Measured +8.6% on H200 (211.9 → 230.0
/// tok/s, glm base); on a 20 GB int4 model that costs ~20 GB extra VRAM, which is
/// why it must NOT be defaulted on for the memory-tight consumer cards that would
/// otherwise benefit most from the instruction-count win.
fn interleave_dequant_enabled() -> bool {
    matches!(
        std::env::var("ONNX_GENAI_INTERLEAVE_DEQUANT")
            .ok()
            .as_deref(),
        Some("1") | Some("true") | Some("on")
    )
}

/// Default-on gate for the prefetch-pipelined block-32 scales-fp16 split-K int4
/// GEMV. The `_pf` entries are bit-identical drop-ins for the plain split-K
/// entries (same launch geometry and accumulation order), differing only in that
/// each lane keeps several weight-word loads in flight to hide the
/// Long-Scoreboard weight-load latency the split-K loop otherwise stalls on.
/// `ONNX_GENAI_ZP_SPLITK_PREFETCH=0` forces the plain entry for A/B measurement.
fn use_scales_f16_zp_splitk_pf() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_ZP_SPLITK_PREFETCH")
            .ok()
            .as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Runs the device side of the offline nibble-interleave for the cache in
/// [`crate::interleave_cache`].
///
/// The interleave itself lives on [`CudaRuntime`] rather than in a module
/// global: the cache key is a device address, an address is only a name for a
/// buffer while the allocator that minted it is alive, and the runtime is the
/// type that owns that allocator. The rules and their falsifiers are in
/// [`crate::interleave_cache`]; the device work is here because the interleave
/// pass is a kernel in this module's NVRTC source.
impl crate::interleave_cache::InterleaveDevice for CudaRuntime {
    fn interleave_device_id(&self) -> u64 {
        self.runtime_id()
    }

    fn interleave_alloc(&self, bytes: usize) -> Result<CUdeviceptr> {
        self.alloc_raw(bytes)
    }

    unsafe fn interleave_free(&self, ptr: CUdeviceptr) {
        // SAFETY: forwarded under the caller's obligation that `ptr` came from
        // `interleave_alloc` above and is freed once.
        let _ = unsafe { self.free_raw(ptr) };
    }

    fn interleave_build(&self, src: CUdeviceptr, dst: CUdeviceptr, bytes: usize) -> Result<()> {
        launch_interleave_int4(self, src, dst, bytes)
    }

    fn interleave_is_capturing(&self) -> Result<bool> {
        self.is_capturing()
    }

    fn interleave_frees_are_observed(&self) -> bool {
        !self.weights_may_be_paged()
    }

    fn interleave_drain_before_free(&self) -> Result<()> {
        self.drain_for_unmap()
    }
}

/// Launch the once-per-weight int4 nibble-interleave pass over `bytes` bytes
/// (`bytes` must be a multiple of 4). Reads `src` as 32-bit words and writes the
/// TRT-LLM interleaved order into `dst`.
fn launch_interleave_int4(
    runtime: &CudaRuntime,
    src: CUdeviceptr,
    dst: CUdeviceptr,
    bytes: usize,
) -> Result<()> {
    let words = (bytes / 4) as u64;
    let function = runtime.nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, INTERLEAVE_INT4_ENTRY)?;
    let src_ptr = cuptr(src as usize as *const c_void);
    let dst_ptr = cuptr(dst as usize as *const c_void);
    const THREADS: u32 = 256;
    let grid = u32::try_from(words.div_ceil(THREADS as u64))
        .unwrap_or(u32::MAX)
        .max(1);
    let mut builder = runtime.stream().launch_builder(&function);
    builder.arg(&src_ptr).arg(&dst_ptr).arg(&words);
    // SAFETY: static grid; `src`/`dst` each cover `bytes` bytes and the kernel
    // bounds-checks the word index against `words`.
    unsafe {
        builder.launch(LaunchConfig {
            grid_dim: (grid, 1, 1),
            block_dim: (THREADS, 1, 1),
            shared_mem_bytes: 0,
        })
    }
    .map(|_| ())
    .map_err(|err| driver_err("launch MatMulNBits int4 interleave", err))
}

/// Ensure the offline-interleaved copy of the `bytes`-byte packed weight buffer
/// at `packed` exists on device, running the device interleave once and caching
/// the result on `runtime`. Returns `(interleaved_ptr, warm)`; `warm == true`
/// means the buffer was already cached (no allocation / interleave / sync this
/// call, so it is CUDA-graph capture-safe). A cold miss while capturing is
/// rejected so the caller falls back to the non-interleaved path rather than
/// allocating inside a capture.
///
/// The entry is keyed by `(packed, bytes)` and lives no longer than `runtime`,
/// which is what makes a device address a valid identity for it.
fn ensure_interleaved(
    runtime: &Arc<CudaRuntime>,
    packed: CUdeviceptr,
    bytes: usize,
) -> Result<(CUdeviceptr, bool)> {
    runtime.ensure_interleaved_int4(packed, bytes)
}

fn use_f16_symmetric_splitk(
    k: usize,
    n: usize,
    multiprocessor_count: u32,
    max_threads_per_block: u32,
) -> bool {
    let eligible =
        k >= 512 && k.is_multiple_of(32) && max_threads_per_block >= GEMV_F16_LARGE_THREADS;
    if !eligible {
        return false;
    }
    n < (multiprocessor_count.max(1) as usize)
        .saturating_mul(F16_SYMMETRIC_SPLITK_TARGET_WARPS_PER_SM)
}

/// Gate for the ASYMMETRIC (zero-point) block-32 `scales_f16` split-K int4
/// decode GEMV, where `K_SPLIT=2` warps cooperate on each output column.
///
/// Split-K pays off for two independent reasons, and this gate covers both.
///
/// The first is occupancy: on a grid-STARVED projection the `K_SPLIT=2` fan-out
/// doubles the grid and fills idle SMs. That is the only reason this gate used
/// to recognise, mirroring the symmetric path (`n < SMs * target`), on the
/// argument that split-K must be a net loss once `ceil(N/8)` single-warp CTAs
/// already fill the device many waves over — so wide-N projections were routed
/// to the single-warp pipe entry instead.
///
/// Measurement does not support that argument. Batch-1 decode of a 26B int4
/// model (K = 6656 and 19968, N = 5k-20k) on a 108-SM A100-SXM4-80GB is
/// **faster** with split-K even though its grid is saturated many waves over:
/// marginal kernel time 48.30 -> 45.90 ms/token (-5.0%) and 4120 -> 3494 kernel
/// launches/token (-15%), nsys-measured with `--cuda-graph-trace=node` over a
/// 32-vs-96-token difference, agreeing in direction with wall clock (27.4 ->
/// 28.5 tok/s over paired runs).
///
/// The reason is the second one: a batch-1 decode GEMV is bound by weight
/// bandwidth, not by the grid. Splitting K halves each column's serial load
/// chain and so doubles the memory-level parallelism per output column, which
/// matters precisely when K is large. The occupancy argument prices the cost
/// (a shared-mem cross-warp reduction plus a per-split activation re-read) but
/// never priced this benefit; on these shapes the benefit is larger.
///
/// So: grid-starved OR large-K. The K threshold is set at the low end of what
/// has actually been measured rather than extrapolated downwards -- below it the
/// original occupancy-only rule stands, because no measurement contradicts it
/// there.
///
/// The split changes the reduction ORDER, so results are not bit-identical to
/// the single-warp pipe entry. That is acceptable for a bf16/fp16 decode path
/// and was checked end to end: 96 greedy tokens of the 26B model are unchanged.
///
/// Keys only on K, N and the live SM count -- no model constants.
/// `ONNX_GENAI_SCALES_F16_ZP_SPLITK=0|1` forces off/on for A/B measurement.
fn use_scales_f16_zp_splitk_gate(k: usize, n: usize, multiprocessor_count: u32) -> bool {
    match std::env::var("ONNX_GENAI_SCALES_F16_ZP_SPLITK")
        .ok()
        .as_deref()
    {
        Some("1") | Some("true") | Some("on") => return true,
        Some("0") | Some("false") | Some("off") => return false,
        _ => {}
    }
    let grid_starved = n
        < (multiprocessor_count.max(1) as usize)
            .saturating_mul(F16_SYMMETRIC_SPLITK_TARGET_WARPS_PER_SM);
    grid_starved || k >= ZP_SPLITK_BANDWIDTH_MIN_K
}

/// Warps cooperating per output column for the asymmetric block-32 split-K
/// decode GEMV. [`use_scales_f16_zp_splitk_gate`] decides WHETHER to split K;
/// this decides HOW FAR.
///
/// The default factor of 2 doubles a starved grid, which was enough for the
/// medium projections it was tuned against but not for the GQA k/v projection.
/// At N=256 a 256-thread CTA still covers 4 output columns, so the whole launch
/// is 64 blocks on a 108-SM A100 -- under a single wave, with 8 of 64 possible
/// warps resident per SM and nothing to hide the weight-load latency behind. It
/// measured 28 GB/s, 1.4% of peak, while the SAME K at N=4096 moved 16x the
/// bytes in 21% LESS time. No bandwidth explanation survives that comparison, so
/// the cost is grid starvation, and the remedy is more grid.
///
/// So: if the grid is still under one wave AFTER the default split, split all the
/// way down to one output column per CTA.
fn scales_f16_zp_split_factor(n: usize, multiprocessor_count: u32) -> usize {
    let warps_per_cta = (GEMV_F16_LARGE_THREADS / 32) as usize;
    let blocks_at_default = n.div_ceil(warps_per_cta / GEMV_F16_SCALES_F16_ZP_SPLITK);
    if blocks_at_default < multiprocessor_count.max(1) as usize {
        GEMV_F16_SCALES_F16_ZP_SPLITK8
    } else {
        GEMV_F16_SCALES_F16_ZP_SPLITK
    }
}

/// Smallest K at which split-K has been measured to win on a saturated grid.
///
/// 6656 is the narrower of the two reduction depths in the 26B measurement
/// above; 19968 is the other. Nothing below this has been measured, so the
/// threshold sits on the evidence rather than beneath it.
const ZP_SPLITK_BANDWIDTH_MIN_K: usize = 6656;

/// Warps-per-CTA (one warp reduces one output column) for the accuracy_level=4
/// blockwise GEMV, chosen so the `ceil(N / warps)` grid fills the device. The
/// grid-starved tiled `matmul_nbits_accuracy4` fallback issued only
/// `ceil(M*N / 256)` CTAs (4 CTAs for a 1024-wide decode projection); here each
/// output column is a warp, so an 8-warp CTA already emits `ceil(N/8)` CTAs. On
/// narrow projections a many-SM device would still be under the ~2-wave target,
/// so the warp count is halved (down to a single warp) until the grid fills.
/// Keying only on `N` and the SM count keeps the choice a launch-time constant
/// that is stable across CUDA-graph replays and never hard-codes a GPU.
fn select_accuracy4_gemv_warps(n: usize, multiprocessor_count: u32) -> u32 {
    if let Some(forced) = std::env::var("ONNX_GENAI_ACC4_WARPS")
        .ok()
        .and_then(|value| value.parse::<u32>().ok())
        .filter(|warps| matches!(warps, 1 | 2 | 4 | 8))
    {
        return forced;
    }
    let target =
        (multiprocessor_count.max(1) as usize).saturating_mul(ACCURACY4_GEMV_FILL_CTAS_PER_SM);
    for warps in [8usize, 4, 2] {
        if n.div_ceil(warps) >= target {
            return warps as u32;
        }
    }
    1
}

/// Select the wider activation stage only when the fixed 8-warp block-32 launch
/// does not provide one resident CTA wave. The estimate uses architectural warp
/// limits via [`crate::arch::decode_resident_warps_per_sm`]: datacenter
/// sm_80/sm_90 parts expose 64 warps/SM, while sm_86/sm_89 consumer parts expose
/// 48. Routing the ladder through the arch layer keeps this decode selector's
/// occupancy math byte-identical to the previous inline `match` (crucially
/// sm_90 → 64) while giving the pending RTX split-K tuning a single seam.
/// Hudson's general blockwise path keeps its separate device-derived warp-width
/// selection.
fn use_accuracy4_stage64(
    n: usize,
    multiprocessor_count: u32,
    compute_capability: (u32, u32),
    max_shared_memory_per_block: u32,
) -> bool {
    if max_shared_memory_per_block < GEMV_ACCURACY4_STAGE64_SHARED_BYTES {
        return false;
    }
    let resident_warps = crate::arch::decode_resident_warps_per_sm(compute_capability) as usize;
    let resident_ctas = resident_warps / (GEMV_ACCURACY4_THREADS as usize / 32);
    let one_wave = (multiprocessor_count.max(1) as usize).saturating_mul(resident_ctas);
    n.div_ceil(GEMV_ACCURACY4_COLUMNS_PER_BLOCK) < one_wave
}

/// Optional developer override for the down-projection columns-per-CTA, used to
/// A/B the grid-fill variants. `ONNX_GENAI_DOWN_COLS=8|4|2` forces that width;
/// any other/unset value keeps the device-driven [`select_down_columns`] choice.
fn down_columns_override() -> Option<(usize, &'static str)> {
    match std::env::var("ONNX_GENAI_DOWN_COLS").ok()?.as_str() {
        "8" => Some((GEMV_F16_DOWN_COLUMNS_PER_BLOCK, GEMV_F16_DOWN_ENTRY)),
        "4" => Some((4, GEMV_F16_DOWN_C4_ENTRY)),
        "2" => Some((2, GEMV_F16_DOWN_C2_ENTRY)),
        _ => None,
    }
}

/// Whether the single-warp block-32 scales-fp16 int4 decode GEMV takes the
/// prefetch-pipelined entry (4 weight loads in flight per lane to hide the
/// Long-Scoreboard global-load latency). Byte-identical to the original entry,
/// so it is default-on; `ONNX_GENAI_GEMV_PIPELINE=0` (or `false`/`off`) forces
/// the original single-load entry for A/B measurement.
fn scales_f16_pipeline_enabled() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_GEMV_PIPELINE").ok().as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Opt-out for the SYMMETRIC (no zero-point) int8 decode GEMV split-K grid-fill.
/// The asymmetric int8 GEMV already routes grid-starved shapes to the split-K
/// entry; the symmetric path was historically pinned to its single-warp kernel
/// purely to stay BYTE-IDENTICAL (split-K reassociates the per-column fp32
/// partial sums). Now that decode correctness is validated on the GREEDY
/// TOKEN-ID lock (not a byte-exact lock) — and fp32 accumulation is preserved,
/// so the reassociation is a ULP-level shift that leaves the argmax stable, the
/// same trade already shipped for the symmetric int4 split-K
/// ([`use_f16_symmetric_splitk`]) — the symmetric int8 path may take the same
/// grid-fill split-K on the grid-starved projections. Default-on; set
/// `ONNX_GENAI_CUDA_DISABLE_INT8_SYMMETRIC_SPLITK=1` (or `true`/`on`) to force
/// the byte-identical single-warp entry for A/B measurement or de-risking.
fn int8_symmetric_splitk_enabled() -> bool {
    !std::env::var_os("ONNX_GENAI_CUDA_DISABLE_INT8_SYMMETRIC_SPLITK")
        .is_some_and(|value| value != "0" && !value.is_empty())
}

/// Whether a single-warp block-32 scales-fp16 int4 GEMV launch is WELL-OCCUPIED
/// enough that it should take the lower-register plain entry
/// ([`GEMV_F16_SCALES_F16_ENTRY`]) instead of the prefetch-pipelined entry
/// ([`GEMV_F16_SCALES_F16_PIPE_ENTRY`]). Both entries are BYTE-IDENTICAL (same
/// lane→nibble mapping, same fp16 accumulation order), so this is a pure
/// occupancy/register trade, not a numeric change. The pipe entry's extra
/// registers pay off only on grid-starved (warp-capped) projections where the
/// scheduler has too few resident warps to hide the Long-Scoreboard weight-load
/// latency; once the launch already fills the SMs many times over (e.g. the
/// wide LM-head projection), the pipe entry's lower occupancy makes it a net
/// loss and the plain entry wins. Keys only on `N`, the launch width and the
/// live SM count (no per-model magic); returns a launch-time constant stable
/// across CUDA-graph replays. `ONNX_GENAI_GEMV_PIPELINE=0` still forces the
/// plain entry everywhere for A/B; `ONNX_GENAI_GEMV_PIPE_WELLOCC=0` forces the
/// pipe entry even on well-occupied launches (restores the pre-gate behavior).
fn scales_f16_pipe_well_occupied(
    n: usize,
    columns_per_block: usize,
    multiprocessor_count: u32,
) -> bool {
    match std::env::var("ONNX_GENAI_GEMV_PIPE_WELLOCC")
        .ok()
        .as_deref()
    {
        Some("0") | Some("false") | Some("off") => return false,
        Some("1") | Some("true") | Some("on") => return true,
        _ => {}
    }
    let ctas = n.div_ceil(columns_per_block.max(1));
    let threshold = (multiprocessor_count.max(1) as usize)
        .saturating_mul(GEMV_F16_PIPE_WELL_OCCUPIED_CTAS_PER_SM);
    ctas >= threshold
}

/// Whether the SYMMETRIC paired gate/up SwiGLU decode GEMV takes the
/// fused-symmetric (`_vec`) entry, which folds the `- 8` symmetric zero point
/// into the dequant bias constants and so issues four fewer `f16x2` ops per
/// weight word. That kernel is the largest decode kernel on qwen2.5-14b and is
/// issue-bound (ncu: ~28% DRAM, ~48% issue-active), so cutting issued
/// instructions is the right lever (prefetch/`uint4` loads do not help: the
/// loads are already 128B-coalesced per warp and strided per lane). The `_vec`
/// entry is BYTE-IDENTICAL to the default entry — every dequant intermediate is
/// an exactly-representable fp16 integer, so folding the two constant
/// subtractions changes no rounding — so it is default-on;
/// `ONNX_GENAI_GATEUP_VEC=0` (or `false`/`off`) forces the scalar entry for A/B
/// measurement.
fn gate_up_vec_enabled() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_GATEUP_VEC").ok().as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

/// Whether the SYMMETRIC RMS-norm-fused gate/up SwiGLU decode GEMV takes the
/// occupancy-raised `_vec_occ` entry (`__launch_bounds__(256, 8)` → 32 regs,
/// 8 blocks/SM, 100% theoretical vs 75% register-limited). That kernel is the
/// largest decode kernel on qwen2.5-14b and is Short-Scoreboard bound (~51% of
/// stall cycles wait on the staged-activation shared load); the extra resident
/// warps hide the latency (isolated ncu: 57.5 -> 54.0us, occupancy 62 -> 82%;
/// E2E +2.6% on 14b). Byte-identical to the `_vec` entry — `__launch_bounds__`
/// only constrains register allocation. DEFAULT-ON; `ONNX_GENAI_GATEUP_OCC=0`
/// (or `false`/`off`) forces the non-occ path for A/B.
fn gate_up_occ_enabled() -> bool {
    !matches!(
        std::env::var("ONNX_GENAI_GATEUP_OCC").ok().as_deref(),
        Some("0") | Some("false") | Some("off")
    )
}

pub struct MatMulNBitsFactory {
    pub runtime: Arc<CudaRuntime>,
}

impl KernelFactory for MatMulNBitsFactory {
    fn create(&self, node: &Node, _input_shapes: &[Vec<usize>]) -> Result<Box<dyn Kernel>> {
        let k = required_positive_attr(node, "K")?;
        let n = required_positive_attr(node, "N")?;
        let bits = optional_int_attr(node, "bits")?.unwrap_or(4);
        if !matches!(bits, 4 | 8) {
            return Err(error(format!(
                "MatMulNBits CUDA supports bits in {{4, 8}}, got bits={bits}. Why: the native \
                 kernels implement packed int4 and int8 layouts. How to fix: export bits=4 or \
                 bits=8, or select another execution provider"
            )));
        }
        let weight_prepacked = optional_int_attr(node, "weight_prepacked")?.unwrap_or(0);
        if weight_prepacked != 0 {
            return Err(error(format!(
                "weight_prepacked={weight_prepacked} is unsupported: CUDA only supports the standard (non-prepacked) layout"
            )));
        }
        let block_size = required_positive_attr(node, "block_size")?;
        if block_size < 16 || !block_size.is_power_of_two() {
            return Err(error(format!(
                "block_size must be a power of two and at least 16, got {block_size}"
            )));
        }
        // int8 at block_size==32 uses the tuned four-lane/eight-block GEMV; any
        // other power-of-two int8 block width routes to the model-agnostic
        // general-block-size GEMV/GEMM (both implement the one-byte-per-weight
        // layout), so no int8 block width is rejected here.
        let accuracy_level = node
            .attr("accuracy_level")
            .and_then(|value| value.as_int())
            .unwrap_or(0);

        let accuracy4_workspace = if bits == 4 && accuracy_level == 4 {
            Some(Mutex::new(Accuracy4Workspace::new(
                self.runtime.clone(),
                k,
                block_size,
            )?))
        } else {
            None
        };
        Ok(Box::new(MatMulNBitsKernel {
            runtime: self.runtime.clone(),
            k,
            n,
            bits: bits as usize,
            block_size,
            accuracy_level,
            accuracy4_workspace,
            marlin_repack_cache: marlin_gemm::RepackCache::new(self.runtime.clone()),
            constant_inputs: [false; 8],
            fold_bias_post_round: node
                .attr(crate::optimizer::MATMUL_NBITS_FOLDED_BIAS_ATTR)
                .and_then(onnx_runtime_ir::Attribute::as_int)
                == Some(1),
            gate_up_swiglu: node
                .attr(crate::optimizer::GATE_UP_SWIGLU_FUSION_ATTR)
                .and_then(onnx_runtime_ir::Attribute::as_int)
                == Some(1),
            decomposed_silu: node
                .attr(crate::optimizer::DECOMPOSED_SILU_ATTR)
                .and_then(onnx_runtime_ir::Attribute::as_int)
                == Some(1),
            rmsnorm_prologue: node
                .attr(crate::optimizer::MATMUL_NBITS_RMSNORM_PROLOGUE_ATTR)
                .and_then(onnx_runtime_ir::Attribute::as_int)
                == Some(1),
            rmsnorm_epsilon: node
                .attr(crate::optimizer::MATMUL_NBITS_RMSNORM_EPSILON_ATTR)
                .and_then(onnx_runtime_ir::Attribute::as_float)
                .unwrap_or(1e-5),
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(self.runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(self.runtime.clone())),
        }))
    }
}

#[derive(Debug)]
struct Accuracy4Workspace {
    allocation: Arc<GraphDeviceAllocation>,
    quantized_activation: CUdeviceptr,
    activation_scale: CUdeviceptr,
    padded_k: usize,
}

impl Accuracy4Workspace {
    fn new(runtime: Arc<CudaRuntime>, k: usize, block_size: usize) -> Result<Self> {
        let padded_k = k.div_ceil(block_size) * block_size;
        // Per-K-block int8 activation scales: one f32 per weight block.
        let k_blocks = padded_k / block_size;
        let scale_bytes = k_blocks * std::mem::size_of::<f32>();
        let allocation = GraphDeviceAllocation::allocate(&runtime, padded_k + scale_bytes)?;
        let quantized_activation = allocation.ptr();
        Ok(Self {
            allocation,
            quantized_activation,
            activation_scale: quantized_activation + padded_k as CUdeviceptr,
            padded_k,
        })
    }
}

impl Accuracy4Workspace {
    fn device_graph_resource(&self) -> DeviceGraphResource {
        GraphDeviceAllocation::device_graph_resource(&self.allocation)
    }
}

/// Reusable device scratch for the BFloat16 activation path.
///
/// BFloat16 operands are staged through Float16 (see
/// [`MatMulNBitsKernel::run_bf16`]). A per-node allocation + free for each
/// staging buffer would synchronize the device on every one of the hundreds of
/// MatMulNBits nodes per decode step (`cuMemAlloc`/`cuMemFree` are synchronous),
/// collapsing throughput. This grow-only arena is carved into per-call regions
/// and reused across decode steps, so after the first step the BFloat16 path
/// issues only asynchronous casts and the tuned fp16 matmul — no device sync.
/// Each kernel instance owns its own arena, and consecutive uses are ordered on
/// the EP stream, so region reuse never races.
#[derive(Debug)]
struct Bf16Scratch {
    runtime: Arc<CudaRuntime>,
    allocation: Option<Arc<GraphDeviceAllocation>>,
    cap: usize,
    used: bool,
}

impl Bf16Scratch {
    fn new(runtime: Arc<CudaRuntime>) -> Self {
        Self {
            runtime,
            allocation: None,
            cap: 0,
            used: false,
        }
    }

    fn begin_call(&mut self) {
        self.used = false;
    }

    /// Ensure the arena holds at least `bytes`, returning its base pointer.
    fn ensure(&mut self, bytes: usize) -> Result<CUdeviceptr> {
        self.used = true;
        if bytes > self.cap {
            if self.allocation.is_some() {
                self.runtime.drain_for_unmap()?;
            }
            self.allocation = Some(GraphDeviceAllocation::allocate(
                &self.runtime,
                bytes.max(1),
            )?);
            self.cap = bytes;
        }
        Ok(self
            .allocation
            .as_ref()
            .map_or(0, |allocation| allocation.ptr()))
    }

    fn device_graph_resource(&self) -> Option<DeviceGraphResource> {
        if !self.used {
            return None;
        }
        self.allocation
            .as_ref()
            .map(GraphDeviceAllocation::device_graph_resource)
    }
}

/// Persistent per-kernel cache of the Float16-staged **constant** inputs on the
/// BFloat16 activation path. A node's scales / zero-point-scales / gamma are
/// immutable weights, but the original `run_bf16` re-cast them from BFloat16 to
/// Float16 into an ephemeral arena on *every* decode step. For Muse-Glimmer that
/// is ~3.3 GB/token of pure-copy traffic (≈25% of the int4 weight traffic) doing
/// nothing but reproducing an identical Float16 buffer. This cache stages each
/// constant once (keyed by its device pointer + element count) and reuses the
/// result across steps. Converting BFloat16→Float16 in one staging pass is
/// byte-identical whether done once or per step, so decode output is unchanged.
#[derive(Debug)]
struct Bf16ConstCache {
    runtime: Arc<CudaRuntime>,
    allocation: Option<Arc<GraphDeviceAllocation>>,
    cap: usize,
    used: bool,
    /// One entry per cached constant: `(src_ptr, numel, byte_offset)`.
    slots: Vec<(CUdeviceptr, usize, usize)>,
}

impl Bf16ConstCache {
    fn new(runtime: Arc<CudaRuntime>) -> Self {
        Self {
            runtime,
            allocation: None,
            cap: 0,
            used: false,
            slots: Vec::new(),
        }
    }

    fn begin_call(&mut self) {
        self.used = false;
    }

    /// Return the Float16 device pointers holding the staged copies of the
    /// BFloat16 constants described by `consts` (`(src_ptr, numel)` each),
    /// casting them on first use and reusing them thereafter. The staged buffer
    /// is allocated once (before CUDA-graph capture, during warmup) and never
    /// grows again for a given node, so replays hit only cache lookups.
    fn staged(&mut self, consts: &[(CUdeviceptr, usize)]) -> Result<Vec<CUdeviceptr>> {
        self.used = true;
        let matches =
            self.slots.len() == consts.len()
                && self.slots.iter().zip(consts).all(
                    |((src, numel, _), (want_src, want_numel))| {
                        *src == *want_src && *numel == *want_numel
                    },
                );
        if !matches {
            self.rebuild(consts)?;
        }
        Ok(self
            .slots
            .iter()
            .map(|(_, _, offset)| {
                self.allocation
                    .as_ref()
                    .map_or(0, |allocation| allocation.ptr())
                    + *offset as CUdeviceptr
            })
            .collect())
    }

    fn rebuild(&mut self, consts: &[(CUdeviceptr, usize)]) -> Result<()> {
        const ALIGN: usize = 256;
        let f16 = std::mem::size_of::<half::f16>();
        let round = |bytes: usize| bytes.div_ceil(ALIGN) * ALIGN;
        let mut slots = Vec::with_capacity(consts.len());
        let mut total = 0usize;
        for (src, numel) in consts {
            slots.push((*src, *numel, total));
            total += round(numel * f16);
        }
        if total > self.cap {
            if self.allocation.is_some() {
                self.runtime.drain_for_unmap()?;
            }
            self.allocation = Some(GraphDeviceAllocation::allocate(
                &self.runtime,
                total.max(1),
            )?);
            self.cap = total;
        }
        let base = self
            .allocation
            .as_ref()
            .map_or(0, |allocation| allocation.ptr());
        for (src, numel, offset) in &slots {
            super::cast::launch_cast_raw(
                &self.runtime,
                cuptr(*src as *const c_void),
                DataType::BFloat16,
                base + *offset as CUdeviceptr,
                DataType::Float16,
                *numel,
            )?;
        }
        self.slots = slots;
        Ok(())
    }

    fn device_graph_resource(&self) -> Option<DeviceGraphResource> {
        if !self.used {
            return None;
        }
        self.allocation
            .as_ref()
            .map(GraphDeviceAllocation::device_graph_resource)
    }
}

#[derive(Debug)]
pub struct MatMulNBitsKernel {
    runtime: Arc<CudaRuntime>,
    k: usize,
    n: usize,
    bits: usize,
    block_size: usize,
    accuracy_level: i64,
    accuracy4_workspace: Option<Mutex<Accuracy4Workspace>>,
    /// Repacked immutable weights owned by this kernel. Owner scoping prevents a
    /// later kernel from hitting stale contents when CUDA reuses an address.
    marlin_repack_cache: marlin_gemm::RepackCache,
    /// Session-lifetime graph constants. Only immutable weights may enter the
    /// owner-scoped Marlin repack cache.
    constant_inputs: [bool; 8],
    /// Set when this node's bias input came from folding a standalone `Add`
    /// (see [`crate::optimizer::MATMUL_NBITS_FOLDED_BIAS_ATTR`]). The fp16 GEMV
    /// then reproduces the two-op `fp16(fp16(acc) + bias)` rounding.
    fold_bias_post_round: bool,
    /// Set on a synthetic node produced by
    /// [`crate::optimizer::CudaGateUpSwiGluFusion`]: inputs are
    /// `[x, W_gate, scales_gate, W_up, scales_up]` and the kernel writes
    /// `silu(gate) * up` directly (see [`GATE_UP_SWIGLU_ENTRY`]).
    gate_up_swiglu: bool,
    decomposed_silu: bool,
    /// Set on a general fp16 GEMV whose input activation must be RMS-normalized
    /// in-kernel before the int4 dot, produced by
    /// [`crate::optimizer::CudaSkipRmsNormMatMulFusion`]. The `gamma` weight is
    /// bound at input slot 6 and the kernel reproduces
    /// `skip_rmsnorm_f16_warp_half4` bit-for-bit (see
    /// [`GEMV_F16_SCALES_F16_RMSNORM_ENTRY`]).
    rmsnorm_prologue: bool,
    /// Epsilon copied from the folded `SkipSimplifiedLayerNormalization` node so
    /// the fused prologue reproduces its `1/sqrt(mean_sq + epsilon)`.
    rmsnorm_epsilon: f32,
    last_call_capture_safe: AtomicBool,
    /// Reusable Float16 staging arena for the BFloat16 activation path.
    bf16_scratch: Mutex<Bf16Scratch>,
    /// Persistent Float16 staging of the BFloat16 *constant* inputs (scales,
    /// gamma) so they are cast once rather than re-cast every decode step.
    bf16_const_cache: Mutex<Bf16ConstCache>,
}

impl MatMulNBitsKernel {
    fn marlin_weight_inputs_constant(&self) -> bool {
        marlin_weight_inputs_are_constant(&self.constant_inputs, self.gate_up_swiglu)
    }

    fn release_marlin_repack_for_decode(&self) {
        // The Marlin repack is a second, tensor-core-layout copy of this op's
        // weights, allocated raw (invisible to the VMM arena) and only read by
        // the M > 1 tensor-core GEMM. At decode it is pure device overhead:
        // measured at ~384 MiB on a 1.8B model whose weights are under 1 GiB.
        //
        // The atomic load is the steady-state cost; the drop happens at most
        // once per prefill→decode transition, and a later prefill simply
        // repacks. Never release during capture, where freeing device memory
        // would invalidate the graph.
        if self.marlin_repack_cache.retained_bytes() > 0
            && !self.runtime.is_capturing().unwrap_or(true)
        {
            self.marlin_repack_cache.release_all();
        }
    }

    fn run(
        &self,
        inputs: &[TensorView],
        outputs: &mut [TensorMut],
        workspace: Option<WorkspaceView>,
    ) -> Result<()> {
        self.last_call_capture_safe.store(false, Ordering::Relaxed);
        self.marlin_repack_cache.begin_call();
        self.bf16_scratch
            .lock()
            .map_err(|_| error("BFloat16 scratch lock poisoned"))?
            .begin_call();
        self.bf16_const_cache
            .lock()
            .map_err(|_| error("BFloat16 constant cache lock poisoned"))?
            .begin_call();
        let max_inputs = if self.gate_up_swiglu { 8 } else { 7 };
        if !(3..=max_inputs).contains(&inputs.len()) || outputs.len() != 1 {
            return Err(error(format!(
                "expected 3 to {max_inputs} inputs and 1 output, got {} inputs and {} outputs",
                inputs.len(),
                outputs.len()
            )));
        }
        if inputs[0].dtype == DataType::Float16 {
            if self.gate_up_swiglu {
                return self.run_f16_gate_up_swiglu(inputs, outputs, workspace);
            }
            return self.run_f16(inputs, outputs, workspace);
        }
        if inputs[0].dtype == DataType::BFloat16 {
            return self.run_bf16(inputs, outputs, workspace);
        }
        require_dtype("A", inputs[0].dtype, DataType::Float32)?;
        require_dtype("B", inputs[1].dtype, DataType::Uint8)?;
        require_dtype("scales", inputs[2].dtype, DataType::Float32)?;
        require_dtype("Y", outputs[0].dtype, DataType::Float32)?;
        let a_shape = inputs[0].shape;
        if a_shape.is_empty() || a_shape[a_shape.len() - 1] != self.k {
            return Err(error(format!(
                "A must have rank >= 1 and last dimension K={}, got {:?}",
                self.k, a_shape
            )));
        }
        let expected_output_shape = [&a_shape[..a_shape.len() - 1], &[self.n]].concat();
        if outputs[0].shape != expected_output_shape {
            return Err(error(format!(
                "Y must have shape {expected_output_shape:?}, got {:?}",
                outputs[0].shape
            )));
        }

        let k_blocks = self.k.div_ceil(self.block_size);
        let blob_size = self.block_size * self.bits / 8;
        require_shape("B", inputs[1].shape, &[self.n, k_blocks, blob_size])?;
        require_flat_or_matrix_shape("scales", inputs[2].shape, self.n, k_blocks)?;

        let zero_points = optional_input(inputs, 3);
        let zp_row_bytes = (k_blocks * self.bits).div_ceil(8);
        if let Some(zp) = zero_points {
            require_dtype("zero_points", zp.dtype, DataType::Uint8)?;
            require_flat_or_matrix_shape("zero_points", zp.shape, self.n, zp_row_bytes)?;
        }

        let group_indices = optional_input(inputs, 4);
        if let Some(g_idx) = group_indices {
            require_dtype("g_idx", g_idx.dtype, DataType::Int32)?;
            if !g_idx.is_contiguous() {
                return Err(error(
                    "g_idx must be contiguous on the CUDA execution provider",
                ));
            }
            let padded_k = k_blocks * self.block_size;
            if g_idx.shape != [self.k] && g_idx.shape != [padded_k] {
                return Err(error(format!(
                    "g_idx must have shape [{}] or [{padded_k}], got {:?}",
                    self.k, g_idx.shape
                )));
            }
            let mut bytes = vec![0u8; g_idx.numel() * 4];
            // SAFETY: `g_idx` is a live contiguous device tensor and `bytes`
            // exactly covers all of its i32 elements.
            unsafe {
                self.runtime
                    .dtoh(&mut bytes, cuptr(g_idx.data_ptr::<u8>() as *const c_void))?
            };
            for (index, value) in bytes.chunks_exact(4).enumerate() {
                let group = i32::from_ne_bytes([value[0], value[1], value[2], value[3]]);
                if group < 0 || group as usize >= k_blocks {
                    return Err(error(format!(
                        "g_idx[{index}]={group} is outside 0..{k_blocks}"
                    )));
                }
            }
        }

        let bias = optional_input(inputs, 5);
        if let Some(bias) = bias {
            require_dtype("bias", bias.dtype, DataType::Float32)?;
            require_shape("bias", bias.shape, &[self.n])?;
        }

        for (name, contiguous) in [
            ("A", inputs[0].is_contiguous()),
            ("B", inputs[1].is_contiguous()),
            ("scales", inputs[2].is_contiguous()),
            (
                "zero_points",
                zero_points.is_none_or(TensorView::is_contiguous),
            ),
            ("g_idx", group_indices.is_none_or(TensorView::is_contiguous)),
            ("bias", bias.is_none_or(TensorView::is_contiguous)),
            ("Y", outputs[0].is_contiguous()),
        ] {
            if !contiguous {
                return Err(error(format!(
                    "{name} must be contiguous on the CUDA execution provider"
                )));
            }
        }

        let m = a_shape[..a_shape.len() - 1].iter().product::<usize>();
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let mut flops = (m as u64)
                .saturating_mul(self.n as u64)
                .saturating_mul(self.k as u64)
                .saturating_mul(2);
            if bias.is_some() {
                flops = flops.saturating_add((m as u64).saturating_mul(self.n as u64));
            }
            flops
        });
        self.last_call_capture_safe
            .store(m == 1 && group_indices.is_none(), Ordering::Relaxed);
        if m == 1 && group_indices.is_none() {
            self.release_marlin_repack_for_decode();
            if self.bits == 4
                && self.block_size == 128
                && let Some(zero_points) = zero_points
            {
                // The asymmetric int4/block-128 fp32 path is the dominant Qwen3
                // decode kernel. Its specialized entry preserves the generic
                // GEMV's arithmetic and reduction order while replacing block
                // division/modulo with shifts, hoisting metadata row bases, and
                // loading each warp's packed nibbles as four aligned u32 words.
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_int4_f32_block128",
                    "M==1 decode: bits=4, block_size=128, asymmetric → specialized \
                     shift-indexed int4 f32 GEMV (bit-identical to the generic path)"
                );
                return self.launch_int4_f32_gemv_block128(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    bias,
                    &mut outputs[0],
                    k_blocks,
                );
            }
            if self.bits == 8 && self.block_size == 128 && zero_points.is_some() {
                // Qwen3-0.6B's dominant decode kernel: int8, block-128,
                // asymmetric (per-block byte zero point), fp32 activations. The
                // generic f32 GEMV below handles this correctly but pays a
                // per-weight integer divide/modulo, a runtime bit-width branch,
                // and repeated scale/zero-point base recomputation. This
                // specialization folds block_size=128 into a shift and hoists the
                // per-column base while preserving each thread's depth order and
                // fp32 reduction, so its output is bit-for-bit identical. Launch
                // geometry is unchanged (one CTA per column, BLOCK_THREADS lanes,
                // no shared memory or arch-specific instructions) so it stays
                // capture-safe and portable across SM counts and CCs.
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_int8_f32_block128",
                    "M==1 decode: bits=8, block_size=128, asymmetric → specialized \
                     shift-indexed int8 f32 GEMV (bit-identical to the generic path)"
                );
                return self.launch_int8_f32_gemv_block128(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    bias,
                    &mut outputs[0],
                    k_blocks,
                );
            }
            if self.bits == 8 && self.block_size == 32 {
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_int8_f32",
                    "M==1 decode: bits=8, block_size=32 → direct capture-safe f32 GEMV"
                );
                return self.launch_int8_f32_gemv(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    bias,
                    &mut outputs[0],
                    k_blocks,
                );
            }
            if self.bits == 8 {
                // int8 at any non-block-32 power-of-two block size: the tuned
                // int8 f32 GEMV bakes in the block-32 geometry, so route to the
                // model-agnostic general f32 GEMV, which derives the block index
                // from the real block_size and accumulates in fp32. accuracy_level
                // 4 (int8-activation) has no block-size-general kernel, so fp32
                // accumulation is used instead (strictly higher precision than the
                // int8-activation reference), keeping the path capture-safe.
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_f32_general_bs_int8",
                    "M==1 decode: bits=8, block_size={} → model-agnostic f32 GEMV \
                     (fp32 accumulation, any power-of-two block_size)",
                    self.block_size
                );
                return self.launch_f32_gemv(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    bias,
                    &mut outputs[0],
                    k_blocks,
                    blob_size,
                    zp_row_bytes,
                );
            }
            if self.accuracy_level == 4 && self.block_size == 32 && zero_points.is_none() {
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_accuracy4_int8",
                    "M==1 decode: accuracy_level==4, block_size==32, symmetric (no zero_points) \
                     → int8-quantized-activation capture-safe GEMV"
                );
                return self.launch_accuracy4_gemv(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    bias,
                    &mut outputs[0],
                    k_blocks,
                );
            }
            if self.bits == 4 && self.accuracy_level == 4 {
                if self.block_size == 32 {
                    onnx_runtime_ep_api::record_kernel_variant!(
                        "gemv_accuracy4_blockwise_int8",
                        "M==1 decode: bits=4, accuracy_level==4, block_size=32 → int8-quantized \
                         activation quantized ONCE then parallelized blockwise GEMV (grid filled \
                         from the device SM count; bit-identical to the tiled accuracy4 GEMM)"
                    );
                    return self.launch_accuracy4_gemv_blockwise(
                        &inputs[0],
                        &inputs[1],
                        &inputs[2],
                        zero_points,
                        bias,
                        &mut outputs[0],
                        k_blocks,
                        blob_size,
                        zp_row_bytes,
                    );
                }
                // accuracy_level 4 requests int8-quantized activations, but the
                // int8 activation quantum is only calibrated at block_size=32
                // (the size the blockwise/tiled accuracy4 kernels bake in). At
                // larger block sizes (e.g. 128) quantizing the activations to
                // int8 discards enough precision to flip razor-thin decode logit
                // ties and diverge from the fp32 reference, so accumulate the
                // activations in fp32 instead. This mirrors the int8/non-block-32
                // path above and the int8/block-128 specialization: fp32
                // activations are strictly higher precision than the
                // int8-activation reference and match the fp32 oracle stream.
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_f32_general_bs_int4",
                    "M==1 decode: bits=4, accuracy_level==4, block_size={} (≠32) → \
                     model-agnostic f32 GEMV (fp32 activations, higher precision than the \
                     int8-activation reference)",
                    self.block_size
                );
                return self.launch_f32_gemv(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    bias,
                    &mut outputs[0],
                    k_blocks,
                    blob_size,
                    zp_row_bytes,
                );
            }
            if self.accuracy_level != 4 {
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_f32",
                    "M==1 decode: accuracy_level={} (non-accuracy4) → direct f32 GEMV",
                    self.accuracy_level
                );
                return self.launch_f32_gemv(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    bias,
                    &mut outputs[0],
                    k_blocks,
                    blob_size,
                    zp_row_bytes,
                );
            }
        }
        if self.bits == 4
            && self.accuracy_level == 4
            && self.block_size == 32
            && group_indices.is_none()
        {
            onnx_runtime_ep_api::record_kernel_variant!(
                "gemm_tiled_accuracy4",
                "M={} (GEMV requires M==1), accuracy_level==4, block_size=32, no g_idx → \
                 tiled accuracy4 GEMM (int8-quantized activations)",
                m
            );
            return self.launch_accuracy4(
                &inputs[0],
                &inputs[1],
                &inputs[2],
                zero_points,
                bias,
                &mut outputs[0],
                m,
                k_blocks,
                blob_size,
                zp_row_bytes,
            );
        }

        onnx_runtime_ep_api::record_kernel_variant!(
            "dequant_cublas_gemm",
            "M={}, accuracy_level={}, g_idx={} → dequantize weights to f32 then cuBLAS GEMM \
             (general prefill / grouped path)",
            m,
            self.accuracy_level,
            group_indices.is_some()
        );

        let weight = self.runtime.alloc_raw(self.k * self.n * 4)?;
        let result = self
            .launch_dequant(
                &inputs[1],
                &inputs[2],
                zero_points,
                group_indices,
                weight,
                k_blocks,
                blob_size,
                zp_row_bytes,
            )
            .and_then(|()| {
                let params = GemmParams {
                    dtype: GemmDtype::F32,
                    a: cuptr(inputs[0].data_ptr::<u8>() as *const c_void),
                    b: weight,
                    c: cuptr(outputs[0].data_ptr_mut::<u8>() as *const c_void),
                    m,
                    k: self.k,
                    n: self.n,
                    batch: 1,
                    a_batch_stride: m * self.k,
                    b_batch_stride: 0,
                    epilogue: bias.map(|bias| GemmEpilogue {
                        kind: GemmEpilogueKind::Bias,
                        bias: cuptr(bias.data_ptr::<u8>() as *const c_void),
                    }),
                };
                // SAFETY: validated dense f32 A/Y and the dequantized [K,N]
                // allocation cover the complete GEMM; workspace and stream live
                // through the call and Y aliases neither input.
                unsafe {
                    blas::governed_gemm(
                        self.runtime.blas(),
                        self.runtime.stream_ptr(),
                        &params,
                        workspace,
                        "MatMulNBits",
                    )
                }
            })
            .and_then(|()| self.runtime.synchronize());

        // SAFETY: `weight` came from `alloc_raw` and is released once, after all
        // submitted work has synchronized (or the submission failed).
        let free_weight = unsafe { self.runtime.free_raw(weight) };
        result.and(free_weight)
    }

    fn uses_dequant_cublas_workspace(
        &self,
        dtype: DataType,
        a_shape: &[usize],
        group_indices_present: bool,
    ) -> bool {
        if dtype != DataType::Float32 || a_shape.is_empty() || a_shape[a_shape.len() - 1] != self.k
        {
            return false;
        }
        let m = a_shape[..a_shape.len() - 1].iter().product::<usize>();
        if m == 1 && !group_indices_present {
            return false;
        }
        !(self.bits == 4
            && self.accuracy_level == 4
            && self.block_size == 32
            && !group_indices_present)
    }

    /// Whether a half-precision activation at M>1 would take the dequantize +
    /// fp16 cuBLASLt tensor-core GEMM, which needs the same declared workspace
    /// the f32 fallback does. BFloat16 counts: it stages through Float16 and
    /// lands on the very same path, carrying this workspace with it.
    fn uses_dequant_f16_cublas_workspace(
        &self,
        dtype: DataType,
        a_shape: &[usize],
        group_indices_present: bool,
    ) -> bool {
        if !matches!(dtype, DataType::Float16 | DataType::BFloat16)
            || a_shape.is_empty()
            || a_shape[a_shape.len() - 1] != self.k
            || group_indices_present
        {
            return false;
        }
        let m = a_shape[..a_shape.len() - 1].iter().product::<usize>();
        // Deliberately looser than the launch-site gates: this only has to be an
        // upper bound. Declaring a workspace a call turns out not to need costs
        // nothing, whereas under-declaring makes `governed_gemm_ex` fail at
        // launch — after the dequantize has already run — and silently fall back.
        dequant_f16_gemm_enabled()
            && m >= dequant_f16_gemm_min_m()
            && self.k.saturating_mul(self.n).saturating_mul(2)
                <= dequant_f16_gemm_max_scratch_bytes()
    }

    fn workspace_requirement_for(
        &self,
        inputs: &[TensorMetadata<'_>],
    ) -> Result<WorkspaceRequirement> {
        let Some(a) = inputs.first() else {
            return Ok(WorkspaceRequirement::NONE);
        };
        let group_indices_present = inputs.get(4).is_some_and(|input| input.present);
        // The fused gate/up node has no group-index or bias slot: it spends
        // inputs 3..=4 on the up projection's packed weights and scales, and
        // 5..=6 on the two zero-point tensors. Reading them positionally, as the
        // unfused node does, makes every fused node look group-indexed and
        // bias-carrying, which silently denies it a workspace.
        let fused = self.gate_up_swiglu;
        let dtype = if self.uses_dequant_cublas_workspace(a.dtype, a.shape, group_indices_present) {
            GemmDtype::F32
        } else if self.uses_dequant_f16_cublas_workspace(
            a.dtype,
            a.shape,
            !fused && group_indices_present,
        ) {
            GemmDtype::F16
        } else {
            return Ok(WorkspaceRequirement::NONE);
        };
        let m = a.shape[..a.shape.len() - 1].iter().product::<usize>();
        if dtype == GemmDtype::F16 {
            // Take the larger of the bias and no-bias plans rather than trying to
            // predict which the launch will pick: the requirement only has to be
            // an upper bound, and under-declaring fails the launch outright.
            let mut bytes = 0;
            let biases: &[Option<u64>] = if fused { &[None] } else { &[None, Some(0)] };
            for bias in biases {
                let params = self.dequant_f16_gemm_ex(1, 1, 1, m, *bias);
                bytes = bytes.max(blas::gemm_ex_workspace_bytes(self.runtime.blas(), &params)?);
            }
            return Ok(blas::governed_workspace_requirement(bytes));
        }
        let params = GemmParams {
            dtype,
            a: 1,
            b: 1,
            c: 1,
            m,
            k: self.k,
            n: self.n,
            batch: 1,
            a_batch_stride: m * self.k,
            b_batch_stride: 0,
            epilogue: inputs
                .get(5)
                .filter(|bias| bias.present)
                .map(|_| GemmEpilogue {
                    kind: GemmEpilogueKind::Bias,
                    bias: 0,
                }),
        };
        let bytes = blas::gemm_workspace_bytes(self.runtime.blas(), &params)?;
        Ok(blas::governed_workspace_requirement(bytes))
    }

    /// BFloat16-activation path. The tuned int4/int8 GEMV/GEMM kernels are
    /// implemented for Float16 and Float32 activations only, so BFloat16 inputs
    /// are staged through Float16: every BFloat16 operand (activation, scales,
    /// and any fused residual/gamma) is converted into a scratch Float16 buffer,
    /// the reused fp16 path runs the actual matmul against the still-quantized
    /// int4/int8 weights, and the Float16 result is converted back to BFloat16.
    ///
    /// Only the small activation/scale/output buffers are converted; the packed
    /// weights (the memory-bound term in decode) keep their int4/int8 layout, so
    /// the extra work is a handful of pointwise casts per node. Float16 losslessly
    /// represents the post-normalization magnitudes MatMulNBits consumes here.
    /// The per-call scratch means this path is not graph-capture safe.
    fn run_bf16(
        &self,
        inputs: &[TensorView],
        outputs: &mut [TensorMut],
        workspace: Option<WorkspaceView>,
    ) -> Result<()> {
        require_dtype("A", inputs[0].dtype, DataType::BFloat16)?;
        require_dtype("Y", outputs[0].dtype, DataType::BFloat16)?;

        // The scale slots are immutable weights (general path: input 2; the
        // gate/up SwiGLU fusion adds a second scale at input 4). They dominate
        // the BFloat16 staging traffic (~25% of the int4 weight bytes/token for
        // Muse-Glimmer), so stage them once into the persistent const cache and
        // reuse across decode steps. Every other BFloat16 input is either the
        // per-step activation (input 0) or a per-token residual bound into the
        // bias slot — both genuinely dynamic — so they keep going through the
        // per-call arena. Caching keys on the weight pointer + element count and
        // never uses pointer identity for the dynamic slots (a reused activation
        // buffer has a stable pointer but changing contents).
        let cache_slots: &[usize] = if self.gate_up_swiglu { &[2, 4] } else { &[2] };
        let is_cached = |index: usize, dtype: DataType| {
            dtype == DataType::BFloat16 && cache_slots.contains(&index)
        };

        // Lay out per-call Float16 regions inside the reusable arena: one region
        // per dynamic BFloat16 input, plus one for the Float16 result. Regions
        // are padded so each begins aligned for the tuned fp16 kernels'
        // vectorized loads.
        const ALIGN: usize = 256;
        let f16 = std::mem::size_of::<half::f16>();
        let round = |bytes: usize| bytes.div_ceil(ALIGN) * ALIGN;

        let mut offsets: Vec<Option<usize>> = Vec::with_capacity(inputs.len());
        let mut total = 0usize;
        for (index, input) in inputs.iter().enumerate() {
            if input.dtype == DataType::BFloat16 && !is_cached(index, input.dtype) {
                offsets.push(Some(total));
                total += round(input.numel() * f16);
            } else {
                offsets.push(None);
            }
        }
        let out_off = total;
        let out_n = outputs[0].numel();
        total += round(out_n * f16);

        // Stage the constant scale slots once into the persistent cache (this is
        // allocation-free on every call after the first warmup call, so the
        // captured decode graph only replays cache hits).
        let cached: Vec<(usize, CUdeviceptr)> = {
            let consts: Vec<(CUdeviceptr, usize)> = cache_slots
                .iter()
                .filter(|index| **index < inputs.len() && is_cached(**index, inputs[**index].dtype))
                .map(|index| {
                    (
                        cuptr(inputs[*index].data_ptr::<u8>() as *const c_void) as CUdeviceptr,
                        inputs[*index].numel(),
                    )
                })
                .collect();
            if consts.is_empty() {
                Vec::new()
            } else {
                let mut cache = self
                    .bf16_const_cache
                    .lock()
                    .map_err(|_| error("MatMulNBits bf16 const cache mutex poisoned"))?;
                let ptrs = cache.staged(&consts)?;
                cache_slots
                    .iter()
                    .filter(|index| {
                        **index < inputs.len() && is_cached(**index, inputs[**index].dtype)
                    })
                    .zip(ptrs)
                    .map(|(index, ptr)| (*index, ptr))
                    .collect()
            }
        };

        // Hold the arena for the whole call: the staging casts, the reused fp16
        // matmul, and the narrowing cast all run stream-ordered against it. The
        // fp16 path never touches `bf16_scratch`, so this cannot deadlock.
        let mut arena = self
            .bf16_scratch
            .lock()
            .map_err(|_| error("MatMulNBits bf16 scratch mutex poisoned"))?;
        let base = arena.ensure(total)?;

        let mut f16_inputs: Vec<TensorView> = Vec::with_capacity(inputs.len());
        for (index, (input, offset)) in inputs.iter().zip(offsets.iter()).enumerate() {
            if let Some((_, cached_ptr)) = cached.iter().find(|(slot, _)| *slot == index) {
                f16_inputs.push(TensorView::new(
                    DevicePtr(raw_ptr(*cached_ptr) as *const c_void),
                    DataType::Float16,
                    input.shape,
                    input.strides,
                    input.device,
                ));
                continue;
            }
            match offset {
                Some(off) => {
                    let ptr = base + *off as CUdeviceptr;
                    super::cast::launch_cast_raw(
                        &self.runtime,
                        cuptr(input.data_ptr::<u8>() as *const c_void),
                        DataType::BFloat16,
                        ptr,
                        DataType::Float16,
                        input.numel(),
                    )?;
                    f16_inputs.push(TensorView::new(
                        DevicePtr(raw_ptr(ptr) as *const c_void),
                        DataType::Float16,
                        input.shape,
                        input.strides,
                        input.device,
                    ));
                }
                None => f16_inputs.push(*input),
            }
        }

        let out_ptr = base + out_off as CUdeviceptr;
        let out_shape = outputs[0].shape;
        let out_strides = outputs[0].strides;
        let out_device = outputs[0].device;
        let mut y_f16 = TensorMut::new(
            DevicePtrMut(raw_ptr(out_ptr)),
            DataType::Float16,
            out_shape,
            out_strides,
            out_device,
        );
        // Offer the real bf16 output to the fp16 path: the split-K decode GEMVs
        // can narrow into it directly and save this node's staging cast. The
        // offer is restored (not just cleared) so a nested bf16 call cannot
        // strand an outer one, and it is restored before `?` so an error cannot
        // leave it published.
        let dst_ptr = cuptr(outputs[0].data_ptr_mut::<u8>() as *const c_void);
        let offer = Some(Bf16DirectOut {
            staging: out_ptr,
            dst: dst_ptr,
            elements: out_n,
            taken: false,
        });
        let previous = BF16_DIRECT_OUT.with(|cell| cell.replace(offer));
        let run_result = self.run(&f16_inputs, std::slice::from_mut(&mut y_f16), workspace);
        let settled = BF16_DIRECT_OUT.with(|cell| cell.replace(previous));
        run_result?;
        if !settled.is_some_and(|offer| offer.taken) {
            super::cast::launch_cast_raw(
                &self.runtime,
                out_ptr,
                DataType::Float16,
                dst_ptr,
                DataType::BFloat16,
                out_n,
            )?;
        }
        // Capture-safety is inherited from the staged fp16 run: the M==1 decode
        // GEMV is capture-safe, and the staging casts add only allocation-free,
        // sync-free stream launches against the persistent arena (which is grown
        // once, before capture). Prefill (M>1) leaves the flag cleared. So the
        // flag `run` set during recursion is exactly right — do not override it.
        drop(arena);
        Ok(())
    }

    /// Direct fp16-activation x int4/int8-weight path. Scales may be fp16 or
    /// f32. M=1 uses the capture-safe decode GEMVs; M>1 uses a portable tiled
    /// CUDA-core GEMM with fp32 accumulation and fp16 output.
    fn run_f16(
        &self,
        inputs: &[TensorView],
        outputs: &mut [TensorMut],
        workspace: Option<WorkspaceView>,
    ) -> Result<()> {
        require_dtype("A", inputs[0].dtype, DataType::Float16)?;
        require_dtype("B", inputs[1].dtype, DataType::Uint8)?;
        let scales_fp16 = match inputs[2].dtype {
            DataType::Float16 => true,
            DataType::Float32 => false,
            other => {
                return Err(error(format!(
                    "scales must have dtype Float16 or Float32 for fp16 activations, got {other:?}"
                )));
            }
        };
        require_dtype("Y", outputs[0].dtype, DataType::Float16)?;

        let a_shape = inputs[0].shape;
        if a_shape.is_empty() || a_shape[a_shape.len() - 1] != self.k {
            return Err(error(format!(
                "A must have rank >= 1 and last dimension K={}, got {:?}",
                self.k, a_shape
            )));
        }
        let expected_output_shape = [&a_shape[..a_shape.len() - 1], &[self.n]].concat();
        if outputs[0].shape != expected_output_shape {
            return Err(error(format!(
                "Y must have shape {expected_output_shape:?}, got {:?}",
                outputs[0].shape
            )));
        }

        let k_blocks = self.k.div_ceil(self.block_size);
        let blob_size = self.block_size * self.bits / 8;
        require_shape("B", inputs[1].shape, &[self.n, k_blocks, blob_size])?;
        require_flat_or_matrix_shape("scales", inputs[2].shape, self.n, k_blocks)?;

        let zero_points = optional_input(inputs, 3);
        let zp_row_bytes = (k_blocks * self.bits).div_ceil(8);
        if let Some(zero_points) = zero_points {
            require_dtype("zero_points", zero_points.dtype, DataType::Uint8)?;
            require_flat_or_matrix_shape("zero_points", zero_points.shape, self.n, zp_row_bytes)?;
        }
        let group_indices = optional_input(inputs, 4);
        let bias = optional_input(inputs, 5);
        let rows = a_shape[..a_shape.len() - 1].iter().product::<usize>();
        if let Some(bias) = bias {
            require_dtype("bias", bias.dtype, DataType::Float16)?;
            // A folded residual epilogue binds the residual activation into this
            // same slot: `[1, 1, N]` (N elements) at decode, or `[1, S, N]`
            // (rows * N elements) at prefill. A genuine broadcast bias is `[N]`.
            if bias.numel() != self.n && bias.numel() != rows * self.n {
                return Err(error(format!(
                    "bias must have {} elements (broadcast [N]) or {} elements (per-token \
                     [1, S, N] residual), got {:?}",
                    self.n,
                    rows * self.n,
                    bias.shape
                )));
            }
        }
        let gamma = optional_input(inputs, 6);
        if self.rmsnorm_prologue {
            let gamma = gamma.ok_or_else(|| {
                error("rmsnorm_prologue fusion requires the normalization weight at input 6")
            })?;
            require_gamma_dtype(gamma.dtype)?;
            require_shape("gamma", gamma.shape, &[self.k])?;
        }

        for (name, contiguous) in [
            ("A", inputs[0].is_contiguous()),
            ("B", inputs[1].is_contiguous()),
            ("scales", inputs[2].is_contiguous()),
            (
                "zero_points",
                zero_points.is_none_or(TensorView::is_contiguous),
            ),
            ("bias", bias.is_none_or(TensorView::is_contiguous)),
            ("gamma", gamma.is_none_or(TensorView::is_contiguous)),
            ("Y", outputs[0].is_contiguous()),
        ] {
            if !contiguous {
                return Err(error(format!(
                    "{name} must be contiguous on the CUDA execution provider"
                )));
            }
        }

        let m = a_shape[..a_shape.len() - 1].iter().product::<usize>();
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let mut flops = (m as u64)
                .saturating_mul(self.n as u64)
                .saturating_mul(self.k as u64)
                .saturating_mul(2);
            if bias.is_some() {
                flops = flops.saturating_add((m as u64).saturating_mul(self.n as u64));
            }
            if self.rmsnorm_prologue {
                let elements = (m as u64).saturating_mul(self.k as u64);
                flops = flops
                    .saturating_add(elements.saturating_mul(4))
                    .saturating_add((m as u64).saturating_mul(4));
            }
            flops
        });
        // Non-block-32 layouts are served by the model-agnostic general-block-size
        // fp16 kernels (int4/int8 decode GEMV + int4/int8 prefill GEMM). The tuned
        // block-32 fusions (rmsnorm prologue, gate/up SwiGLU, down-projection) are
        // gated to block_size==32 in the optimizer, so a non-block-32 node always
        // arrives here as a plain int4/int8 GEMV/GEMM. The general-block-size GEMV
        // selects the packed layout from `bits`, so bits==8 with a non-block-32
        // width routes to it just like int4 does.
        if group_indices.is_some() {
            return Err(error(
                "MatMulNBits CUDA fp16 activations do not support g_idx. Why: the block-32 fp16 \
                 kernels map each K block directly to its scale and zero point and do not implement \
                 group remapping. How to fix: omit g_idx, provide f32 activations, or select another \
                 execution provider",
            ));
        }

        if m > 1 {
            // Small-batch decode fast path: for M within the crossover bound,
            // reuse the capture-safe single-row decode GEMV once per row instead
            // of the tiled prefill GEMM. The tiled GEMM tiles M in 16-row blocks,
            // so M=2..16 pay the same M-independent full-weight-grid pass; the
            // looped GEMV instead reads the weights once per row and skips that
            // fixed overhead, which is faster while M x gemv_step < tiled_step
            // (measured crossover ~11 on qwen05b-q4; see DECODE_GEMV_LOOP_MAX_M_*).
            // Excludes the fused SwiGLU/decomposed-SiLU epilogues, which have no
            // single-row GEMV equivalent in `dispatch_f16_decode_gemv_row`.
            //
            // Numerics: each row is computed byte-identically to a single-sequence
            // (M==1) decode of that row — the strongest batching-correctness
            // guarantee (a batched row produces the same tokens as if run alone).
            // Capture-safe: every per-row launch is static-grid, allocation- and
            // sync-free, so the batch decode graph captures and replays it.
            // Streaming: the resident weight is read M times from VRAM, not
            // re-streamed, so the weight-offload HtoD 1/N amortization is intact.
            if m <= decode_gemv_loop_max_m()
                && decode_gemv_loop_rows_aligned(self.k)
                && !self.gate_up_swiglu
                && !self.decomposed_silu
            {
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_f16_batched_loop",
                    "M={} small-batch decode: {} single-row decode GEMV launches (one per row), \
                     each byte-identical to M==1 decode; skips the tiled prefill GEMM's \
                     M-independent full-weight-grid pass",
                    m,
                    m
                );
                self.last_call_capture_safe.store(true, Ordering::Relaxed);
                let per_token_bias =
                    bias.filter(|b| b.numel() == m * self.n && m * self.n != self.n);
                let a_base = inputs[0].data_ptr::<u8>();
                let y_base = outputs[0].data_ptr_mut::<u8>();
                let bias_base = per_token_bias.map(|b| b.data_ptr::<u8>());
                let a_row_shape = [1usize, self.k];
                let a_row_strides = [self.k as i64, 1];
                let y_row_shape = [1usize, self.n];
                let y_row_strides = [self.n as i64, 1];
                let a_row_bytes = self.k * 2; // fp16 activation
                let y_row_bytes = self.n * 2; // fp16 output / residual
                for row in 0..m {
                    let a_row = TensorView::new(
                        DevicePtr(a_base.wrapping_add(row * a_row_bytes) as *const c_void),
                        DataType::Float16,
                        &a_row_shape,
                        &a_row_strides,
                        inputs[0].device,
                    );
                    let mut y_row = TensorMut::new(
                        DevicePtrMut(y_base.wrapping_add(row * y_row_bytes) as *mut c_void),
                        DataType::Float16,
                        &y_row_shape,
                        &y_row_strides,
                        outputs[0].device,
                    );
                    let bias_row = bias_base.map(|base| {
                        TensorView::new(
                            DevicePtr(base.wrapping_add(row * y_row_bytes) as *const c_void),
                            DataType::Float16,
                            &y_row_shape,
                            &y_row_strides,
                            inputs[0].device,
                        )
                    });
                    let bias_ref = match bias_row {
                        Some(ref b) => Some(b),
                        None => bias,
                    };
                    self.dispatch_f16_decode_gemv_row(
                        &a_row,
                        &inputs[1],
                        &inputs[2],
                        scales_fp16,
                        zero_points,
                        bias_ref,
                        gamma,
                        &mut y_row,
                        k_blocks,
                        blob_size,
                        zp_row_bytes,
                    )?;
                }
                return Ok(());
            }
            // SAFETY: the tiled prefill kernel itself has fixed pointers and no
            // allocation or host synchronization. We nevertheless keep the
            // advertised capture contract conservative: variable-M prefill is
            // outside the persistent M=1 decode graph and has no replay coverage.
            self.last_call_capture_safe.store(false, Ordering::Relaxed);
            // A folded residual epilogue supplies a per-token residual (rows * N
            // elements) in the bias slot; index it with row stride N. A genuine
            // broadcast bias (N elements) keeps stride 0.
            let bias_row_stride = match bias {
                Some(bias) if bias.numel() == m * self.n && m * self.n != self.n => self.n,
                _ => 0,
            };
            // Dequantize to fp16 and run the GEMM on cuBLASLt tensor cores. This
            // sits ahead of Marlin because both of the int4 M>1 kernels below
            // leave most of the machine idle on this shape: Marlin stages
            // nothing in shared memory, so every warp re-reads its whole A panel
            // from global memory, and the f32 dequant fallback gives up tensor
            // cores. One K*N dequantize pass buys the full fp16 tensor-core rate
            // for the matmul itself, which prefill is large enough to amortize.
            // Ineligibility and launch errors fall through to Marlin and then
            // the tiled GEMM (Rule 11 fallback contract).
            if dequant_f16_gemm_enabled()
                && m >= dequant_f16_gemm_min_m()
                && !self.gate_up_swiglu
                && !self.decomposed_silu
                && !self.rmsnorm_prologue
                && group_indices.is_none()
            {
                match self.try_dequant_f16_cublas_gemm(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    scales_fp16,
                    zero_points,
                    bias,
                    &mut outputs[0],
                    m,
                    bias_row_stride,
                    k_blocks,
                    blob_size,
                    zp_row_bytes,
                    workspace,
                ) {
                    Ok(true) => {
                        onnx_runtime_ep_api::record_kernel_variant!(
                            "gemm_dequant_f16_cublas",
                            "M={} prefill: dequantize int{} weights to [K, N] fp16, then \
                             cuBLASLt fp16 tensor-core GEMM with f32 accumulation",
                            m,
                            self.bits
                        );
                        return Ok(());
                    }
                    Ok(false) => {
                        // Not eligible at runtime (bias form, scratch size).
                    }
                    Err(_err) => {
                        // Hard launch error; fall through rather than fail the op.
                    }
                }
            }
            // Opt-in Marlin int4 tensor-core GEMM for the M>1 path. Gated on
            // SM80+, int4, immutable initializer weights, no g_idx (checked
            // above), no fused SwiGLU/RMSNorm epilogue yet, and
            // `ONNX_GENAI_MARLIN_M_GT_1`. Runtime weights cannot use Marlin:
            // the kernel-owned address key is valid only while an immutable
            // constant remains bound to this kernel. On any ineligibility or
            // runtime error it falls through to the byte-identical portable
            // tiled GEMM below (Rule 11 fallback contract).
            if marlin_gemm::marlin_m_gt_1_enabled()
                && self.bits == 4
                && !self.gate_up_swiglu
                && !self.decomposed_silu
                && !self.rmsnorm_prologue
                && self.marlin_weight_inputs_constant()
                && marlin_gemm::device_supports_marlin(
                    self.runtime.capabilities().compute_capability(),
                )
            {
                match self.try_launch_marlin_gemm(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    scales_fp16,
                    zero_points,
                    bias,
                    &mut outputs[0],
                    m,
                    bias_row_stride,
                ) {
                    Ok(Some(warm)) => {
                        // Static grid + (when warm) no alloc/repack/sync this
                        // call ⇒ capture-safe. A cold first call repacked and is
                        // reported unsafe; subsequent replays hit the cache.
                        self.last_call_capture_safe.store(warm, Ordering::Relaxed);
                        onnx_runtime_ep_api::record_kernel_variant!(
                            "gemm_marlin_int4",
                            "M={} prefill/verify: fp16 activation, int4, block_size={}, \
                             zero_points={} → Marlin SM80 mma.sync int4 tensor-core GEMM \
                             (static grid, capture-safe when weights are pre-repacked)",
                            m,
                            self.block_size,
                            zero_points.is_some()
                        );
                        return Ok(());
                    }
                    Ok(None) => {
                        // Not eligible at runtime (e.g. dims); fall through.
                    }
                    Err(_err) => {
                        // Hard launch error: fall through to the portable tiled
                        // GEMM rather than fail the op. The tiled variant records
                        // its own kernel-variant note below.
                    }
                }
            }
            if self.rmsnorm_prologue {
                let gamma = gamma.ok_or_else(|| {
                    error("rmsnorm_prologue fusion requires the normalization weight at input 6")
                })?;
                // Opt-in Marlin int4 tensor-core GEMM with the fused RMS-norm
                // prologue: stage the per-token normalized activation into
                // scratch (byte-identical to the standalone prologue), then run
                // Marlin over it. The scratch allocation keeps this off the
                // advertised capture contract (like the tiled rmsnorm prefill),
                // but prefill is outside the persistent decode graph. Falls
                // through to the tiled rmsnorm GEMM on ineligibility / error.
                if marlin_gemm::marlin_m_gt_1_enabled()
                    && self.bits == 4
                    && !self.gate_up_swiglu
                    && !self.decomposed_silu
                    && self.marlin_weight_inputs_constant()
                    && marlin_gemm::device_supports_marlin(
                        self.runtime.capabilities().compute_capability(),
                    )
                {
                    match self.try_launch_marlin_gemm_rmsnorm(
                        &inputs[0],
                        &inputs[1],
                        &inputs[2],
                        scales_fp16,
                        zero_points,
                        gamma,
                        bias,
                        &mut outputs[0],
                        m,
                        bias_row_stride,
                    ) {
                        Ok(Some(warm)) => {
                            // Static grid + pooled scratch/weights ⇒ capture-safe
                            // on a warm replay; a cold call allocated and is
                            // reported unsafe.
                            self.last_call_capture_safe.store(warm, Ordering::Relaxed);
                            onnx_runtime_ep_api::record_kernel_variant!(
                                "gemm_marlin_int4_rmsnorm",
                                "M={} prefill/verify: RMS-normalization prologue \
                                 (SkipSimplifiedLayerNormalization folded) into pooled scratch, \
                                 then Marlin SM80 mma.sync int4 tensor-core GEMM (capture-safe \
                                 when weights + scratch are pre-warmed)",
                                m
                            );
                            return Ok(());
                        }
                        Ok(None) => {
                            // Not eligible (e.g. dims); fall through to tiled.
                        }
                        Err(_err) => {
                            // Hard error: fall through to the tiled rmsnorm GEMM.
                        }
                    }
                }
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemm_f16_tiled_rmsnorm",
                    "M={} prefill: RMS-normalization prologue (SkipSimplifiedLayerNormalization \
                     folded) into a per-token scratch, then portable 16x16 tiled GEMM with fp32 \
                     accumulation; not advertised as CUDA-graph capture-safe",
                    m
                );
                return self.launch_f16_gemm_rmsnorm_prefill(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    zero_points,
                    gamma,
                    bias,
                    &mut outputs[0],
                    m,
                    k_blocks,
                    bias_row_stride,
                );
            }
            onnx_runtime_ep_api::record_kernel_variant!(
                "gemm_f16_tiled",
                "M={} prefill: fp16 activation, bits={}, block_size={}, zero_points={}, \
                 scales={} → portable 16x16 CUDA-core tiled GEMM with fp32 accumulation; \
                 not advertised as CUDA-graph capture-safe",
                m,
                self.bits,
                self.block_size,
                zero_points.is_some(),
                if scales_fp16 { "fp16" } else { "fp32" }
            );
            return self.launch_f16_gemm(
                &inputs[0],
                &inputs[1],
                &inputs[2],
                scales_fp16,
                zero_points,
                bias,
                &mut outputs[0],
                m,
                k_blocks,
                blob_size,
                bias_row_stride,
            );
        }

        self.last_call_capture_safe.store(true, Ordering::Relaxed);
        self.dispatch_f16_decode_gemv_row(
            &inputs[0],
            &inputs[1],
            &inputs[2],
            scales_fp16,
            zero_points,
            bias,
            gamma,
            &mut outputs[0],
            k_blocks,
            blob_size,
            zp_row_bytes,
        )
    }

    /// Dispatch one single-row (M==1) fp16-activation decode GEMV for `a_row`
    /// into `y_row`, selecting the specialized kernel by bits/block_size/rmsnorm
    /// exactly as the M==1 path does. `packed`/`scales`/`zero_points`/`gamma` are
    /// the shared weight metadata; `bias` is the row's bias/residual slice (or a
    /// broadcast `[N]` bias). Reused by [`Self::run_f16`] for the true M==1 step
    /// and by the small-batch looped decode path (one call per row).
    #[allow(clippy::too_many_arguments)]
    fn dispatch_f16_decode_gemv_row(
        &self,
        a_row: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        gamma: Option<&TensorView>,
        y_row: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        if self.bits == 8 && self.block_size == 32 {
            if self.rmsnorm_prologue {
                let gamma = gamma.ok_or_else(|| {
                    error("rmsnorm_prologue fusion requires the normalization weight at input 6")
                })?;
                if !scales_fp16 {
                    return Err(error(
                        "rmsnorm_prologue fusion requires fp16 scales (the fused kernel replicates \
                         the fp16 general scales path)",
                    ));
                }
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gemv_int8_f16_scales_f16_rmsnorm",
                    "M==1 decode: fp16 activation, bits=8, block_size=32, fp16 scales, \
                     zero_points={} → int8 GEMV with fused RMS-normalization prologue \
                     (SkipSimplifiedLayerNormalization folded)",
                    zero_points.is_some()
                );
                return self.launch_int8_f16_gemv_rmsnorm(
                    a_row,
                    packed,
                    scales,
                    zero_points,
                    gamma,
                    bias,
                    y_row,
                    k_blocks,
                );
            }
            onnx_runtime_ep_api::record_kernel_variant!(
                "gemv_int8_f16",
                "M==1 decode: fp16 activation, bits=8, block_size=32, zero_points={} → direct \
                 capture-safe GEMV",
                zero_points.is_some()
            );
            return self.launch_int8_f16_gemv(
                a_row,
                packed,
                scales,
                scales_fp16,
                zero_points,
                bias,
                y_row,
                k_blocks,
            );
        }
        if self.rmsnorm_prologue {
            let gamma = gamma.ok_or_else(|| {
                error("rmsnorm_prologue fusion requires the normalization weight at input 6")
            })?;
            if !scales_fp16 {
                return Err(error(
                    "rmsnorm_prologue fusion requires fp16 scales (the fused kernel replicates \
                     the fp16 general scales path)",
                ));
            }
            onnx_runtime_ep_api::record_kernel_variant!(
                "gemv_f16_scales_f16_rmsnorm",
                "M==1 decode: fp16 activation, bits=4, block_size=32, fp16 scales, \
                 zero_points={} → general GEMV with fused RMS-normalization prologue \
                 (SkipSimplifiedLayerNormalization folded)",
                zero_points.is_some()
            );
            return self.launch_f16_gemv_rmsnorm(
                a_row,
                packed,
                scales,
                zero_points,
                gamma,
                bias,
                y_row,
                k_blocks,
                blob_size,
                zp_row_bytes,
            );
        }
        self.launch_f16_gemv(
            a_row,
            packed,
            scales,
            scales_fp16,
            zero_points,
            bias,
            y_row,
            k_blocks,
            blob_size,
            zp_row_bytes,
        )
    }

    #[allow(clippy::too_many_arguments)]
    /// Attempt the opt-in Marlin int4 tensor-core GEMM for the M>1 path.
    ///
    /// Returns `Ok(Some(warm))` when the kernel launched (`warm == true` means
    /// the repacked weights were already cached, so this call did no allocation
    /// and is CUDA-graph capture-safe), `Ok(None)` when the inputs are not
    /// eligible (caller falls through to the portable tiled GEMM), or `Err` on a
    /// hard launch failure (caller also falls through).
    ///
    /// Eligibility (SM80, int4, no fused SwiGLU/RMSNorm epilogue, opt-in flag)
    /// is checked by the caller; here we validate the numeric shape contract
    /// (`K` divisible by 16 and by the group size). The caller also requires B
    /// to be an immutable graph constant before the kernel-owned cache is
    /// entered, then the weight is repacked into the tensor-core layout once.
    #[allow(clippy::too_many_arguments)]
    fn try_launch_marlin_gemm(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        bias_row_stride: usize,
    ) -> Result<Option<bool>> {
        // Shape contract: the tensor-core kernel tiles K in units of 16 and
        // applies one scale per quantization group, so K must be divisible by
        // both. Anything else stays on the portable tiled GEMM.
        if self.block_size == 0
            || !self.k.is_multiple_of(16)
            || !self.k.is_multiple_of(self.block_size)
        {
            return Ok(None);
        }
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits Marlin int4 tensor-core GEMM")?;

        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let (weights_ptr, warm) = self.marlin_repack_cache.ensure_repacked(
            packed_ptr,
            self.n,
            self.k,
            self.block_size,
        )?;

        let args = marlin_gemm::MarlinGemmArgs {
            activation: cuptr(activation.data_ptr::<u8>() as *const c_void),
            weights: weights_ptr,
            scales: cuptr(scales.data_ptr::<u8>() as *const c_void),
            zero_points: zero_points.map(|t| cuptr(t.data_ptr::<u8>() as *const c_void)),
            bias: bias.map(|t| cuptr(t.data_ptr::<u8>() as *const c_void)),
            output: cuptr(output.data_ptr_mut::<u8>() as *const c_void),
            m,
            k: self.k,
            n: self.n,
            group_size: self.block_size,
            scales_fp16,
            bias_post_round: self.fold_bias_post_round && bias.is_some(),
            bias_row_stride,
        };
        // Split-K (opt-in): partition K across grid.z to fill idle SMs when the
        // base block count is small. Partials come from the capture-safe scratch
        // pool (slot 4) so warm replays stay allocation-free; the reduce applies
        // the same fold_bias epilogue. Falls back to the byte-identical direct
        // kernel whenever the heuristic declines to split.
        let split_warm = self.maybe_launch_marlin_splitk(&args)?;
        Ok(Some(warm && split_warm))
    }

    /// Launch `args` through split-K when enabled and the heuristic elects to
    /// split, otherwise through the direct kernel. Returns whether the launch
    /// was allocation-free (`true` for the direct kernel; for split-K, whether
    /// the pooled partials scratch was already warm) so callers can propagate
    /// capture-safety.
    fn maybe_launch_marlin_splitk(&self, args: &marlin_gemm::MarlinGemmArgs) -> Result<bool> {
        if marlin_gemm::marlin_splitk_enabled() {
            let k_blocks = self.k / self.block_size.max(1);
            let sm = self.runtime.capabilities().multiprocessor_count();
            let split_k = marlin_gemm::choose_split_k(args.m, args.n, k_blocks, sm);
            if split_k > 1 {
                let bytes = marlin_gemm::splitk_partials_len(split_k, args.m, args.n)
                    * std::mem::size_of::<f32>();
                let (partials, warm) = self.marlin_repack_cache.ensure_scratch(4, bytes)?;
                marlin_gemm::launch_marlin_gemm_splitk(&self.runtime, args, split_k, partials)?;
                return Ok(warm);
            }
        }
        marlin_gemm::launch_marlin_gemm(&self.runtime, args)?;
        Ok(true)
    }

    /// Marlin M>1 GEMM with the fused RMS-normalization prologue. Stages the
    /// per-token normalized activation into pooled scratch (byte-identical to the
    /// standalone `launch_rmsnorm_prefill` output the tiled path uses), then runs
    /// the Marlin int4 tensor-core GEMM over the normalized rows. Returns
    /// `Some(warm)` when it launched (`warm` means both the repacked weights and
    /// the scratch were already pooled ⇒ no allocation this call ⇒ capture-safe),
    /// or `None` when the shape is ineligible (caller falls through to the tiled
    /// rmsnorm GEMM).
    #[allow(clippy::too_many_arguments)]
    fn try_launch_marlin_gemm_rmsnorm(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        gamma: &TensorView,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        bias_row_stride: usize,
    ) -> Result<Option<bool>> {
        if self.block_size == 0
            || !self.k.is_multiple_of(16)
            || !self.k.is_multiple_of(self.block_size)
        {
            return Ok(None);
        }
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits Marlin int4 tensor-core GEMM (rmsnorm)")?;

        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let (weights_ptr, weights_warm) = self.marlin_repack_cache.ensure_repacked(
            packed_ptr,
            self.n,
            self.k,
            self.block_size,
        )?;
        // Pooled normalized-activation scratch (slot 0). On a warm replay this is
        // already allocated, so the whole path is allocation-free.
        let scratch_bytes = m * self.k * std::mem::size_of::<half::f16>();
        let (scratch, scratch_warm) = self.marlin_repack_cache.ensure_scratch(0, scratch_bytes)?;

        self.launch_rmsnorm_prefill(activation, gamma, scratch, m)?;
        let args = marlin_gemm::MarlinGemmArgs {
            activation: scratch,
            weights: weights_ptr,
            scales: cuptr(scales.data_ptr::<u8>() as *const c_void),
            zero_points: zero_points.map(|t| cuptr(t.data_ptr::<u8>() as *const c_void)),
            bias: bias.map(|t| cuptr(t.data_ptr::<u8>() as *const c_void)),
            output: cuptr(output.data_ptr_mut::<u8>() as *const c_void),
            m,
            k: self.k,
            n: self.n,
            group_size: self.block_size,
            scales_fp16,
            bias_post_round: self.fold_bias_post_round && bias.is_some(),
            bias_row_stride,
        };
        let split_warm = self.maybe_launch_marlin_splitk(&args)?;
        Ok(Some(weights_warm && scratch_warm && split_warm))
    }

    /// Dequantize + fp16 cuBLASLt M>1 path for the paired gate/up SwiGLU MLP
    /// fusion, optionally with the fused RMS-norm prologue.
    ///
    /// These are the widest projections in the decoder and therefore most of
    /// prefill's arithmetic, so leaving them on Marlin while the unfused nodes
    /// moved to tensor cores would cap the win. The structure is the Marlin
    /// path's: stage the normalized activation once, run the two projections
    /// into pooled scratch, then apply the same fp16 SiluMul epilogue — only
    /// the two GEMMs differ.
    ///
    /// Returns `Ok(false)` when ineligible so the caller falls through.
    #[allow(clippy::too_many_arguments)]
    fn try_dequant_f16_gate_up_prefill(
        &self,
        activation: &TensorView,
        packed_gate: &TensorView,
        scales_gate: &TensorView,
        packed_up: &TensorView,
        scales_up: &TensorView,
        scales_fp16: bool,
        zp_gate: Option<&TensorView>,
        zp_up: Option<&TensorView>,
        gamma: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
        workspace: Option<WorkspaceView>,
    ) -> Result<bool> {
        let Some(block_shift) = self.dequant_f16_block_shift() else {
            return Ok(false);
        };
        let weight_bytes = self
            .k
            .checked_mul(self.n)
            .and_then(|elems| elems.checked_mul(2))
            .ok_or_else(|| error("dequantized f16 weight size overflowed"))?;
        if weight_bytes > dequant_f16_gemm_max_scratch_bytes() {
            return Ok(false);
        }
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits dequant f16 gate/up SwiGLU GEMM")?;

        // Stage the RMS-normalized activation once (slot 0, as the Marlin path
        // does), so both projections read the same normalized copy.
        let act_ptr = if let Some(gamma) = gamma {
            let norm_bytes = m * self.k * std::mem::size_of::<half::f16>();
            let (norm, _warm) = self.marlin_repack_cache.ensure_scratch(0, norm_bytes)?;
            self.launch_rmsnorm_prefill(activation, gamma, norm, m)?;
            norm
        } else {
            cuptr(activation.data_ptr::<u8>() as *const c_void)
        };

        let out_bytes = output.byte_size();
        // Slot 1 holds the gate projection, as on the Marlin path; the up
        // projection writes the real output and SiluMul folds them in place.
        let (gate_buf, _warm) = self.marlin_repack_cache.ensure_scratch(1, out_bytes)?;
        // Slots 5 and 6 hold the two dequantized weights. They must differ: both
        // are live across the second GEMM.
        let (weight_gate, _warm) = self.marlin_repack_cache.ensure_scratch(5, weight_bytes)?;
        let (weight_up, _warm) = self.marlin_repack_cache.ensure_scratch(6, weight_bytes)?;
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);

        for (packed, scales, zero_points, weight, out) in [
            (packed_gate, scales_gate, zp_gate, weight_gate, gate_buf),
            (packed_up, scales_up, zp_up, weight_up, output_ptr),
        ] {
            self.launch_dequant_f16(
                packed,
                scales,
                scales_fp16,
                zero_points,
                weight,
                k_blocks,
                blob_size,
                zp_row_bytes,
                block_shift,
            )?;
            let params = self.dequant_f16_gemm_ex(act_ptr, weight, out, m, None);
            // SAFETY: the dequantized [N, K] weight was just written, the
            // activation is the validated (optionally normalized) [M, K] fp16
            // panel, and the destination is a distinct [M, N] fp16 buffer.
            unsafe {
                blas::governed_gemm_ex(
                    self.runtime.blas(),
                    self.runtime.stream_ptr(),
                    &params,
                    workspace,
                    "MatMulNBits",
                )
            }?;
        }

        crate::kernels::elementwise::launch_silu_mul_f16_raw(
            &self.runtime,
            gate_buf,
            output_ptr,
            output_ptr,
            output.numel(),
            self.decomposed_silu,
        )?;
        Ok(true)
    }

    /// Marlin M>1 path for the paired gate/up SwiGLU MLP fusion (optionally with
    /// a fused RMS-norm prologue). Runs both projections through the Marlin int4
    /// tensor-core GEMM into pooled scratch, then the same fp16 SiluMul epilogue
    /// the tiled path uses (`silu(gate) * up`, decomposed or not). Returns
    /// `Some(warm)` when it launched (`warm` ⇒ every repacked weight and scratch
    /// buffer was already pooled, so the call is allocation-free and
    /// capture-safe), or `None` when the shape is ineligible (caller falls
    /// through to the tiled gate/up prefill).
    #[allow(clippy::too_many_arguments)]
    fn try_launch_marlin_gate_up_prefill(
        &self,
        activation: &TensorView,
        packed_gate: &TensorView,
        scales_gate: &TensorView,
        packed_up: &TensorView,
        scales_up: &TensorView,
        zp_gate: Option<&TensorView>,
        zp_up: Option<&TensorView>,
        gamma: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
    ) -> Result<Option<bool>> {
        if self.block_size == 0
            || !self.k.is_multiple_of(16)
            || !self.k.is_multiple_of(self.block_size)
        {
            return Ok(None);
        }
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits Marlin int4 gate/up SwiGLU GEMM")?;

        let packed_gate_ptr = cuptr(packed_gate.data_ptr::<u8>() as *const c_void);
        let packed_up_ptr = cuptr(packed_up.data_ptr::<u8>() as *const c_void);
        let (weights_gate, gate_w_warm) = self.marlin_repack_cache.ensure_repacked(
            packed_gate_ptr,
            self.n,
            self.k,
            self.block_size,
        )?;
        let (weights_up, up_w_warm) = self.marlin_repack_cache.ensure_repacked(
            packed_up_ptr,
            self.n,
            self.k,
            self.block_size,
        )?;

        // Optionally stage the RMS-normalized activation into pooled scratch
        // (slot 0), byte-identical to the standalone prologue; both projections
        // then read that single normalized copy.
        let (act_ptr, norm_warm) = if let Some(gamma) = gamma {
            let norm_bytes = m * self.k * std::mem::size_of::<half::f16>();
            let (norm, norm_warm) = self.marlin_repack_cache.ensure_scratch(0, norm_bytes)?;
            self.launch_rmsnorm_prefill(activation, gamma, norm, m)?;
            (norm, norm_warm)
        } else {
            (cuptr(activation.data_ptr::<u8>() as *const c_void), true)
        };

        // Pooled gate-projection scratch (slot 1). The up projection writes the
        // real output; SiluMul folds them into the output in place.
        let out_bytes = output.byte_size();
        let (gate_buf, gate_s_warm) = self.marlin_repack_cache.ensure_scratch(1, out_bytes)?;
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);

        let gate_args = marlin_gemm::MarlinGemmArgs {
            activation: act_ptr,
            weights: weights_gate,
            scales: cuptr(scales_gate.data_ptr::<u8>() as *const c_void),
            zero_points: zp_gate.map(|t| cuptr(t.data_ptr::<u8>() as *const c_void)),
            bias: None,
            output: gate_buf,
            m,
            k: self.k,
            n: self.n,
            group_size: self.block_size,
            scales_fp16: true,
            bias_post_round: false,
            bias_row_stride: 0,
        };
        // Route both projections through split-K: at the M=K speculative-verify
        // width these gate/up GEMMs (the largest MLP projections) are
        // memory/latency-bound, so `choose_split_k` elects an 8-way K split to
        // fill the SMs. Partials use the shared slot-4 scratch sequentially (gate
        // fully reduces into `gate_buf` before the up GEMM overwrites the
        // partials), so the stream ordering keeps it correct and capture-safe.
        let gate_split_warm = self.maybe_launch_marlin_splitk(&gate_args)?;

        let up_args = marlin_gemm::MarlinGemmArgs {
            activation: act_ptr,
            weights: weights_up,
            scales: cuptr(scales_up.data_ptr::<u8>() as *const c_void),
            zero_points: zp_up.map(|t| cuptr(t.data_ptr::<u8>() as *const c_void)),
            bias: None,
            output: output_ptr,
            m,
            k: self.k,
            n: self.n,
            group_size: self.block_size,
            scales_fp16: true,
            bias_post_round: false,
            bias_row_stride: 0,
        };
        let up_split_warm = self.maybe_launch_marlin_splitk(&up_args)?;

        crate::kernels::elementwise::launch_silu_mul_f16_raw(
            &self.runtime,
            gate_buf,
            output_ptr,
            output_ptr,
            output.numel(),
            self.decomposed_silu,
        )?;

        Ok(Some(
            gate_w_warm
                && up_w_warm
                && norm_warm
                && gate_s_warm
                && gate_split_warm
                && up_split_warm,
        ))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_f16_gemm(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        k_blocks: usize,
        blob_size: usize,
        bias_row_stride: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits fp16 prefill GEMM")?;
        let general_block_size = self.block_size != 32;
        let entry = if general_block_size {
            GEMM_F16_GENERAL_BS_ENTRY
        } else {
            GEMM_F16_ENTRY
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let m_i32 = as_i32("M", m)?;
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let bits = as_i32("bits", self.bits)?;
        let scales_fp16_flag = scales_fp16 as i32;
        let bias_post_round_flag: i32 = (self.fold_bias_post_round && bias.is_some()) as i32;
        let bias_row_stride_i32 = as_i32("bias row stride", bias_row_stride)?;
        let block_size_i32 = as_i32("block_size", self.block_size)?;
        let blob_size_i32 = as_i32("block blob size", blob_size)?;
        let grid_x = u32::try_from(self.n.div_ceil(GEMM_F16_TILE))
            .map_err(|_| error(format!("N={} exceeds CUDA prefill grid limits", self.n)))?;
        let grid_y = u32::try_from(m.div_ceil(GEMM_F16_TILE))
            .map_err(|_| error(format!("M={m} exceeds CUDA prefill grid limits")))?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&m_i32)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks)
            .arg(&bits)
            .arg(&scales_fp16_flag)
            .arg(&bias_post_round_flag)
            .arg(&bias_row_stride_i32);
        // The general-block-size prefill kernel takes two extra trailing scalars
        // (`block_size`, `blob_size`) to derive the packed layout for any block
        // width; the tuned block-32 kernel bakes those in and takes neither.
        if general_block_size {
            builder.arg(&block_size_i32).arg(&blob_size_i32);
        }
        // SAFETY: dense tensors and all dimensions were validated
        // above. The 16x16 CTA uses 4 KiB of statically sized shared memory,
        // ordinary fp32 CUDA-core arithmetic, and fp16 conversions only. It has
        // no tensor-core/PTX/cp.async dependency, so the same path is the
        // portable fallback on every CUDA SM supported by this crate.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (grid_x, grid_y, 1),
                block_dim: (GEMM_F16_TILE as u32, GEMM_F16_TILE as u32, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits fp16 prefill GEMM", err))
    }

    /// M>1 prefill path for the fused RMS-normalization prologue. It stages the
    /// per-token normalized activation (byte-identical to the standalone
    /// `skip_rmsnorm_f16_warp_half4` output) into scratch, then runs the
    /// portable tiled GEMM over it. Prefill is outside the persistent decode
    /// graph, so the scratch allocation here is not on any captured path.
    #[allow(clippy::too_many_arguments)]
    fn launch_f16_gemm_rmsnorm_prefill(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        gamma: &TensorView,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        k_blocks: usize,
        bias_row_stride: usize,
    ) -> Result<()> {
        let scratch = self
            .runtime
            .alloc_raw(m * self.k * std::mem::size_of::<half::f16>())?;
        let scratch_shape = [m, self.k];
        let scratch_strides = [self.k as i64, 1];
        let normalized = TensorView::new(
            DevicePtr(raw_ptr(scratch) as *const c_void),
            DataType::Float16,
            &scratch_shape,
            &scratch_strides,
            activation.device,
        );
        let result = self
            .launch_rmsnorm_prefill(activation, gamma, scratch, m)
            .and_then(|()| {
                self.launch_f16_gemm(
                    &normalized,
                    packed,
                    scales,
                    true,
                    zero_points,
                    bias,
                    output,
                    m,
                    k_blocks,
                    self.block_size * self.bits / 8,
                    bias_row_stride,
                )
            });
        // SAFETY: `scratch` came from `alloc_raw` above and is freed exactly
        // once; `cuMemFree` waits for the preceding norm + GEMM stream work.
        let free_scratch = unsafe { self.runtime.free_raw(scratch) };
        result.and(free_scratch)
    }

    /// Launches the standalone RMS-normalization prologue used by prefill. One
    /// warp normalizes one token row of `activation` into `normalized`.
    fn launch_rmsnorm_prefill(
        &self,
        activation: &TensorView,
        gamma: &TensorView,
        normalized: CUdeviceptr,
        m: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits fp16 RMS-norm prefill prologue")?;
        let function =
            self.runtime
                .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, RMSNORM_PREFILL_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let gamma_ptr = cuptr(gamma.data_ptr::<u8>() as *const c_void);
        let normalized_ptr = normalized;
        let norm_size = as_i32("K", self.k)?;
        let num_groups = as_i32("M", m)?;
        let gamma_is_half: i32 = (gamma.dtype == DataType::Float16) as i32;
        let epsilon = self.rmsnorm_epsilon;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&gamma_ptr)
            .arg(&normalized_ptr)
            .arg(&norm_size)
            .arg(&num_groups)
            .arg(&gamma_is_half)
            .arg(&epsilon);
        // SAFETY: `activation` and `gamma` are validated contiguous fp16 tensors
        // and `normalized` is a `K * M`-half scratch buffer allocated by the
        // caller. Each of the `M` one-warp blocks reads/writes only its own row
        // with the launch-predicate-guaranteed `K % 128 == 0` half4 chunking.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (m as u32, 1, 1),
                block_dim: (RMSNORM_PREFILL_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits fp16 RMS-norm prefill prologue", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_int8_f16_gemv(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits int8 fp16 GEMV")?;
        // Grid-starved standalone int8-zp GEMV (e.g. Phi's int8 down projection,
        // grid 384 / ~0.48 waves/SM): when K is a whole multiple of the 256-wide
        // step and the shape uses the 256-thread large path, take the split-K
        // entry (K_SPLIT warps/column, K_SPLIT x larger grid) to fill the SMs.
        // This kernel has no serial prologue, so the extra grid parallelism pays
        // off directly. Asymmetric int8 (with zero points) fires unconditionally
        // on the large path; SYMMETRIC int8 (no zero points) opts in only when
        // the live SM count says the single-warp grid is too narrow (mirrors the
        // symmetric int4 grid-fill gate [`use_f16_symmetric_splitk`]), so the
        // already-occupied wide projections keep the byte-identical single-warp
        // entry and small consumer GPUs are unaffected. The symmetric split-K
        // reassociates the per-column fp32 partials (near-equal, not
        // byte-identical) — greedy-token-stable under fp32 accumulation — and is
        // opt-out via `int8_symmetric_splitk_enabled`.
        let large_path_eligible = self.k.is_multiple_of(256)
            && !(self.n <= GEMV_F16_SMALL_N_MAX && self.k <= GEMV_F16_SMALL_N_MAX);
        let capabilities = self.runtime.capabilities();
        let use_splitk = large_path_eligible
            && if zero_points.is_some() {
                true
            } else {
                int8_symmetric_splitk_enabled()
                    && use_f16_symmetric_splitk(
                        self.k,
                        self.n,
                        capabilities.multiprocessor_count(),
                        capabilities.max_threads_per_block(),
                    )
            };
        let entry = if use_splitk {
            GEMV_INT8_F16_SPLITK_ENTRY
        } else {
            GEMV_INT8_F16_ENTRY
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let scales_fp16_flag = scales_fp16 as i32;
        let bias_post_round_flag: i32 = (self.fold_bias_post_round && bias.is_some()) as i32;
        let threads = if self.n <= GEMV_F16_SMALL_N_MAX && self.k <= GEMV_F16_SMALL_N_MAX {
            GEMV_F16_SMALL_THREADS
        } else {
            GEMV_F16_LARGE_THREADS
        };
        let columns_per_block = if use_splitk {
            (threads / 32) as usize / GEMV_INT8_F16_SPLITK
        } else {
            (threads / 32) as usize
        };
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks)
            .arg(&scales_fp16_flag)
            .arg(&bias_post_round_flag);
        // SAFETY: validation restricts this entry to dense fp16 block-32 M=1
        // tensors. The kernel uses fixed device pointers, registers, and warp
        // shuffles only, so it performs no allocation or synchronization and is
        // legal to capture and replay on every CUDA SM supported by this crate.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n.div_ceil(columns_per_block) as u32, 1, 1),
                block_dim: (threads, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits int8 fp16 GEMV", err))
    }

    /// INT8 decode GEMV with a fused RMS-normalization prologue. Mirrors
    /// [`Self::launch_f16_gemv_rmsnorm`] but dispatches the int8 sibling kernel,
    /// which shares the RMS reduction / normalized-activation staging bit-for-bit
    /// and swaps in the block-32 int8 dequant dot. Restricted to fp16 scales and
    /// block-32, matching the fusion's eligibility gates.
    #[allow(clippy::too_many_arguments)]
    fn launch_int8_f16_gemv_rmsnorm(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        gamma: &TensorView,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits int8 fp16 RMS-norm-prologue GEMV")?;
        if bias.is_some() {
            if self.fold_bias_post_round {
                onnx_runtime_ep_api::record_kernel_variant_stage!(
                    "bias",
                    "qkv_bias_fused",
                    "folded standalone Add(MatMulNBits, bias) into GEMV epilogue with \
                     fp16-after-round semantics fp16(fp16(acc)+bias) (token-identity preserved)"
                );
            } else {
                onnx_runtime_ep_api::record_kernel_variant_stage!(
                    "bias",
                    "bias_native",
                    "native MatMulNBits bias: single-round epilogue fp16(acc+bias)"
                );
            }
        }
        let entry = if zero_points.is_some() {
            GEMV_INT8_F16_SCALES_F16_RMSNORM_ZP_ENTRY
        } else {
            GEMV_INT8_F16_SCALES_F16_RMSNORM_ENTRY
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let gamma_ptr = cuptr(gamma.data_ptr::<u8>() as *const c_void);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let bias_post_round_flag: i32 = (self.fold_bias_post_round && bias.is_some()) as i32;
        let gamma_is_half: i32 = (gamma.dtype == DataType::Float16) as i32;
        let epsilon = self.rmsnorm_epsilon;
        let threads = if self.n <= GEMV_F16_SMALL_N_MAX && self.k <= GEMV_F16_SMALL_N_MAX {
            GEMV_F16_SMALL_THREADS
        } else {
            GEMV_F16_LARGE_THREADS
        };
        let columns_per_block = (threads / 32) as usize;
        let shared_mem_bytes = (self.k * std::mem::size_of::<half::f16>()) as u32;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&gamma_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks)
            .arg(&bias_post_round_flag)
            .arg(&gamma_is_half)
            .arg(&epsilon);
        // SAFETY: restricted to block-32 M=1 fp16 inputs with fp16 scales, all
        // dtype/shape/contiguity validated above. The kernel stages the
        // normalized activation in launch-time dynamic shared memory
        // (`K * sizeof(f16)`, bounded by the fusion's `K % 128 == 0` predicate)
        // and uses only registers, warp shuffles, and `__syncthreads` — no
        // per-call allocation or host synchronization — so it is legal to record
        // into and replay from a CUDA graph.
        // Clamp the K-sized activation stage to the device's shared-memory
        // budget: opt into >48 KB when the card allows it, and fail loudly
        // (rather than launch-crash on a smaller consumer GPU) if K exceeds even
        // the opt-in ceiling.
        self.runtime
            .configure_dynamic_shared_memory(&function, shared_mem_bytes)?;
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n.div_ceil(columns_per_block) as u32, 1, 1),
                block_dim: (threads, 1, 1),
                shared_mem_bytes,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits int8 fp16 RMS-norm-prologue GEMV", err))
    }

    /// Paired gate/up projection + SwiGLU path (see
    /// [`crate::optimizer::CudaGateUpSwiGluFusion`]). Inputs are
    /// `[x, W_gate, scales_gate, W_up, scales_up]`. M=1 keeps the paired decode
    /// GEMV unchanged; M>1 reuses the portable tiled prefill GEMM for both
    /// projections before applying the existing fp16 `silu(gate)*up` kernel.
    fn run_f16_gate_up_swiglu(
        &self,
        inputs: &[TensorView],
        outputs: &mut [TensorMut],
        workspace: Option<WorkspaceView>,
    ) -> Result<()> {
        // Contract from `CudaGateUpSwiGluFusion`:
        //   [x, W_gate, scales_gate, W_up, scales_up, (gamma?)@5, (zp_gate?)@6, (zp_up?)@7]
        // Slot 5 carries the RMS-norm gamma when the skip-rmsnorm prologue is
        // folded in; slots 6/7 carry per-projection asymmetric zero points
        // (both present for asymmetric weights, both absent for symmetric ones).
        if !(5..=8).contains(&inputs.len()) || outputs.len() != 1 {
            return Err(error(format!(
                "gate/up SwiGLU fusion expects 5 to 8 inputs [x, W_gate, scales_gate, W_up, \
                 scales_up, (gamma), (zp_gate, zp_up)] and 1 output, got {} inputs and {} outputs",
                inputs.len(),
                outputs.len()
            )));
        }
        require_dtype("A", inputs[0].dtype, DataType::Float16)?;
        require_dtype("W_gate", inputs[1].dtype, DataType::Uint8)?;
        require_dtype("scales_gate", inputs[2].dtype, DataType::Float16)?;
        require_dtype("W_up", inputs[3].dtype, DataType::Uint8)?;
        require_dtype("scales_up", inputs[4].dtype, DataType::Float16)?;
        require_dtype("Y", outputs[0].dtype, DataType::Float16)?;
        let gamma = if self.rmsnorm_prologue {
            let gamma = optional_input(inputs, 5).ok_or_else(|| {
                error("rmsnorm_prologue fusion requires the normalization weight at input 5")
            })?;
            require_gamma_dtype(gamma.dtype)?;
            require_shape("gamma", gamma.shape, &[self.k])?;
            if !gamma.is_contiguous() {
                return Err(error(
                    "gamma must be contiguous on the CUDA execution provider".to_string(),
                ));
            }
            Some(gamma)
        } else {
            None
        };

        let a_shape = inputs[0].shape;
        if a_shape.is_empty() || a_shape[a_shape.len() - 1] != self.k {
            return Err(error(format!(
                "A must have rank >= 1 and last dimension K={}, got {:?}",
                self.k, a_shape
            )));
        }
        let m = a_shape[..a_shape.len() - 1].iter().product::<usize>();
        let expected_output_shape = [&a_shape[..a_shape.len() - 1], &[self.n]].concat();
        if outputs[0].shape != expected_output_shape {
            return Err(error(format!(
                "Y must have shape {expected_output_shape:?}, got {:?}",
                outputs[0].shape
            )));
        }

        if self.block_size != 32 || self.bits != 4 {
            return Err(error(format!(
                "gate/up SwiGLU fusion received bits={} and block_size={}. Why: the fused fp16 \
                 path implements the block-32 packed int4 layout. How to fix: export 4-bit \
                 MatMulNBits weights with block_size=32 or disable this fusion",
                self.bits, self.block_size
            )));
        }
        let k_blocks = self.k.div_ceil(self.block_size);
        let blob_size = self.block_size / 2;
        require_shape("W_gate", inputs[1].shape, &[self.n, k_blocks, blob_size])?;
        require_shape("W_up", inputs[3].shape, &[self.n, k_blocks, blob_size])?;
        require_flat_or_matrix_shape("scales_gate", inputs[2].shape, self.n, k_blocks)?;
        require_flat_or_matrix_shape("scales_up", inputs[4].shape, self.n, k_blocks)?;

        // Optional asymmetric zero points (slots 6/7). Symmetric weights omit
        // both and the kernels apply the implicit `zp == 8` subtrahend, matching
        // the historical byte-identical path. Require them paired: mixing a
        // zero-point projection with a symmetric one is never valid.
        let zp_gate = optional_input(inputs, 6);
        let zp_up = optional_input(inputs, 7);
        if zp_gate.is_some() != zp_up.is_some() {
            return Err(error(
                "gate/up SwiGLU fusion requires zero points for both projections or neither"
                    .to_string(),
            ));
        }
        let zp_row_bytes = (k_blocks * self.bits).div_ceil(8);
        for (name, zp) in [("zp_gate", zp_gate), ("zp_up", zp_up)] {
            if let Some(zp) = zp {
                require_dtype(name, zp.dtype, DataType::Uint8)?;
                require_flat_or_matrix_shape(name, zp.shape, self.n, zp_row_bytes)?;
                if !zp.is_contiguous() {
                    return Err(error(format!(
                        "{name} must be contiguous on the CUDA execution provider"
                    )));
                }
            }
        }

        for (name, contiguous) in [
            ("A", inputs[0].is_contiguous()),
            ("W_gate", inputs[1].is_contiguous()),
            ("scales_gate", inputs[2].is_contiguous()),
            ("W_up", inputs[3].is_contiguous()),
            ("scales_up", inputs[4].is_contiguous()),
            ("Y", outputs[0].is_contiguous()),
        ] {
            if !contiguous {
                return Err(error(format!(
                    "{name} must be contiguous on the CUDA execution provider"
                )));
            }
        }
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let rows = m as u64;
            let mut flops = rows
                .saturating_mul(self.n as u64)
                .saturating_mul(self.k as u64)
                .saturating_mul(4)
                .saturating_add(rows.saturating_mul(self.n as u64).saturating_mul(5));
            if self.rmsnorm_prologue {
                let elements = rows.saturating_mul(self.k as u64);
                flops = flops
                    .saturating_add(elements.saturating_mul(4))
                    .saturating_add(rows.saturating_mul(4));
            }
            flops
        });

        if m == 0 {
            self.last_call_capture_safe.store(false, Ordering::Relaxed);
            onnx_runtime_ep_api::record_kernel_variant!(
                "gate_up_swiglu_empty",
                "M=0 gate/up SwiGLU has an empty output and requires no CUDA launch"
            );
            return Ok(());
        }
        if m > 1 {
            // Small-batch decode fast path (mirrors the plain-GEMV loop in
            // `run_f16`): for M within the crossover window, loop the capture-safe
            // M==1 fused gate/up SwiGLU GEMV once per row instead of the tiled
            // prefill GEMM. Each row is computed byte-identically to a
            // single-sequence (M==1) fused SwiGLU decode of that row, and every
            // per-row launch is static-grid, allocation- and sync-free, so the
            // batch decode graph captures it as part of the whole-subgraph capture
            // instead of fragmenting into an eager seam. This is the node that
            // otherwise leaves batch-N (M>=2) decode capturing as many segments as
            // there are MLP layers, whose per-step eager replay dominates the
            // M>=2 step cost. Streaming is unaffected: the resident gate/up weight
            // is read M times from VRAM, not re-streamed (HtoD 1/N amortization
            // intact).
            //
            // GATED TO THE RMS-NORM-PROLOGUE (`gamma.is_some()`) PATH ONLY. The
            // production skip-rmsnorm fusion (`CudaGateUpSwiGluFusion` +
            // `MATMUL_NBITS_RMSNORM_PROLOGUE_ATTR`) folds the pre-MLP RMS norm
            // into this node for every RMSNorm architecture (Qwen/Llama/Phi), so
            // the resident-model decode win lives entirely on this branch. A ULP
            // sweep (`fp16_gate_up_swiglu_rmsnorm_two_op_ulp_bound_sweep`) shows
            // the fused rmsnorm decode GEMV is BYTE-IDENTICAL (0 ULP, 0/60 cases)
            // to the two-op decode reference at M==1, so routing M>1 through the
            // per-row loop is byte-exact to running each row alone as M==1 decode
            // (the batching contract) AND within the two-op decode identity.
            //
            // The PLAIN (`gamma.is_none()`) gate/up SwiGLU is intentionally NOT
            // routed here: its M==1 fused decode GEMV is measured up to 2 ULP off
            // the two-op decode reference (8/56 cases in
            // `fp16_gate_up_swiglu_two_op_ulp_bound_sweep`), so a looped M>1
            // decode-GEMV would change plain-path logits vs the two-op path by
            // more than 1 ULP. It stays on the prefill/Marlin path (advertised
            // capture-unsafe at M>1) pending a decision on that bound in #1334.
            if m <= decode_gemv_loop_max_m()
                && decode_gemv_loop_rows_aligned(self.k)
                && let Some(gamma) = gamma
            {
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gate_up_swiglu_rmsnorm_batched_loop",
                    "M={} small-batch rmsnorm decode: {} single-row fused gate/up SwiGLU \
                         GEMV launches (one per row), each byte-identical to M==1 decode; keeps \
                         the batch decode graph a single captured subgraph instead of a \
                         per-MLP-layer eager seam",
                    m,
                    m
                );
                self.last_call_capture_safe.store(true, Ordering::Relaxed);
                let a_base = inputs[0].data_ptr::<u8>();
                let y_base = outputs[0].data_ptr_mut::<u8>();
                let a_row_shape = [1usize, self.k];
                let a_row_strides = [self.k as i64, 1];
                let y_row_shape = [1usize, self.n];
                let y_row_strides = [self.n as i64, 1];
                let a_row_bytes = self.k * 2; // fp16 activation
                let y_row_bytes = self.n * 2; // fp16 output
                for row in 0..m {
                    let a_row = TensorView::new(
                        DevicePtr(a_base.wrapping_add(row * a_row_bytes) as *const c_void),
                        DataType::Float16,
                        &a_row_shape,
                        &a_row_strides,
                        inputs[0].device,
                    );
                    let mut y_row = TensorMut::new(
                        DevicePtrMut(y_base.wrapping_add(row * y_row_bytes) as *mut c_void),
                        DataType::Float16,
                        &y_row_shape,
                        &y_row_strides,
                        outputs[0].device,
                    );
                    self.launch_gate_up_swiglu_rmsnorm(
                        &a_row,
                        &inputs[1],
                        &inputs[2],
                        &inputs[3],
                        &inputs[4],
                        zp_gate,
                        zp_up,
                        gamma,
                        &mut y_row,
                        k_blocks,
                        blob_size,
                        zp_row_bytes,
                    )?;
                }
                return Ok(());
            }
            self.last_call_capture_safe.store(false, Ordering::Relaxed);
            // Dequantize both projections to fp16 and run them on cuBLASLt
            // tensor cores, ahead of Marlin, for the reason given at the
            // unfused M>1 site: Marlin re-reads its whole A panel from global
            // memory per warp on these shapes. These are the widest projections
            // in the decoder, so leaving them behind would cap the win.
            if dequant_f16_gemm_enabled() && m >= dequant_f16_gemm_min_m() {
                match self.try_dequant_f16_gate_up_prefill(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    &inputs[3],
                    &inputs[4],
                    inputs[2].dtype == DataType::Float16,
                    zp_gate,
                    zp_up,
                    gamma,
                    &mut outputs[0],
                    m,
                    k_blocks,
                    blob_size,
                    zp_row_bytes,
                    workspace,
                ) {
                    Ok(true) => {
                        onnx_runtime_ep_api::record_kernel_variant!(
                            "gate_up_swiglu_dequant_f16_cublas",
                            "M={} prefill: dequantize both int{} projections to [N, K] fp16, \
                             two cuBLASLt fp16 tensor-core GEMMs, then the fp16 SiluMul \
                             epilogue",
                            m,
                            self.bits
                        );
                        return Ok(());
                    }
                    Ok(false) => {
                        if std::env::var_os("ONNX_GENAI_DEQUANT_F16_DEBUG").is_some() {
                            eprintln!("dequant_f16 gate/up: ineligible m={m}");
                        }
                    }
                    Err(_err) => {
                        if std::env::var_os("ONNX_GENAI_DEQUANT_F16_DEBUG").is_some() {
                            eprintln!("dequant_f16 gate/up: {_err}");
                        }
                    }
                }
            }
            // Opt-in Marlin int4 tensor-core path for the paired gate/up MLP:
            // both projections run on tensor cores, then the same fp16 SiluMul
            // epilogue. This is the bulk of prefill/verify cost and the last
            // MatMulNBits node that otherwise falls back to the tiled GEMM at
            // M>1 (which would keep the captured forward segmented). Warm replays
            // (pooled weights + scratch) are capture-safe. Falls through to the
            // tiled gate/up prefill on ineligibility or launch error.
            if marlin_gemm::marlin_m_gt_1_enabled()
                && self.bits == 4
                && self.marlin_weight_inputs_constant()
                && marlin_gemm::device_supports_marlin(
                    self.runtime.capabilities().compute_capability(),
                )
            {
                match self.try_launch_marlin_gate_up_prefill(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    &inputs[3],
                    &inputs[4],
                    zp_gate,
                    zp_up,
                    gamma,
                    &mut outputs[0],
                    m,
                ) {
                    Ok(Some(warm)) => {
                        self.last_call_capture_safe.store(warm, Ordering::Relaxed);
                        onnx_runtime_ep_api::record_kernel_variant!(
                            "gate_up_swiglu_marlin_prefill",
                            "M={} prefill/verify: {}paired gate/up Marlin SM80 mma.sync int4 \
                             tensor-core GEMMs followed by fp16 SiluMul (capture-safe when \
                             weights + scratch are pre-warmed)",
                            m,
                            if gamma.is_some() {
                                "RMS-normalization prologue then "
                            } else {
                                ""
                            }
                        );
                        return Ok(());
                    }
                    Ok(None) => {
                        // Ineligible shape; fall through to the tiled prefill.
                    }
                    Err(_err) => {
                        // Hard error; fall through to the tiled prefill.
                    }
                }
            }
            if let Some(gamma) = gamma {
                onnx_runtime_ep_api::record_kernel_variant!(
                    "gate_up_swiglu_rmsnorm_prefill",
                    "M={} prefill: RMS-normalization prologue into scratch, then two portable \
                     block-32 int4 fp16 tiled GEMMs with fp32 accumulation, followed by fp16 \
                     SiluMul; not advertised as CUDA-graph capture-safe",
                    m
                );
                return self.launch_gate_up_swiglu_rmsnorm_prefill(
                    &inputs[0],
                    &inputs[1],
                    &inputs[2],
                    &inputs[3],
                    &inputs[4],
                    zp_gate,
                    zp_up,
                    gamma,
                    &mut outputs[0],
                    m,
                    k_blocks,
                    zp_row_bytes,
                );
            }
            onnx_runtime_ep_api::record_kernel_variant!(
                "gate_up_swiglu_prefill",
                "M={} prefill: two portable block-32 int4 fp16 tiled GEMMs with fp32 \
                 accumulation, followed by fp16 SiluMul; not advertised as CUDA-graph \
                 capture-safe",
                m
            );
            return self.launch_gate_up_swiglu_prefill(
                &inputs[0],
                &inputs[1],
                &inputs[2],
                &inputs[3],
                &inputs[4],
                zp_gate,
                zp_up,
                &mut outputs[0],
                m,
                k_blocks,
            );
        }

        if let Some(gamma) = gamma {
            onnx_runtime_ep_api::record_kernel_variant!(
                "gate_up_swiglu_rmsnorm_fused",
                "fp16 block-32 M==1 decode: fused RMS-normalization prologue + paired gate/up \
                 int4 GEMV + SwiGLU (silu(gate)*up) in one capture-safe kernel; the RMS \
                 reduction runs once for both projections and reproduces the standalone norm \
                 plus two-op fp16 rounding for byte-identical greedy tokens"
            );
            self.last_call_capture_safe.store(true, Ordering::Relaxed);
            return self.launch_gate_up_swiglu_rmsnorm(
                &inputs[0],
                &inputs[1],
                &inputs[2],
                &inputs[3],
                &inputs[4],
                zp_gate,
                zp_up,
                gamma,
                &mut outputs[0],
                k_blocks,
                blob_size,
                zp_row_bytes,
            );
        }

        onnx_runtime_ep_api::record_kernel_variant!(
            "gate_up_swiglu_fused",
            "fp16 block-32 M==1 decode: fused paired gate/up int4 GEMV + SwiGLU \
             (silu(gate)*up) in one capture-safe kernel; reproduces the two-op fp16 \
             rounding for byte-identical greedy tokens"
        );

        self.last_call_capture_safe.store(true, Ordering::Relaxed);
        self.launch_gate_up_swiglu(
            &inputs[0],
            &inputs[1],
            &inputs[2],
            &inputs[3],
            &inputs[4],
            zp_gate,
            zp_up,
            &mut outputs[0],
            k_blocks,
            blob_size,
            zp_row_bytes,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_gate_up_swiglu_prefill(
        &self,
        activation: &TensorView,
        packed_gate: &TensorView,
        scales_gate: &TensorView,
        packed_up: &TensorView,
        scales_up: &TensorView,
        zp_gate: Option<&TensorView>,
        zp_up: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        k_blocks: usize,
    ) -> Result<()> {
        let scratch = self.runtime.alloc_raw(output.byte_size())?;
        let scratch_shape = output.shape.to_vec();
        let scratch_strides = output.strides.to_vec();
        let mut gate_output = TensorMut::new(
            DevicePtrMut(raw_ptr(scratch)),
            DataType::Float16,
            &scratch_shape,
            &scratch_strides,
            output.device,
        );

        let result = (|| {
            self.launch_f16_gemm(
                activation,
                packed_gate,
                scales_gate,
                true,
                zp_gate,
                None,
                &mut gate_output,
                m,
                k_blocks,
                self.block_size * self.bits / 8,
                0,
            )?;
            self.launch_f16_gemm(
                activation,
                packed_up,
                scales_up,
                true,
                zp_up,
                None,
                output,
                m,
                k_blocks,
                self.block_size * self.bits / 8,
                0,
            )?;
            let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
            crate::kernels::elementwise::launch_silu_mul_f16_raw(
                &self.runtime,
                scratch,
                output_ptr,
                output_ptr,
                output.numel(),
                self.decomposed_silu,
            )
        })();

        // Always release the prefill gate projection. `cuMemFree` waits for
        // preceding stream work that uses this allocation, including SiluMul.
        // SAFETY: `scratch` came from `alloc_raw` above and is freed exactly once.
        let free_scratch = unsafe { self.runtime.free_raw(scratch) };
        result.and(free_scratch)
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_gate_up_swiglu(
        &self,
        activation: &TensorView,
        packed_gate: &TensorView,
        scales_gate: &TensorView,
        packed_up: &TensorView,
        scales_up: &TensorView,
        zp_gate: Option<&TensorView>,
        zp_up: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits fp16 gate/up SwiGLU GEMV")?;
        // Symmetric weights launch the `HasZp == false` entry, whose PTX drops the
        // per-block zero-point load entirely; only asymmetric weights pay for it.
        // When `ONNX_GENAI_GATEUP_VEC` is armed, the symmetric entries reroute to
        // their byte-identical fused-symmetric `_vec` sibling (fewer issued ops).
        let has_zp = zp_gate.is_some() || zp_up.is_some();
        let vec = !has_zp && gate_up_vec_enabled();
        let entry = match (self.decomposed_silu, has_zp, vec) {
            (true, true, _) => GATE_UP_DECOMPOSED_SWIGLU_ZP_ENTRY,
            (true, false, true) => GATE_UP_DECOMPOSED_SWIGLU_VEC_ENTRY,
            (true, false, false) => GATE_UP_DECOMPOSED_SWIGLU_ENTRY,
            (false, true, _) => GATE_UP_SWIGLU_ZP_ENTRY,
            (false, false, true) => GATE_UP_SWIGLU_VEC_ENTRY,
            (false, false, false) => GATE_UP_SWIGLU_ENTRY,
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_gate_ptr = cuptr(packed_gate.data_ptr::<u8>() as *const c_void);
        let scales_gate_ptr = cuptr(scales_gate.data_ptr::<u8>() as *const c_void);
        let packed_up_ptr = cuptr(packed_up.data_ptr::<u8>() as *const c_void);
        let scales_up_ptr = cuptr(scales_up.data_ptr::<u8>() as *const c_void);
        let zp_gate_ptr = zp_gate
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let zp_up_ptr = zp_up
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row byte count", zp_row_bytes)?;
        let threads = GATE_UP_SWIGLU_THREADS;
        let columns_per_block = (threads / 32) as usize;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_gate_ptr)
            .arg(&scales_gate_ptr)
            .arg(&packed_up_ptr)
            .arg(&scales_up_ptr)
            .arg(&zp_gate_ptr)
            .arg(&zp_up_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes);
        // SAFETY: restricted to fp16 block-32 M=1 inputs validated above; both
        // persistent weight/scale sets and the output are fixed device pointers,
        // the scalar ABI matches the paired entry point, and the kernel uses only
        // registers + warp shuffles (no per-call alloc, shared memory, or sync),
        // so the launch is legal to record into and replay from a CUDA graph.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n.div_ceil(columns_per_block) as u32, 1, 1),
                block_dim: (threads, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits fp16 gate/up SwiGLU GEMV", err))
    }

    /// Decode (M==1) paired gate/up SwiGLU with a fused RMS-normalization
    /// prologue. The block reduces the shared activation once and stages the
    /// normalized activation in launch-time dynamic shared memory (`K *
    /// sizeof(f16)`, bounded by the fusion's `K % 128 == 0` predicate), then
    /// both projections read that single staged copy. Fixing the reduction to a
    /// single pass is what recovers the double-recompute cost the fan-out-2
    /// post-attention norm otherwise pays.
    #[allow(clippy::too_many_arguments)]
    fn launch_gate_up_swiglu_rmsnorm(
        &self,
        activation: &TensorView,
        packed_gate: &TensorView,
        scales_gate: &TensorView,
        packed_up: &TensorView,
        scales_up: &TensorView,
        zp_gate: Option<&TensorView>,
        zp_up: Option<&TensorView>,
        gamma: &TensorView,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits fp16 gate/up SwiGLU RMS-norm GEMV")?;
        // `ONNX_GENAI_GATEUP_VEC` reroutes the symmetric RMS-norm-fused entries to
        // their byte-identical fused-symmetric `_vec` sibling (fewer issued ops);
        // `ONNX_GENAI_GATEUP_OCC` further reroutes them to the `_vec_occ` sibling
        // (same body + `__launch_bounds__(256, 8)` to raise occupancy 62->83% and
        // hide the Short-Scoreboard shared-load latency). Both are byte-identical.
        let has_zp = zp_gate.is_some() || zp_up.is_some();
        let vec = !has_zp && gate_up_vec_enabled();
        let occ = !has_zp && gate_up_occ_enabled();
        let entry = match (self.decomposed_silu, has_zp, occ, vec) {
            (true, true, _, _) => GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_ZP_ENTRY,
            (true, false, true, _) => GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_VEC_OCC_ENTRY,
            (true, false, false, true) => GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_VEC_ENTRY,
            (true, false, false, false) => GATE_UP_DECOMPOSED_SWIGLU_RMSNORM_ENTRY,
            (false, true, _, _) => GATE_UP_SWIGLU_RMSNORM_ZP_ENTRY,
            (false, false, true, _) => GATE_UP_SWIGLU_RMSNORM_VEC_OCC_ENTRY,
            (false, false, false, true) => GATE_UP_SWIGLU_RMSNORM_VEC_ENTRY,
            (false, false, false, false) => GATE_UP_SWIGLU_RMSNORM_ENTRY,
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_gate_ptr = cuptr(packed_gate.data_ptr::<u8>() as *const c_void);
        let scales_gate_ptr = cuptr(scales_gate.data_ptr::<u8>() as *const c_void);
        let packed_up_ptr = cuptr(packed_up.data_ptr::<u8>() as *const c_void);
        let scales_up_ptr = cuptr(scales_up.data_ptr::<u8>() as *const c_void);
        let zp_gate_ptr = zp_gate
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let zp_up_ptr = zp_up
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let gamma_ptr = cuptr(gamma.data_ptr::<u8>() as *const c_void);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row byte count", zp_row_bytes)?;
        let gamma_is_half: i32 = (gamma.dtype == DataType::Float16) as i32;
        let epsilon = self.rmsnorm_epsilon;
        let threads = GATE_UP_SWIGLU_THREADS;
        let columns_per_block = (threads / 32) as usize;
        let shared_mem_bytes = (self.k * std::mem::size_of::<half::f16>()) as u32;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_gate_ptr)
            .arg(&scales_gate_ptr)
            .arg(&packed_up_ptr)
            .arg(&scales_up_ptr)
            .arg(&zp_gate_ptr)
            .arg(&zp_up_ptr)
            .arg(&gamma_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes)
            .arg(&gamma_is_half)
            .arg(&epsilon);
        // SAFETY: restricted to fp16 block-32 M=1 inputs validated above; the
        // weight/scale/gamma sets and the output are fixed device pointers, the
        // scalar ABI matches the paired RMS-norm entry point, and the kernel
        // stages the normalized activation in launch-time dynamic shared memory
        // (`K * sizeof(f16)`, bounded by the fusion's `K % 128 == 0` predicate)
        // using only registers, warp shuffles, and `__syncthreads` — no per-call
        // allocation or host sync — so it is legal to record into and replay
        // from a CUDA graph.
        // Clamp the K-sized activation stage to the device's shared-memory
        // budget: opt into >48 KB when the card allows it, and fail loudly
        // (rather than launch-crash on a smaller consumer GPU) if K exceeds even
        // the opt-in ceiling.
        self.runtime
            .configure_dynamic_shared_memory(&function, shared_mem_bytes)?;
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n.div_ceil(columns_per_block) as u32, 1, 1),
                block_dim: (threads, 1, 1),
                shared_mem_bytes,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits fp16 gate/up SwiGLU RMS-norm GEMV", err))
    }

    /// Prefill (M>1) gate/up SwiGLU with an RMS-normalization prologue.
    /// Normalizes each token row into scratch (byte-identical to
    /// `skip_rmsnorm_f16_warp_half4`), then runs the standard paired gate/up
    /// SwiGLU prefill over the normalized activation. Prefill is outside the
    /// persistent decode graph, so the scratch allocation is not on any captured
    /// path.
    #[allow(clippy::too_many_arguments)]
    fn launch_gate_up_swiglu_rmsnorm_prefill(
        &self,
        activation: &TensorView,
        packed_gate: &TensorView,
        scales_gate: &TensorView,
        packed_up: &TensorView,
        scales_up: &TensorView,
        zp_gate: Option<&TensorView>,
        zp_up: Option<&TensorView>,
        gamma: &TensorView,
        output: &mut TensorMut,
        m: usize,
        k_blocks: usize,
        _zp_row_bytes: usize,
    ) -> Result<()> {
        let scratch = self
            .runtime
            .alloc_raw(m * self.k * std::mem::size_of::<half::f16>())?;
        let scratch_shape = [m, self.k];
        let scratch_strides = [self.k as i64, 1];
        let normalized = TensorView::new(
            DevicePtr(raw_ptr(scratch) as *const c_void),
            DataType::Float16,
            &scratch_shape,
            &scratch_strides,
            activation.device,
        );
        let result = self
            .launch_rmsnorm_prefill(activation, gamma, scratch, m)
            .and_then(|()| {
                self.launch_gate_up_swiglu_prefill(
                    &normalized,
                    packed_gate,
                    scales_gate,
                    packed_up,
                    scales_up,
                    zp_gate,
                    zp_up,
                    output,
                    m,
                    k_blocks,
                )
            });
        // SAFETY: `scratch` came from `alloc_raw` above and is freed exactly
        // once; `cuMemFree` waits for the preceding norm + GEMM stream work.
        let free_scratch = unsafe { self.runtime.free_raw(scratch) };
        result.and(free_scratch)
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_f16_gemv(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        let selection = select_f16_gemv_variant(
            self.k,
            self.n,
            self.block_size,
            scales_fp16,
            zero_points.is_some(),
        );
        // Non-block-32 layouts are served by the model-agnostic general_bs
        // kernel; tag them distinctly so nsys/trace timelines can tell the
        // block-size-general decode GEMV apart from a tuned block-32 general one.
        let variant_name = if self.block_size != 32 {
            "gemv_f16_general_bs"
        } else {
            match selection.variant {
                F16GemvVariant::DownProjection => "gemv_f16_down_projection",
                F16GemvVariant::General => "gemv_f16_general",
            }
        };
        onnx_runtime_ep_api::record_kernel_variant!(
            variant_name,
            "fp16-activation x int{} M==1 decode GEMV: block_size={}; zero_points={}; {}",
            self.bits,
            self.block_size,
            zero_points.is_some(),
            selection.reason
        );
        if bias.is_some() {
            if self.fold_bias_post_round {
                onnx_runtime_ep_api::record_kernel_variant_stage!(
                    "bias",
                    "qkv_bias_fused",
                    "folded standalone Add(MatMulNBits, bias) into GEMV epilogue with \
                     fp16-after-round semantics fp16(fp16(acc)+bias) (token-identity preserved)"
                );
            } else {
                onnx_runtime_ep_api::record_kernel_variant_stage!(
                    "bias",
                    "bias_native",
                    "native MatMulNBits bias: single-round epilogue fp16(acc+bias)"
                );
            }
        }
        self.launch_f16_gemv_variant(
            activation,
            packed,
            scales,
            scales_fp16,
            zero_points,
            bias,
            output,
            k_blocks,
            blob_size,
            zp_row_bytes,
            selection,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_f16_gemv_variant(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
        selection: F16GemvSelection,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits fp16 GEMV")?;
        // Split-K routing for standalone block-32, scales-fp16 general GEMVs.
        // Both the asymmetric (zero-point) and symmetric paths now gate on the
        // live SM count: split-K only fires when the single-warp warp grid is too
        // narrow to fill the device, so grid-saturated large-N projections keep
        // the single-warp (pipe) path and smaller GPUs keep their current path.
        let capabilities = self.runtime.capabilities();
        let use_scales_f16_zp_splitk = self.block_size == 32
            && scales_fp16
            && zero_points.is_some()
            && matches!(selection.variant, F16GemvVariant::General)
            && self.k.is_multiple_of(256)
            // Split-K needs >= K_SPLIT warps/block; the small-shape path uses only
            // 64 threads (2 warps), so restrict to the 256-thread large path.
            && !(self.n <= GEMV_F16_SMALL_N_MAX && self.k <= GEMV_F16_SMALL_N_MAX)
            // Split-K helps for two independent reasons; this gate covers both.
            // See [`use_scales_f16_zp_splitk_gate`].
            && use_scales_f16_zp_splitk_gate(
                self.k,
                self.n,
                capabilities.multiprocessor_count(),
            );
        let scales_f16_zp_factor =
            scales_f16_zp_split_factor(self.n, capabilities.multiprocessor_count());
        let use_scales_f16_symmetric_splitk = self.block_size == 32
            && scales_fp16
            && zero_points.is_none()
            && matches!(selection.variant, F16GemvVariant::General)
            && use_f16_symmetric_splitk(
                self.k,
                self.n,
                capabilities.multiprocessor_count(),
                capabilities.max_threads_per_block(),
            );
        let use_scales_f16_splitk = use_scales_f16_zp_splitk || use_scales_f16_symmetric_splitk;
        // Prefetch-pipeline routing for the SINGLE-WARP block-32 scales-fp16 int4
        // GEMV (the entry taken when split-K is not selected). Byte-identical to
        // the original entry (same mapping/math/order) but keeps 2 weight loads
        // in flight per lane to hide the Long-Scoreboard latency that dominates
        // the grid-starved projections. Default-on; `ONNX_GENAI_GEMV_PIPELINE=0`
        // forces the original entry.
        //
        // Occupancy gate: the pipe entry's extra registers are a net LOSS once
        // the launch already fills the SMs many waves over (the pipe kernel's
        // lower occupancy then outweighs its latency hiding). The wide LM-head
        // projection is the only such well-occupied block-32 GEMV here (measured
        // plain 85.0 µs vs pipe 98.8 µs, -14%), so it falls back to the plain
        // entry while the grid-starved q/gate/kv projections keep the pipe entry.
        // `pipe_columns_per_block` mirrors the launch's `columns_per_block`: the
        // pipe path always takes the 256-thread (8-warp) large launch unless BOTH
        // n and k are small.
        let use_scales_f16_pipeline = self.block_size == 32
            && scales_fp16
            && matches!(selection.variant, F16GemvVariant::General)
            && !use_scales_f16_splitk
            && scales_f16_pipeline_enabled();
        let pipe_columns_per_block =
            if self.n <= GEMV_F16_SMALL_N_MAX && self.k <= GEMV_F16_SMALL_N_MAX {
                (GEMV_F16_SMALL_THREADS / 32) as usize
            } else {
                (GEMV_F16_LARGE_THREADS / 32) as usize
            };
        let use_scales_f16_pipe = use_scales_f16_pipeline
            && !scales_f16_pipe_well_occupied(
                self.n,
                pipe_columns_per_block,
                self.runtime.capabilities().multiprocessor_count(),
            );
        // Down projection grid-fill: choose columns-per-CTA (8/4/2) from the
        // device SM count so a small-N (grid-starved) down launch splits enough
        // to fill the multiprocessors, bit-identically. A developer env override
        // is honored for A/B measurement.
        let down_choice = down_columns_override().unwrap_or_else(|| {
            select_down_columns(self.n, self.runtime.capabilities().multiprocessor_count())
        });
        // Grid-fill split-K for the block!=32 int4 decode GEMV: the single-warp
        // general_bs launch under-fills the SMs on the medium/KV projections
        // (~0.5 waves), starving the latency-bound global loads. K_SPLIT warps
        // per column doubles the grid to fill the device; the wide gate_up GEMV
        // (already >3 waves) keeps the single-warp entry.
        let use_general_splitk = self.block_size != 32
            && use_general_bs_splitk(
                self.k,
                self.n,
                self.bits,
                self.runtime.capabilities().multiprocessor_count(),
            );
        let entry = if self.block_size != 32 {
            // Any non-block-32 layout uses the model-agnostic general kernel; the
            // tuned DownProjection / scales_f16 / general entries bake in the
            // block-32 lane→block mapping. `select_f16_gemv_variant` already
            // returns `General` for block_size != 32, so shape/thread selection
            // below (the `General` arm) applies unchanged. The general_bs kernel
            // dequantizes an optional asymmetric zero point per block, so it is
            // correct for both symmetric (zp==8) and asymmetric layouts.
            if use_general_splitk {
                if use_gemv_wideload(self.bits, self.block_size, self.k) {
                    // The multicol hybrid register-blocks WIDE_NC columns/warp,
                    // which lifts memory-level parallelism on the medium/large
                    // projections but collapses the launch grid on a narrow
                    // (grid-starved) projection. For those, fall back to the
                    // byte-identical single-column split-K wide entry, whose 4x
                    // larger grid fills the otherwise-idle SMs.
                    if use_gemv_splitk_multicol()
                        && !splitk_smalln_prefers_single_column(
                            self.n,
                            self.runtime.capabilities().multiprocessor_count(),
                        )
                    {
                        GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY
                    } else {
                        GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY
                    }
                } else {
                    GEMV_F16_GENERAL_BS_SPLITK_ENTRY
                }
            } else if use_gemv_wideload(self.bits, self.block_size, self.k) {
                if use_gemv_wide_multicol() {
                    if use_gemv_fp16() {
                        GEMV_F16_GENERAL_BS_WIDE_MULTICOL_FP16_ENTRY
                    } else {
                        GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY
                    }
                } else {
                    GEMV_F16_GENERAL_BS_WIDE_ENTRY
                }
            } else {
                GEMV_F16_GENERAL_BS_ENTRY
            }
        } else {
            match selection.variant {
                F16GemvVariant::DownProjection => down_choice.1,
                // The vectorized `scales_f16` kernel is compiled in two
                // specializations: the symmetric entry (`HasZp == false`) folds
                // the subtrahend to the constant fp16 8.0 with zero extra memory
                // traffic (byte-identical PTX to the pre-zero-point path), while
                // the `_zp` entry reads the per-block asymmetric zero point.
                // Symmetric weights must take the constant path so the memory-
                // bound M=1 decode GEMV does not pay for an unused per-block load.
                F16GemvVariant::General if scales_fp16 => {
                    if zero_points.is_some() {
                        // Grid-starved standalone int4 zp GEMV: when K is a whole
                        // multiple of the 256-wide step, take the split-K entry
                        // (K_SPLIT warps/column, K_SPLIT x larger grid) to fill the
                        // SMs; otherwise the plain single-warp `_zp` entry (which
                        // handles the divergent K tail).
                        if use_scales_f16_zp_splitk {
                            if scales_f16_zp_factor == GEMV_F16_SCALES_F16_ZP_SPLITK8 {
                                GEMV_F16_SCALES_F16_ZP_SPLITK8_ENTRY
                            } else {
                                GEMV_F16_SCALES_F16_ZP_SPLITK_ENTRY
                            }
                        } else if use_scales_f16_pipe {
                            GEMV_F16_SCALES_F16_ZP_PIPE_ENTRY
                        } else {
                            GEMV_F16_SCALES_F16_ZP_ENTRY
                        }
                    } else {
                        if use_scales_f16_symmetric_splitk {
                            GEMV_F16_SCALES_F16_SPLITK_ENTRY
                        } else if use_scales_f16_pipe {
                            GEMV_F16_SCALES_F16_PIPE_ENTRY
                        } else {
                            GEMV_F16_SCALES_F16_ENTRY
                        }
                    }
                }
                F16GemvVariant::General => GEMV_F16_ENTRY,
            }
        };
        // Opt-in TRT-LLM interleaved + biased dequant lever. Keying off the
        // ALREADY-selected `entry` (rather than re-deriving the shape predicates)
        // guarantees each swap is a drop-in with identical launch geometry. The
        // wide multicol and the grid-starved split-K wide entries (block!=32,
        // fp32-accum) consume offline nibble-interleaved weights so runtime
        // dequant drops both the per-block `sub.f16x2` (folded -8 bias) and the
        // `prmt.b32` activation reorder; they swap the packed pointer for the
        // cached interleaved buffer AND route to the interleaved sibling kernel.
        // Byte-identical on symmetric weights.
        //
        // The block-32 `scales_f16` fp16-accum family was evaluated (a pure
        // bias-fold, no weight interleave) and measured a NO-GO: byte-identical
        // but no decode speedup on qwen2.5-14b-int4 (that kernel is not
        // issue-slot-bound the way the fp32 wide path is), so it is deliberately
        // NOT wired here. Any other entry (narrow single-warp, fp16-accum
        // multicol, asymmetric) is likewise left untouched.
        let interleaved_entry = if entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY {
            Some(GEMV_F16_GENERAL_BS_WIDE_MULTICOL_INTERLEAVED_ENTRY)
        } else if entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY {
            Some(GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_INTERLEAVED_ENTRY)
        } else if entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY {
            Some(GEMV_F16_GENERAL_BS_SPLITK_WIDE_INTERLEAVED_ENTRY)
        } else {
            None
        };
        let orig_packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let interleave_on = interleave_dequant_enabled() && self.bits == 4 && zero_points.is_none();
        let (entry, packed_ptr) = if interleave_on && let Some(target) = interleaved_entry {
            let bytes = self.n.saturating_mul(k_blocks).saturating_mul(blob_size);
            match ensure_interleaved(&self.runtime, orig_packed_ptr, bytes) {
                Ok((iptr, warm)) => {
                    if !warm {
                        self.last_call_capture_safe.store(false, Ordering::Relaxed);
                    }
                    onnx_runtime_ep_api::record_kernel_variant_stage!(
                        "dequant",
                        "interleaved_biased",
                        "TRT-LLM interleaved+biased int4 dequant: offline nibble-interleave + \
                         folded symmetric -8 bias drops the per-block sub.f16x2 and the prmt.b32 \
                         activation reorder (byte-identical to the fp32 wide/multicol/split-K path)"
                    );
                    (target, iptr)
                }
                Err(_) => (entry, orig_packed_ptr),
            }
        } else {
            (entry, orig_packed_ptr)
        };
        // Prefetch-pipelined split-K swap: the `_pf` entries are bit-identical
        // drop-ins (same K_SPLIT geometry, ABI and accumulation order) that keep
        // several weight-word loads in flight per lane to hide the weight-load
        // latency the plain split-K loop stalls on. Default-on;
        // `ONNX_GENAI_ZP_SPLITK_PREFETCH=0` keeps the plain entry for A/B.
        let entry = if use_scales_f16_zp_splitk_pf() {
            if entry == GEMV_F16_SCALES_F16_ZP_SPLITK_ENTRY {
                GEMV_F16_SCALES_F16_ZP_SPLITK_PF_ENTRY
            } else if entry == GEMV_F16_SCALES_F16_SPLITK_ENTRY {
                GEMV_F16_SCALES_F16_SPLITK_PF_ENTRY
            } else if entry == GEMV_F16_SCALES_F16_ZP_SPLITK8_ENTRY {
                GEMV_F16_SCALES_F16_ZP_SPLITK8_PF_ENTRY
            } else {
                entry
            }
        } else {
            entry
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        // These entries narrow their fp16 epilogue through
        // `matmul_nbits_store_narrowed`, so they can write a bf16 consumer
        // buffer directly and let `run_bf16` drop its per-node staging cast.
        // The prefetch `_pf` siblings share the identical narrowing epilogue.
        let bf16_direct_capable = entry == GEMV_F16_SCALES_F16_SPLITK_ENTRY
            || entry == GEMV_F16_SCALES_F16_ZP_SPLITK_ENTRY
            || entry == GEMV_F16_SCALES_F16_SPLITK_PF_ENTRY
            || entry == GEMV_F16_SCALES_F16_ZP_SPLITK_PF_ENTRY
            || entry == GEMV_F16_SCALES_F16_ZP_SPLITK8_ENTRY
            || entry == GEMV_F16_SCALES_F16_ZP_SPLITK8_PF_ENTRY;
        let staging_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let direct_bf16_ptr = bf16_direct_capable
            .then(|| take_bf16_direct_out(staging_ptr, self.n))
            .flatten();
        let output_ptr = direct_bf16_ptr.unwrap_or(staging_ptr);
        let out_bf16_flag: i32 = direct_bf16_ptr.is_some() as i32;
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let block_size = as_i32("block_size", self.block_size)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row byte count", zp_row_bytes)?;
        let scales_fp16_flag: i32 = scales_fp16 as i32;
        let bias_post_round_flag: i32 = (self.fold_bias_post_round && bias.is_some()) as i32;
        let bits = as_i32("bits", self.bits)?;
        let (threads, columns_per_block, shared_mem_bytes) = match selection.variant {
            F16GemvVariant::DownProjection => (GEMV_F16_DOWN_THREADS, down_choice.0, 0),
            F16GemvVariant::General => {
                let threads = if self.n <= GEMV_F16_SMALL_N_MAX
                    && self.k <= GEMV_F16_SMALL_N_MAX
                    && !use_general_splitk
                {
                    GEMV_F16_SMALL_THREADS
                } else {
                    GEMV_F16_LARGE_THREADS
                };
                // Split-K assigns K_SPLIT warps per output column, so a block of
                // `threads/32` warps now covers `warps / K_SPLIT` columns and the
                // grid grows by K_SPLIT to fill the SMs. The block-32 scales_f16
                // split-K uses K_SPLIT = GEMV_F16_SCALES_F16_ZP_SPLITK; the
                // block!=32 general_bs split-K uses GENERAL_BS_SPLITK. Both force
                // the 256-thread path so `threads/32 >= K_SPLIT`.
                let columns_per_block = if use_general_splitk {
                    // Split-K covers `warps / K_SPLIT` column groups; the multicol
                    // hybrid register-blocks WIDE_NC output columns per group, so
                    // it covers that many more columns per block.
                    if entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY
                        || entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_INTERLEAVED_ENTRY
                    {
                        (threads / 32) as usize / GENERAL_BS_SPLITK_MULTICOL
                            * GEMV_F16_WIDE_MULTICOL_NC
                    } else {
                        (threads / 32) as usize / GENERAL_BS_SPLITK
                    }
                } else if use_scales_f16_splitk {
                    // The symmetric split-K entry is always factor 2; only the
                    // asymmetric one deepens on a still-starved grid.
                    let factor = if use_scales_f16_zp_splitk {
                        scales_f16_zp_factor
                    } else {
                        GEMV_F16_SCALES_F16_ZP_SPLITK
                    };
                    (threads / 32) as usize / factor
                } else if entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY
                    || entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_FP16_ENTRY
                    || entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_INTERLEAVED_ENTRY
                {
                    // Each warp emits WIDE_NC columns, so a `threads/32`-warp CTA
                    // covers `warps * WIDE_NC` output columns; the grid shrinks by
                    // WIDE_NC accordingly.
                    (threads / 32) as usize * GEMV_F16_WIDE_MULTICOL_NC
                } else {
                    (threads / 32) as usize
                };
                (threads, columns_per_block, 0)
            }
        };
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&block_size)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes)
            .arg(&scales_fp16_flag)
            .arg(&bias_post_round_flag);
        // The model-agnostic general-block-size GEMV takes one extra trailing
        // scalar (`bits`) to select the packed int4/int8 layout for any block
        // width; the tuned block-32 entries bake in their bit width and take none.
        // The general_bs split-K entry shares the same trailing `bits` ABI.
        if entry == GEMV_F16_GENERAL_BS_ENTRY
            || entry == GEMV_F16_GENERAL_BS_SPLITK_ENTRY
            || entry == GEMV_F16_GENERAL_BS_WIDE_ENTRY
            || entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_ENTRY
            || entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_ENTRY
            || entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_FP16_ENTRY
            || entry == GEMV_F16_GENERAL_BS_WIDE_MULTICOL_INTERLEAVED_ENTRY
            || entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_INTERLEAVED_ENTRY
            || entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_ENTRY
            || entry == GEMV_F16_GENERAL_BS_SPLITK_WIDE_MULTICOL_INTERLEAVED_ENTRY
        {
            builder.arg(&bits);
        }
        // The block-32 split-K entries take one extra trailing scalar selecting
        // the fp16 or bf16 narrowing store in their epilogue.
        if bf16_direct_capable {
            builder.arg(&out_bf16_flag);
        }
        // SAFETY: M=1 fp16 inputs; all tensors were dtype/shape/contiguity
        // validated above, including the optional packed per-block zero-point
        // rows. Block-32 layouts use the tuned entries; any other (power-of-two,
        // >=16) block size routes to the general_bs entry, which derives the
        // scale/zero-point block index from `block_size`. The scalar ABI is
        // shared by all these entries. Every variant uses only registers and
        // launch-time shared memory (no per-call alloc or sync), so the launch
        // is legal to record into and replay from a CUDA graph.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n.div_ceil(columns_per_block) as u32, 1, 1),
                block_dim: (threads, 1, 1),
                shared_mem_bytes,
            })
        }
        .map(|_| ())
        .map_err(|err| {
            driver_err(
                &format!("launch MatMulNBits fp16 GEMV ({})", selection.reason),
                err,
            )
        })
    }

    /// General fp16 GEMV whose input activation is RMS-normalized in-kernel
    /// (the [`GEMV_F16_SCALES_F16_RMSNORM_ENTRY`] entry). Bit-for-bit identical
    /// to the standalone `SkipSimplifiedLayerNormalization` residual output
    /// followed by the general `scales_f16` GEMV, so decode tokens are
    /// unchanged while the separate normalization launch is removed.
    #[allow(clippy::too_many_arguments)]
    fn launch_f16_gemv_rmsnorm(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        gamma: &TensorView,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        self.runtime
            .require_nvrtc_half_headers("MatMulNBits fp16 RMS-norm-prologue GEMV")?;
        if bias.is_some() {
            if self.fold_bias_post_round {
                onnx_runtime_ep_api::record_kernel_variant_stage!(
                    "bias",
                    "qkv_bias_fused",
                    "folded standalone Add(MatMulNBits, bias) into GEMV epilogue with \
                     fp16-after-round semantics fp16(fp16(acc)+bias) (token-identity preserved)"
                );
            } else {
                onnx_runtime_ep_api::record_kernel_variant_stage!(
                    "bias",
                    "bias_native",
                    "native MatMulNBits bias: single-round epilogue fp16(acc+bias)"
                );
            }
        }
        let capabilities = self.runtime.capabilities();
        let use_splitk = zero_points.is_none()
            && use_f16_symmetric_splitk(
                self.k,
                self.n,
                capabilities.multiprocessor_count(),
                capabilities.max_threads_per_block(),
            );
        let entry = if zero_points.is_some() {
            GEMV_F16_SCALES_F16_RMSNORM_ZP_ENTRY
        } else if use_splitk {
            GEMV_F16_SCALES_F16_RMSNORM_SPLITK_ENTRY
        } else {
            GEMV_F16_SCALES_F16_RMSNORM_ENTRY
        };
        let function = self
            .runtime
            .nvrtc_function(GEMV_F16_MODULE, GEMV_F16_SRC, entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let gamma_ptr = cuptr(gamma.data_ptr::<u8>() as *const c_void);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row byte count", zp_row_bytes)?;
        let bias_post_round_flag: i32 = (self.fold_bias_post_round && bias.is_some()) as i32;
        let gamma_is_half: i32 = (gamma.dtype == DataType::Float16) as i32;
        let epsilon = self.rmsnorm_epsilon;
        let threads = if self.n <= GEMV_F16_SMALL_N_MAX && self.k <= GEMV_F16_SMALL_N_MAX {
            GEMV_F16_SMALL_THREADS
        } else {
            GEMV_F16_LARGE_THREADS
        };
        let columns_per_block = (threads / 32) as usize
            / if use_splitk {
                GEMV_F16_SCALES_F16_ZP_SPLITK
            } else {
                1
            };
        let shared_mem_bytes = (self.k * std::mem::size_of::<half::f16>()) as u32;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&gamma_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes)
            .arg(&bias_post_round_flag)
            .arg(&gamma_is_half)
            .arg(&epsilon);
        // SAFETY: restricted to block-32 M=1 fp16 inputs with fp16 scales and no
        // zero_points, all dtype/shape/contiguity validated above. The kernel
        // stages the normalized activation in launch-time dynamic shared memory
        // (`K * sizeof(f16)`, bounded by the fusion's `K % 128 == 0` predicate)
        // and uses only registers, warp shuffles, and `__syncthreads` — no
        // per-call allocation or host synchronization — so it is legal to record
        // into and replay from a CUDA graph.
        // Clamp the K-sized activation stage to the device's shared-memory
        // budget: opt into >48 KB when the card allows it, and fail loudly
        // (rather than launch-crash on a smaller consumer GPU) if K exceeds even
        // the opt-in ceiling.
        self.runtime
            .configure_dynamic_shared_memory(&function, shared_mem_bytes)?;
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n.div_ceil(columns_per_block) as u32, 1, 1),
                block_dim: (threads, 1, 1),
                shared_mem_bytes,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits fp16 RMS-norm-prologue GEMV", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_int8_f32_gemv(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
    ) -> Result<()> {
        let function = self
            .runtime
            .nvrtc_function(GEMV_MODULE, GEMV_SRC, GEMV_INT8_F32_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks);
        // SAFETY: dense tensors were validated for the one-byte-per-weight
        // block-32 layout. This fixed-geometry launch uses no dynamic allocation,
        // host synchronization, or architecture-specific instructions, so it is
        // CUDA-graph-capturable and portable across supported SM versions.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n as u32, 1, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits int8 f32 GEMV", err))
    }

    /// Specialized asymmetric int4 / `block_size == 128` fp32-activation decode
    /// GEMV. The fixed layout makes `blob_size == 64` and
    /// `zp_row_bytes == ceil(k_blocks / 2)`, so neither is passed at runtime.
    #[allow(clippy::too_many_arguments)]
    fn launch_int4_f32_gemv_block128(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: &TensorView,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
    ) -> Result<()> {
        let function =
            self.runtime
                .nvrtc_function(GEMV_MODULE, GEMV_SRC, GEMV_INT4_F32_BLOCK128_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = cuptr(zero_points.data_ptr::<u8>() as *const c_void);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks);
        // SAFETY: validation guarantees the asymmetric int4 block-128 layout.
        // The fixed one-CTA-per-column launch has no allocation, synchronization,
        // or architecture-specific launch geometry, so it is capture-safe.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n as u32, 1, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits int4 f32 block-128 GEMV", err))
    }

    /// Specialized int8 / `block_size == 128` / asymmetric fp32-activation decode
    /// GEMV. Structurally selected from [`Self::launch_f32_gemv`] and bit-for-bit
    /// identical to it; see [`GEMV_INT8_F32_BLOCK128_ENTRY`] for the kernel-level
    /// rationale. Only `k`, `n`, and `k_blocks` are passed because `block_size`,
    /// `blob_size`, `zp_row_bytes`, and `bits` are all fixed by the structural
    /// dispatch (128 / 128 / `k_blocks` / 8).
    #[allow(clippy::too_many_arguments)]
    fn launch_int8_f32_gemv_block128(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
    ) -> Result<()> {
        let function =
            self.runtime
                .nvrtc_function(GEMV_MODULE, GEMV_SRC, GEMV_INT8_F32_BLOCK128_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks);
        // SAFETY: dense tensors were validated for the one-byte-per-weight
        // block-128 layout (blob_size == 128). The launch geometry (one CTA per
        // column, BLOCK_THREADS lanes, no dynamic allocation, host sync, or
        // architecture-specific instructions) matches the generic f32 GEMV, so it
        // is CUDA-graph-capturable and portable across supported SM counts/CCs.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n as u32, 1, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits int8 f32 block-128 GEMV", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_f32_gemv(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        let function = self
            .runtime
            .nvrtc_function(GEMV_MODULE, GEMV_SRC, GEMV_F32_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let block_size = as_i32("block_size", self.block_size)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row size", zp_row_bytes)?;
        let bits = as_i32("bits", self.bits)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&block_size)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes)
            .arg(&bits);
        // SAFETY: validated dense tensors cover the complete M=1 operation and
        // the scalar ABI matches `matmul_nbits_gemv_f32`.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (self.n as u32, 1, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits f32 GEMV", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_accuracy4_gemv(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
    ) -> Result<()> {
        let workspace = self
            .accuracy4_workspace
            .as_ref()
            .ok_or_else(|| error("accuracy_level=4 GEMV workspace is unavailable"))?
            .lock()
            .map_err(|_| error("accuracy_level=4 GEMV workspace lock poisoned"))?;
        let quantize_function =
            self.runtime
                .nvrtc_function(GEMV_MODULE, GEMV_SRC, QUANTIZE_ACCURACY4_ENTRY)?;
        let capabilities = self.runtime.capabilities();
        let stage64 = use_accuracy4_stage64(
            self.n,
            capabilities.multiprocessor_count(),
            capabilities.compute_capability(),
            capabilities.max_shared_memory_per_block_optin(),
        );
        let gemv_entry = if stage64 {
            GEMV_ACCURACY4_STAGE64_ENTRY
        } else {
            GEMV_ACCURACY4_ENTRY
        };
        let gemv_function = self
            .runtime
            .nvrtc_function(GEMV_MODULE, GEMV_SRC, gemv_entry)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let padded_k = as_i32("padded K", workspace.padded_k)?;

        let mut quantize_builder = self.runtime.stream().launch_builder(&quantize_function);
        quantize_builder
            .arg(&activation_ptr)
            .arg(&workspace.quantized_activation)
            .arg(&workspace.activation_scale)
            .arg(&k)
            .arg(&padded_k);
        // SAFETY: the persistent workspace covers padded_k int8 values plus one
        // f32 scale per block-32, and the scalar ABI matches the quantization
        // entry point. One warp (CUDA block) quantizes one K-block.
        unsafe {
            quantize_builder.launch(LaunchConfig {
                grid_dim: ((workspace.padded_k / 32) as u32, 1, 1),
                block_dim: (32, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map_err(|err| driver_err("launch MatMulNBits accuracy_level=4 quantization", err))?;

        let mut gemv_builder = self.runtime.stream().launch_builder(&gemv_function);
        gemv_builder
            .arg(&workspace.quantized_activation)
            .arg(&workspace.activation_scale)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks);
        // SAFETY: this path is restricted to symmetric block-32 M=1 inputs; the
        // persistent quantized activation is initialized by the preceding stream
        // launch, and the scalar ABI matches the tiled GEMV entry point.
        unsafe {
            gemv_builder.launch(LaunchConfig {
                grid_dim: (
                    self.n.div_ceil(GEMV_ACCURACY4_COLUMNS_PER_BLOCK) as u32,
                    1,
                    1,
                ),
                block_dim: (GEMV_ACCURACY4_THREADS, 1, 1),
                shared_mem_bytes: if stage64 {
                    GEMV_ACCURACY4_STAGE64_SHARED_BYTES
                } else {
                    GEMV_ACCURACY4_SHARED_BYTES
                },
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits accuracy_level=4 GEMV", err))
    }

    /// General-block-size fp32-activation accuracy_level=4 decode GEMV. Quantizes
    /// the fp32 activation to int8 ONCE per K-block into the persistent workspace
    /// (matching the tiled reference's per-block quantization), then runs a
    /// warp-per-column blockwise GEMV whose grid width is chosen from the device
    /// multiprocessor count so it fills consumer and datacenter GPUs alike. This
    /// replaces the grid-starved tiled `matmul_nbits_accuracy4` fallback for M==1
    /// int4 decode (any power-of-two block_size, symmetric or asymmetric),
    /// bit-for-bit identically, and eliminates the per-output re-quantization.
    #[allow(clippy::too_many_arguments)]
    fn launch_accuracy4_gemv_blockwise(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        let workspace = self
            .accuracy4_workspace
            .as_ref()
            .ok_or_else(|| error("accuracy_level=4 GEMV workspace is unavailable"))?
            .lock()
            .map_err(|_| error("accuracy_level=4 GEMV workspace lock poisoned"))?;
        let quantize_function = self.runtime.nvrtc_function(
            GEMV_MODULE,
            GEMV_SRC,
            QUANTIZE_ACCURACY4_BLOCKWISE_ENTRY,
        )?;
        let gemv_function =
            self.runtime
                .nvrtc_function(GEMV_MODULE, GEMV_SRC, GEMV_ACCURACY4_BLOCKWISE_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let block_size = as_i32("block_size", self.block_size)?;
        let k_blocks_arg = as_i32("K block count", k_blocks)?;
        let blob_size_arg = as_i32("block blob size", blob_size)?;
        let zp_row_bytes_arg = as_i32("zero-point row size", zp_row_bytes)?;
        let padded_k = as_i32("padded K", workspace.padded_k)?;

        let mut quantize_builder = self.runtime.stream().launch_builder(&quantize_function);
        quantize_builder
            .arg(&activation_ptr)
            .arg(&workspace.quantized_activation)
            .arg(&workspace.activation_scale)
            .arg(&k)
            .arg(&block_size)
            .arg(&padded_k);
        // SAFETY: the persistent workspace covers padded_k int8 values plus one
        // f32 scale per K-block, and the scalar ABI matches the quantization
        // entry point. One warp (CUDA block) quantizes one K-block.
        unsafe {
            quantize_builder.launch(LaunchConfig {
                grid_dim: (k_blocks as u32, 1, 1),
                block_dim: (32, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map_err(|err| {
            driver_err(
                "launch MatMulNBits accuracy_level=4 blockwise quantization",
                err,
            )
        })?;

        let warps =
            select_accuracy4_gemv_warps(self.n, self.runtime.capabilities().multiprocessor_count());
        let grid = self.n.div_ceil(warps as usize) as u32;
        let mut gemv_builder = self.runtime.stream().launch_builder(&gemv_function);
        gemv_builder
            .arg(&workspace.quantized_activation)
            .arg(&workspace.activation_scale)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&k)
            .arg(&n)
            .arg(&k_blocks_arg)
            .arg(&block_size)
            .arg(&blob_size_arg)
            .arg(&zp_row_bytes_arg);
        // SAFETY: the persistent quantized activation is initialized by the
        // preceding stream launch, the scalar ABI matches the blockwise GEMV
        // entry point, and each warp reduces exactly one output column.
        unsafe {
            gemv_builder.launch(LaunchConfig {
                grid_dim: (grid, 1, 1),
                block_dim: (warps * 32, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits accuracy_level=4 blockwise GEMV", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_accuracy4(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        let total = m.checked_mul(self.n).ok_or_else(|| {
            error(format!(
                "accuracy_level=4 output size {m} * {} overflows usize",
                self.n
            ))
        })?;
        let blocks = total.div_ceil(BLOCK_THREADS as usize).clamp(1, 65_535) as u32;
        let function =
            self.runtime
                .nvrtc_function(ACCURACY4_MODULE, ACCURACY4_SRC, ACCURACY4_ENTRY)?;
        let activation_ptr = cuptr(activation.data_ptr::<u8>() as *const c_void);
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let bias_ptr = bias
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let m = as_i32("M", m)?;
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let block_size = as_i32("block_size", self.block_size)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row size", zp_row_bytes)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&activation_ptr)
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&bias_ptr)
            .arg(&output_ptr)
            .arg(&m)
            .arg(&k)
            .arg(&n)
            .arg(&block_size)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes);
        // SAFETY: all tensors were dtype/shape/contiguity validated above and
        // the scalar ABI matches `matmul_nbits_accuracy4`.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (blocks, 1, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits accuracy_level=4", err))
    }

    #[allow(clippy::too_many_arguments)]
    /// Dequantize the int4/int8 weights to `[K, N]` fp16 and run the GEMM on
    /// cuBLASLt tensor cores.
    ///
    /// Returns `Ok(false)` when this call is not eligible, so the caller falls
    /// through to Marlin / the tiled GEMM under the usual fallback contract.
    #[allow(clippy::too_many_arguments)]
    fn try_dequant_f16_cublas_gemm(
        &self,
        activation: &TensorView,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        bias: Option<&TensorView>,
        output: &mut TensorMut,
        m: usize,
        bias_row_stride: usize,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
        workspace: Option<WorkspaceView>,
    ) -> Result<bool> {
        // cuBLASLt's bias epilogue adds one value per output column into the f32
        // accumulator before rounding. That is exactly `bias_post_round == 0`
        // with a broadcast bias; a per-token residual (row stride N) or a folded
        // standalone `Add` (which must round the accumulator *first*) would be a
        // different computation, so both stay on the existing paths.
        if bias.is_some() && (bias_row_stride != 0 || self.fold_bias_post_round) {
            return Ok(false);
        }
        let Some(block_shift) = self.dequant_f16_block_shift() else {
            return Ok(false);
        };
        let weight_bytes = self
            .k
            .checked_mul(self.n)
            .and_then(|elems| elems.checked_mul(2))
            .ok_or_else(|| error("dequantized f16 weight size overflowed"))?;
        if weight_bytes > dequant_f16_gemm_max_scratch_bytes() {
            return Ok(false);
        }

        // A persistent pooled scratch, not a per-call allocation. Prefill runs
        // this hundreds of times per generation, and the VMM arena charges
        // `cuMemCreate`/`cuMemSetAccess`/`cuMemUnmap` for every map and unmap of
        // a buffer this large — enough allocator time to swamp the GEMM the
        // dequantize exists to feed. Slot 5 is unused by the Marlin fused paths.
        let (weight, _warm) = self.marlin_repack_cache.ensure_scratch(5, weight_bytes)?;
        let result = self
            .launch_dequant_f16(
                packed,
                scales,
                scales_fp16,
                zero_points,
                weight,
                k_blocks,
                blob_size,
                zp_row_bytes,
                block_shift,
            )
            .and_then(|()| {
                let params = self.dequant_f16_gemm_ex(
                    cuptr(activation.data_ptr::<u8>() as *const c_void),
                    weight,
                    cuptr(output.data_ptr_mut::<u8>() as *const c_void),
                    m,
                    bias.map(|bias| cuptr(bias.data_ptr::<u8>() as *const c_void)),
                );
                // SAFETY: A is the freshly written [N, K] fp16 dequantized
                // weight, B the validated [M, K] fp16 activation, and C the op's
                // [M, N] fp16 output, which aliases neither. The workspace and
                // stream outlive the call.
                unsafe {
                    blas::governed_gemm_ex(
                        self.runtime.blas(),
                        self.runtime.stream_ptr(),
                        &params,
                        workspace,
                        "MatMulNBits",
                    )
                }
            });

        // The scratch stays pooled for the next call; nothing to release here.
        result.map(|()| true)
    }

    /// The one place the dequantize + fp16 GEMM's column-major mapping lives, so
    /// the launch and the declared workspace requirement cannot drift apart.
    ///
    /// cuBLAS is column-major, and the row-major product `C[M, N] = A[M, K] ·
    /// W[K, N]` is the column-major product `Cᶜ[N, M] = Wᵀ · Aᶜ`. The
    /// dequantized weight is `[N, K]` row-major, i.e. `K × N` column-major, so
    /// transposing it gives the `N × K` first operand; the `[M, K]` row-major
    /// activation is already `K × M` column-major and needs no transpose. The
    /// epilogue bias then indexes the `m = N` axis, which is the output channel
    /// a MatMulNBits bias is defined over.
    fn dequant_f16_gemm_ex(
        &self,
        activation: CUdeviceptr,
        weight_nk: CUdeviceptr,
        output: CUdeviceptr,
        m: usize,
        bias: Option<CUdeviceptr>,
    ) -> GemmEx {
        GemmEx {
            dtype: GemmDtype::F16,
            transa: true,
            transb: false,
            m: self.n,
            n: m,
            k: self.k,
            alpha: 1.0,
            beta: 0.0,
            a: weight_nk,
            lda: self.k,
            b: activation,
            ldb: self.k,
            c: output,
            ldc: self.n,
            epilogue: bias.map(|bias| GemmEpilogue {
                kind: GemmEpilogueKind::Bias,
                bias,
            }),
        }
    }

    /// Whether this node's quantization layout is expressible by the packed
    /// eight-nibble word the fp16 dequant kernel reads.
    fn dequant_f16_block_shift(&self) -> Option<i32> {
        if self.bits != 4 || !self.k.is_multiple_of(8) {
            return None;
        }
        if !self.block_size.is_multiple_of(8) || !self.block_size.is_power_of_two() {
            return None;
        }
        Some(self.block_size.trailing_zeros() as i32)
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_dequant_f16(
        &self,
        packed: &TensorView,
        scales: &TensorView,
        scales_fp16: bool,
        zero_points: Option<&TensorView>,
        weight: cudarc::driver::sys::CUdeviceptr,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
        block_shift: i32,
    ) -> Result<()> {
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let k = as_i32("K", self.k)?;
        let k_blocks_i = as_i32("K block count", k_blocks)?;
        let blob_size_i = as_i32("block blob size", blob_size)?;
        let zp_row_bytes_i = as_i32("zero-point row size", zp_row_bytes)?;
        let scales_fp16_flag: i32 = scales_fp16 as i32;
        let words = self.k / 8;
        let grid_x = words.div_ceil(BLOCK_THREADS as usize) as u32;
        let grid_y = as_i32("N", self.n)? as u32;
        let function =
            self.runtime
                .nvrtc_function(DEQUANT_F16_MODULE, DEQUANT_F16_SRC, DEQUANT_F16_ENTRY)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&weight)
            .arg(&k)
            .arg(&k_blocks_i)
            .arg(&blob_size_i)
            .arg(&zp_row_bytes_i)
            .arg(&block_shift)
            .arg(&scales_fp16_flag);
        // SAFETY: argument order/types match the CUDA entry point; all device
        // buffers were shape-validated and `weight` has N*K fp16 elements.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (grid_x.max(1), grid_y, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits f16 dequant", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_dequant(
        &self,
        packed: &TensorView,
        scales: &TensorView,
        zero_points: Option<&TensorView>,
        group_indices: Option<&TensorView>,
        weight: cudarc::driver::sys::CUdeviceptr,
        k_blocks: usize,
        blob_size: usize,
        zp_row_bytes: usize,
    ) -> Result<()> {
        let packed_ptr = cuptr(packed.data_ptr::<u8>() as *const c_void);
        let scales_ptr = cuptr(scales.data_ptr::<u8>() as *const c_void);
        let zero_points_ptr = zero_points
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let group_indices_ptr = group_indices
            .map(|tensor| cuptr(tensor.data_ptr::<u8>() as *const c_void))
            .unwrap_or(0);
        let k = as_i32("K", self.k)?;
        let n = as_i32("N", self.n)?;
        let block_size = as_i32("block_size", self.block_size)?;
        let k_blocks = as_i32("K block count", k_blocks)?;
        let blob_size = as_i32("block blob size", blob_size)?;
        let zp_row_bytes = as_i32("zero-point row size", zp_row_bytes)?;
        let bits = as_i32("bits", self.bits)?;
        let total = self.k * self.n;
        let blocks = total.div_ceil(BLOCK_THREADS as usize).clamp(1, 65_535) as u32;
        let function = self
            .runtime
            .nvrtc_function(DEQUANT_MODULE, DEQUANT_SRC, DEQUANT_ENTRY)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&packed_ptr)
            .arg(&scales_ptr)
            .arg(&zero_points_ptr)
            .arg(&group_indices_ptr)
            .arg(&weight)
            .arg(&k)
            .arg(&n)
            .arg(&block_size)
            .arg(&k_blocks)
            .arg(&blob_size)
            .arg(&zp_row_bytes)
            .arg(&bits);
        // SAFETY: argument order/types match the CUDA entry point; all device
        // buffers were shape-validated and `weight` has K*N f32 elements.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (blocks, 1, 1),
                block_dim: (BLOCK_THREADS, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map(|_| ())
        .map_err(|err| driver_err("launch MatMulNBits dequant", err))
    }
}

impl Kernel for MatMulNBitsKernel {
    fn set_constant_inputs(&mut self, constant_inputs: &[bool]) {
        for (index, is_constant) in self.constant_inputs.iter_mut().enumerate() {
            *is_constant = constant_inputs.get(index).copied().unwrap_or(false);
        }
    }

    fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.run(inputs, outputs, None)
    }

    fn workspace_requirement(&self, inputs: &[TensorMetadata<'_>]) -> Result<WorkspaceRequirement> {
        self.workspace_requirement_for(inputs)
    }

    fn execute_with_workspace(
        &self,
        inputs: &[TensorView],
        outputs: &mut [TensorMut],
        workspace: Option<WorkspaceView>,
    ) -> Result<()> {
        self.run(inputs, outputs, workspace)
    }

    fn supports_strided_input(&self, _input_idx: usize) -> bool {
        false
    }

    fn device_graph_resources(&self) -> Vec<DeviceGraphResource> {
        let mut resources = self.marlin_repack_cache.device_graph_resources();
        if let Some(workspace) = &self.accuracy4_workspace
            && let Ok(workspace) = workspace.lock()
        {
            resources.push(workspace.device_graph_resource());
        }
        if let Ok(scratch) = self.bf16_scratch.lock()
            && let Some(resource) = scratch.device_graph_resource()
        {
            resources.push(resource);
        }
        if let Ok(cache) = self.bf16_const_cache.lock()
            && let Some(resource) = cache.device_graph_resource()
        {
            resources.push(resource);
        }
        resources
    }

    fn capture_support(&self) -> onnx_runtime_ep_api::CaptureSupport {
        // The m=1 no-g_idx GEMV uses only launch-time shared memory and a
        // shape-fixed persistent accuracy-4 activation workspace; it performs no
        // per-call allocation, D2H, or synchronization. The direct fp16 GEMV is
        // likewise capture-safe: fixed grid/block geometry from the shape
        // signature and register/launch-time-shared scratch.
        //
        // The opt-in Marlin M>1 tensor-core GEMM is ALSO capture-safe once its
        // weights are repacked: its launch grid is a pure function of (M, N) and,
        // on a warm repack-cache hit, the call performs no allocation, D2H, or
        // synchronization. The dispatch records this by storing the cache-warm
        // flag into `last_call_capture_safe`, so a cold (repacking) first call is
        // reported unsupported and only warm replays advertise support — which is
        // exactly what unlocks capture-stable speculative verification at M>1.
        //
        // The portable (non-Marlin) fp16 prefill GEMM remains conservatively
        // unadvertised because variable-M prefill is outside the persistent
        // decode graph and lacks replay coverage; f32 prefill scratch and g_idx
        // validation are also non-capturable.
        if self.last_call_capture_safe.load(Ordering::Relaxed) {
            onnx_runtime_ep_api::CaptureSupport::Supported
        } else {
            onnx_runtime_ep_api::CaptureSupport::unsupported(
                "requires M==1 decode GEMV without group_indices, or a warm-cache Marlin M>1 GEMM; a cold Marlin repack and portable prefill are outside the advertised capture contract and group_indices validation reads D2H",
            )
        }
    }
}

fn optional_input<'a>(inputs: &'a [TensorView<'a>], index: usize) -> Option<&'a TensorView<'a>> {
    inputs.get(index).filter(|input| !input.is_absent())
}

fn required_positive_attr(node: &Node, name: &str) -> Result<usize> {
    let value = optional_int_attr(node, name)?
        .ok_or_else(|| error(format!("missing required integer attribute '{name}'")))?;
    if value <= 0 {
        return Err(error(format!(
            "attribute '{name}' must be positive, got {value}"
        )));
    }
    Ok(value as usize)
}

fn optional_int_attr(node: &Node, name: &str) -> Result<Option<i64>> {
    match node.attr(name) {
        Some(attribute) => attribute
            .as_int()
            .map(Some)
            .ok_or_else(|| error(format!("attribute '{name}' must be an integer"))),
        None => Ok(None),
    }
}

fn require_dtype(name: &str, got: DataType, expected: DataType) -> Result<()> {
    if got != expected {
        return Err(error(format!(
            "{name} must have dtype {expected:?}, got {got:?}"
        )));
    }
    Ok(())
}

// The RMS-norm prologue accepts an fp16 OR fp32 gamma. Gamma is only a final
// multiplicand (never in the fp32 variance accumulation), so an fp32 gamma is
// numerically safe and lets fp32-gamma exports (e.g. Phi-4-mini) fuse. The
// fused kernels branch on `gamma_is_half` to read gamma at full precision.
fn require_gamma_dtype(got: DataType) -> Result<()> {
    if got != DataType::Float16 && got != DataType::Float32 {
        return Err(error(format!(
            "gamma must have dtype Float16 or Float, got {got:?}"
        )));
    }
    Ok(())
}

fn require_shape(name: &str, got: &[usize], expected: &[usize]) -> Result<()> {
    if got != expected {
        return Err(error(format!(
            "{name} must have shape {expected:?}, got {got:?}"
        )));
    }
    Ok(())
}

fn require_flat_or_matrix_shape(
    name: &str,
    got: &[usize],
    rows: usize,
    columns: usize,
) -> Result<()> {
    if got != [rows * columns] && got != [rows, columns] {
        return Err(error(format!(
            "{name} must have shape [{}] or [{rows}, {columns}], got {got:?}",
            rows * columns
        )));
    }
    Ok(())
}

fn as_i32(name: &str, value: usize) -> Result<i32> {
    i32::try_from(value).map_err(|_| error(format!("{name}={value} exceeds i32")))
}

fn error(message: impl Into<String>) -> EpError {
    EpError::KernelFailed(format!("cuda_ep MatMulNBits: {}", message.into()))
}

#[cfg(test)]
mod tests {
    use half::f16;

    use onnx_runtime_ep_api::{DevicePtr, DevicePtrMut, TensorMut, TensorView};
    use onnx_runtime_ir::{DataType, DeviceId};

    use super::*;

    #[test]
    fn marlin_repack_requires_constant_weight_inputs() {
        let mut constant_inputs = [false; 8];
        assert!(!marlin_weight_inputs_are_constant(&constant_inputs, false));
        constant_inputs[1] = true;
        assert!(marlin_weight_inputs_are_constant(&constant_inputs, false));

        assert!(!marlin_weight_inputs_are_constant(&constant_inputs, true));
        constant_inputs[3] = true;
        assert!(marlin_weight_inputs_are_constant(&constant_inputs, true));
    }

    /// Guards the `ONNX_GENAI_INTERLEAVE_DEQUANT` / `ONNX_GENAI_GEMV_PIPELINE`
    /// levers, which the interleaved-dequant byte-identity test flips by writing
    /// the PROCESS environment.
    ///
    /// A plain mutex is not enough here, and used to be the bug: it only excludes
    /// other lock *holders*, while an env var is visible to every thread in the
    /// binary. Any parity test running concurrently would silently pick up the
    /// lever, route through `ensure_interleaved`, allocate the interleaved
    /// weights on first sight and therefore report that call capture-UNSAFE —
    /// failing an assertion about a kernel it never meant to exercise, at a
    /// timing that depended on the harness's thread interleaving.
    ///
    /// So the writer takes the exclusive side and every helper that depends on
    /// the levers being at their default (OFF) takes the shared side.
    static INTERLEAVE_TEST_ENV_LOCK: std::sync::OnceLock<std::sync::RwLock<()>> =
        std::sync::OnceLock::new();

    /// Exclusive guard that clears the dispatch levers when it drops.
    ///
    /// Restoring the environment on the normal path only is not enough: these
    /// helpers `unwrap()` their kernel runs, so a failing assertion unwinds past
    /// the cleanup and leaves the lever set. The `RwLock` is then poisoned, and
    /// readers — which recover with `into_inner` rather than cascade the
    /// failure — would run with a lever nobody asked for, turning one real
    /// failure into a run of unrelated ones. Clearing from `Drop` makes the
    /// restore unwind-safe.
    struct LeverEnvGuard(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);

    impl LeverEnvGuard {
        fn acquire() -> Self {
            Self(
                INTERLEAVE_TEST_ENV_LOCK
                    .get_or_init(Default::default)
                    .write()
                    .unwrap_or_else(|e| e.into_inner()),
            )
        }
    }

    impl Drop for LeverEnvGuard {
        fn drop(&mut self) {
            // SAFETY: still inside the exclusive section, so no other thread is
            // reading the environment concurrently.
            unsafe {
                std::env::remove_var("ONNX_GENAI_INTERLEAVE_DEQUANT");
                std::env::remove_var("ONNX_GENAI_GENERAL_SPLITK");
                std::env::remove_var("ONNX_GENAI_GEMV_PIPELINE");
                std::env::remove_var("ONNX_GENAI_GATEUP_VEC");
                std::env::remove_var("ONNX_GENAI_GATEUP_OCC");
            }
        }
    }

    /// Shared guard for a test that requires the dispatch levers to be OFF.
    fn default_levers_guard() -> std::sync::RwLockReadGuard<'static, ()> {
        INTERLEAVE_TEST_ENV_LOCK
            .get_or_init(Default::default)
            .read()
            .unwrap_or_else(|e| e.into_inner())
    }

    // Qwen2.5-0.5B down-projection shape (K=intermediate, N=hidden). Used as a
    // test fixture for the tall-skinny down variant and, transposed, as the
    // gate/up shape — the runtime code never keys on these values.
    const QWEN_DOWN_K: usize = 4864;
    const QWEN_DOWN_N: usize = 896;
    const STAGED_DOWN_REFERENCE_ENTRY: &str =
        "matmul_nbits_gemv_f16_scales_f16_down_staged_reference";
    const STAGED_DOWN_REFERENCE_SRC: &str = r#"
extern "C" __global__ void matmul_nbits_gemv_f16_scales_f16_down_staged_reference(
    const __half* __restrict__ activation,
    const unsigned char* __restrict__ packed,
    const void* __restrict__ scales_raw,
    const unsigned char* __restrict__ zero_points,
    const __half* __restrict__ bias,
    __half* __restrict__ output,
    const int k,
    const int n,
    const int block_size,
    const int k_blocks,
    const int blob_size,
    const int zp_row_bytes,
    const int scales_fp16,
    const int bias_post_round)
{
    (void)block_size;
    (void)zero_points;
    (void)zp_row_bytes;
    (void)scales_fp16;
    extern __shared__ uint4 activation_shared[];
    __shared__ float warp_sums[8][8];
    const __half* __restrict__ scales =
        reinterpret_cast<const __half*>(scales_raw);
    const int tid = (int)threadIdx.x;
    const int lane = tid & 31;
    const int warp = tid >> 5;
    const int column_base = (int)blockIdx.x * 8;

    for (int vector = tid; vector * 8 < k; vector += (int)blockDim.x) {
        activation_shared[vector] =
            permute_activation_f16x8(activation + vector * 8);
    }
    __syncthreads();

    float values[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
    for (int block = tid; block < k_blocks; block += (int)blockDim.x) {
        const uint4 activation0 = activation_shared[block * 4];
        const uint4 activation1 = activation_shared[block * 4 + 1];
        const uint4 activation2 = activation_shared[block * 4 + 2];
        const uint4 activation3 = activation_shared[block * 4 + 3];
#pragma unroll
        for (int tile_column = 0; tile_column < 8; ++tile_column) {
            const int column = column_base + tile_column;
            if (column < n) {
                const long packed_start =
                    ((long)column * k_blocks + block) * blob_size;
                const uint4 packed_weights =
                    *reinterpret_cast<const uint4*>(packed + packed_start);
                const __half scale = scales[(long)column * k_blocks + block];
                values[tile_column] += dot_int4x32_f16_permuted_scaled(
                    packed_weights,
                    activation0,
                    activation1,
                    activation2,
                    activation3,
                    scale);
            }
        }
    }

#pragma unroll
    for (int tile_column = 0; tile_column < 8; ++tile_column) {
        const float value = warp_sum(values[tile_column]);
        if (lane == 0) {
            warp_sums[warp][tile_column] = value;
        }
    }
    __syncthreads();

    if (warp == 0 && lane < 8) {
        const int column = column_base + lane;
        float value = warp_sums[0][lane];
        value += warp_sums[1][lane];
        value += warp_sums[2][lane];
        value += warp_sums[3][lane];
        value += warp_sums[4][lane];
        value += warp_sums[5][lane];
        value += warp_sums[6][lane];
        value += warp_sums[7][lane];
        output[column] = fold_bias_f16(value, bias, column, bias_post_round);
    }
}
"#;

    fn runtime() -> Option<Arc<CudaRuntime>> {
        crate::test_support::maybe_runtime()
    }

    fn as_bytes<T: Copy>(values: &[T]) -> &[u8] {
        // SAFETY: reinterpreting a POD slice as raw bytes for a host->device copy.
        unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
        }
    }

    fn as_bytes_mut<T: Copy>(values: &mut [T]) -> &mut [u8] {
        // SAFETY: reinterpreting a POD slice as raw bytes for a device->host copy.
        unsafe {
            std::slice::from_raw_parts_mut(
                values.as_mut_ptr().cast::<u8>(),
                std::mem::size_of_val(values),
            )
        }
    }

    /// Apples-to-apples wall-clock comparison of the Marlin M>1 tensor-core GEMM
    /// against the portable tiled CUDA-core GEMM through the real op, across a
    /// sweep of M at a production projection shape. Prints median kernel wall per
    /// path; this is the measurement that quantifies the M=1→M=2 cliff collapse.
    /// Ignored (perf, needs a dedicated idle SM80+ GPU).
    #[test]
    #[ignore = "perf microbench; requires a dedicated idle SM80+ CUDA device"]
    fn marlin_m_gt_1_op_wall_vs_tiled() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping Marlin M>1 wall bench: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("marlin_m_gt_1_wall")
            .is_err()
            || !marlin_gemm::device_supports_marlin(runtime.capabilities().compute_capability())
        {
            eprintln!("skipping Marlin M>1 wall bench: headers unavailable or pre-SM80");
            return;
        }

        let k = 5120usize;
        let n = 13824usize;
        let block_size = 128usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);

        let mut state = 0xcafe_f00d_1234_5678_u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let max_m = 128usize;
        let mut activation_f16 = vec![f16::ZERO; max_m * k];
        for h in activation_f16.iter_mut() {
            *h = f16::from_f32(next());
        }
        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for pair in 0..blob_size {
                    let low = quant[col * k + block * block_size + pair * 2] & 15;
                    let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                    packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                }
            }
        }
        let mut zp_packed = vec![0u8; n * zp_row_bytes];
        for byte in zp_packed.iter_mut() {
            *byte = ((next() * 0.5 + 0.5) * 255.0) as u8;
        }
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        for h in scale_f16.iter_mut() {
            *h = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
        }

        let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scale_f16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zp_packed.len()).unwrap();
        let output_dev = runtime.alloc_raw(max_m * n * 2).unwrap();
        // SAFETY: buffers sized to their sources.
        unsafe {
            runtime
                .htod(as_bytes(&activation_f16), activation_dev)
                .unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            runtime.htod(&zp_packed, zp_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        let time_path = |kernel: &MatMulNBitsKernel, m: usize| -> f64 {
            let a_shape = [m, k];
            let a_strides = [k as i64, 1];
            let y_shape = [m, n];
            let y_strides = [n as i64, 1];
            let inputs = vec![
                TensorView::new(
                    device_ptr(activation_dev),
                    DataType::Float16,
                    &a_shape,
                    &a_strides,
                    device,
                ),
                TensorView::new(
                    device_ptr(packed_dev),
                    DataType::Uint8,
                    &b_shape,
                    &b_strides,
                    device,
                ),
                TensorView::new(
                    device_ptr(scales_dev),
                    DataType::Float16,
                    &scales_shape,
                    &scales_strides,
                    device,
                ),
                TensorView::new(
                    device_ptr(zp_dev),
                    DataType::Uint8,
                    &zp_shape,
                    &zp_strides,
                    device,
                ),
            ];
            let run = || {
                let mut outputs = [TensorMut::new(
                    device_ptr_mut(output_dev),
                    DataType::Float16,
                    &y_shape,
                    &y_strides,
                    device,
                )];
                kernel.run(&inputs, &mut outputs, None).unwrap();
            };
            // Warm up (NVRTC compile, repack cache fill).
            run();
            runtime.synchronize().unwrap();
            let iters = 30;
            let mut samples = Vec::with_capacity(iters);
            for _ in 0..iters {
                let start = std::time::Instant::now();
                run();
                runtime.synchronize().unwrap();
                samples.push(start.elapsed().as_secs_f64() * 1e6);
            }
            samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
            samples[samples.len() / 2]
        };

        eprintln!("Marlin M>1 wall vs tiled @ K={k} N={n} block={block_size} (median us):");
        eprintln!("  M     tiled_us   marlin_us   speedup");
        for &m in &[1usize, 2, 4, 8, 16, 32, 64, 128] {
            // SAFETY: serial ignored bench; flag toggling is race-free here.
            // Marlin M>1 is default-ON, so the tiled arm opts out explicitly.
            unsafe {
                std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "0");
            }
            let tiled = time_path(&kernel, m);
            unsafe {
                std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "1");
            }
            let marlin = time_path(&kernel, m);
            let marlin_used = m > 1;
            eprintln!(
                "  {m:<5} {tiled:>8.1}   {marlin:>8.1}   {:>6.2}x{}",
                tiled / marlin,
                if marlin_used {
                    ""
                } else {
                    " (M=1 stays on GEMV)"
                }
            );
        }
        // SAFETY: clear the flag so it cannot leak into other tests.
        unsafe {
            std::env::remove_var("ONNX_GENAI_MARLIN_M_GT_1");
        }

        // SAFETY: every pointer came from this runtime's alloc_raw, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }
    }

    /// Parity of the fused RMS-norm + Marlin M>1 path against the already-trusted
    /// fused RMS-norm + tiled GEMM. Both share the identical `launch_rmsnorm_prefill`
    /// staging, so the residual isolates the tensor-core GEMM's reordered
    /// accumulation. Drives the real op: flag off → tiled reference, flag on →
    /// Marlin; compares within the relayout tolerance.
    #[test]
    #[ignore = "requires an SM80+ CUDA device"]
    fn marlin_m_gt_1_rmsnorm_op_parity() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping Marlin M>1 rmsnorm parity: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("marlin_m_gt_1_rmsnorm")
            .is_err()
            || !marlin_gemm::device_supports_marlin(runtime.capabilities().compute_capability())
        {
            eprintln!("skipping Marlin M>1 rmsnorm parity: headers unavailable or pre-SM80");
            return;
        }

        let m = 8usize;
        let k = 2048usize;
        let n = 64usize;
        let block_size = 128usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);

        let mut state = 0x0bad_c0de_feed_face_u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation = vec![f16::ZERO; m * k];
        for h in activation.iter_mut() {
            *h = f16::from_f32(next());
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for byte in packed.iter_mut() {
            *byte = ((next() * 0.5 + 0.5) * 255.0) as u8;
        }
        let mut zp_packed = vec![0u8; n * zp_row_bytes];
        for byte in zp_packed.iter_mut() {
            *byte = ((next() * 0.5 + 0.5) * 255.0) as u8;
        }
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        for h in scale_f16.iter_mut() {
            *h = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
        }
        let mut gamma = vec![f16::ZERO; k];
        for h in gamma.iter_mut() {
            *h = f16::from_f32(0.5 + 0.5 * (next() * 0.5 + 0.5));
        }

        let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scale_f16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zp_packed.len()).unwrap();
        let gamma_dev = runtime.alloc_raw(gamma.len() * 2).unwrap();
        let output_dev = runtime.alloc_raw(m * n * 2).unwrap();
        // SAFETY: buffers sized to their sources.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            runtime.htod(&zp_packed, zp_dev).unwrap();
            runtime.htod(as_bytes(&gamma), gamma_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let gamma_shape = [k];
        let gamma_strides = [1i64];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];

        // Slots: 3=zero_points, 4=g_idx (absent), 5=bias (absent), 6=gamma.
        let inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
            TensorView::absent(DataType::Int32),
            TensorView::absent(DataType::Float16),
            TensorView::new(
                device_ptr(gamma_dev),
                DataType::Float16,
                &gamma_shape,
                &gamma_strides,
                device,
            ),
        ];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: true,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        let run = |want_marlin: bool| -> Vec<f16> {
            // SAFETY: serial ignored GPU test; flag toggling is race-free here.
            unsafe {
                if want_marlin {
                    std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "1");
                } else {
                    // Marlin M>1 is default-ON, so the tiled arm must opt out
                    // explicitly; unsetting the variable would select Marlin.
                    std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "0");
                }
            }
            let mut outputs = [TensorMut::new(
                device_ptr_mut(output_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            )];
            kernel.run(&inputs, &mut outputs, None).unwrap();
            runtime.synchronize().unwrap();
            let mut got = vec![f16::ZERO; m * n];
            // SAFETY: `output_dev` holds `m * n` fp16 values.
            unsafe {
                runtime.dtoh(as_bytes_mut(&mut got), output_dev).unwrap();
            }
            got
        };

        let tiled = run(false);
        let marlin = run(true);
        // SAFETY: reset the flag so it cannot leak into other tests.
        unsafe {
            std::env::remove_var("ONNX_GENAI_MARLIN_M_GT_1");
        }

        // SAFETY: every pointer came from this runtime's alloc_raw, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(gamma_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut max_out = 0.0f32;
        for (mv, tv) in marlin.iter().zip(tiled.iter()) {
            let mf = mv.to_f32();
            let tf = tv.to_f32();
            assert!(mf.is_finite(), "Marlin rmsnorm output must be finite");
            worst_abs = worst_abs.max((mf - tf).abs());
            max_out = max_out.max(tf.abs());
        }
        let tol = 2e-2 * max_out.max(1e-3);
        eprintln!(
            "Marlin M>1 rmsnorm parity: worst_abs={worst_abs:.5}, max_out={max_out:.5}, tol={tol:.5}"
        );
        assert!(
            worst_abs <= tol,
            "fused rmsnorm Marlin output diverges from tiled: worst_abs={worst_abs} > tol={tol}"
        );
    }

    /// Gate/up SwiGLU MLP fusion parity + capture-safety for the Marlin M>1 path.
    /// Drives the real fused op (gate_up_swiglu = true) with the flag off (tiled
    /// two-GEMM + SiluMul reference) then on (paired Marlin GEMMs + the identical
    /// SiluMul), and asserts the outputs match within the relayout tolerance.
    /// Also checks the capture-safety contract on the plain (no-gamma) variant:
    /// cold call allocates pooled weights/scratch and is NOT capture-safe; a warm
    /// replay reuses them and IS capture-safe with byte-identical output.
    fn run_marlin_gate_up_parity(with_gamma: bool, decomposed: bool, check_capture: bool) {
        let Some(runtime) = runtime() else {
            eprintln!("skipping Marlin gate/up parity: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("marlin_gate_up")
            .is_err()
            || !marlin_gemm::device_supports_marlin(runtime.capabilities().compute_capability())
        {
            eprintln!("skipping Marlin gate/up parity: headers unavailable or pre-SM80");
            return;
        }

        let m = 8usize;
        let k = 1024usize;
        let n = 256usize;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = (k_blocks * 4).div_ceil(8);

        let mut state = 0xa5a5_1234_dead_beef_u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation = vec![f16::ZERO; m * k];
        for h in activation.iter_mut() {
            *h = f16::from_f32(next() * 0.5);
        }
        let mut make_weights = |scale: f32| {
            let mut packed = vec![0u8; n * k_blocks * blob_size];
            for byte in packed.iter_mut() {
                *byte = ((next() * 0.5 + 0.5) * 255.0) as u8;
            }
            let mut scales = vec![f16::ZERO; n * k_blocks];
            for h in scales.iter_mut() {
                *h = f16::from_f32(scale * (0.5 + 0.5 * (next() * 0.5 + 0.5)));
            }
            let mut zp = vec![0u8; n * zp_row_bytes];
            for byte in zp.iter_mut() {
                *byte = ((next() * 0.5 + 0.5) * 255.0) as u8;
            }
            (packed, scales, zp)
        };
        // Modest weight magnitudes so silu stays in a well-conditioned range.
        let (packed_gate, scales_gate, zp_gate) = make_weights(0.02);
        let (packed_up, scales_up, zp_up) = make_weights(0.02);
        let mut gamma = vec![f16::ZERO; k];
        for h in gamma.iter_mut() {
            *h = f16::from_f32(0.5 + 0.5 * (next() * 0.5 + 0.5));
        }

        let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
        let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
        let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
        let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
        let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
        let zp_gate_dev = runtime.alloc_raw(zp_gate.len()).unwrap();
        let zp_up_dev = runtime.alloc_raw(zp_up.len()).unwrap();
        let gamma_dev = runtime.alloc_raw(gamma.len() * 2).unwrap();
        let output_dev = runtime.alloc_raw(m * n * 2).unwrap();
        // SAFETY: buffers sized to their sources.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed_gate, packed_gate_dev).unwrap();
            runtime
                .htod(as_bytes(&scales_gate), scales_gate_dev)
                .unwrap();
            runtime.htod(&packed_up, packed_up_dev).unwrap();
            runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
            runtime.htod(&zp_gate, zp_gate_dev).unwrap();
            runtime.htod(&zp_up, zp_up_dev).unwrap();
            runtime.htod(as_bytes(&gamma), gamma_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let gamma_shape = [k];
        let gamma_strides = [1i64];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];

        // [x, W_gate, scales_gate, W_up, scales_up, gamma@5, zp_gate@6, zp_up@7]
        let mut inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_gate_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_gate_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_up_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_up_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
        ];
        if with_gamma {
            inputs.push(TensorView::new(
                device_ptr(gamma_dev),
                DataType::Float16,
                &gamma_shape,
                &gamma_strides,
                device,
            ));
        } else {
            inputs.push(TensorView::absent(DataType::Float16));
        }
        inputs.push(TensorView::new(
            device_ptr(zp_gate_dev),
            DataType::Uint8,
            &zp_shape,
            &zp_strides,
            device,
        ));
        inputs.push(TensorView::new(
            device_ptr(zp_up_dev),
            DataType::Uint8,
            &zp_shape,
            &zp_strides,
            device,
        ));

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: true,
            decomposed_silu: decomposed,
            rmsnorm_prologue: with_gamma,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        let run = |want_marlin: bool| -> Vec<f16> {
            // SAFETY: serial ignored GPU test; flag toggling is race-free here.
            unsafe {
                if want_marlin {
                    std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "1");
                } else {
                    // Marlin M>1 is default-ON, so the tiled arm must opt out
                    // explicitly; unsetting the variable would select Marlin.
                    std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "0");
                }
            }
            let mut outputs = [TensorMut::new(
                device_ptr_mut(output_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            )];
            kernel.run(&inputs, &mut outputs, None).unwrap();
            runtime.synchronize().unwrap();
            let mut got = vec![f16::ZERO; m * n];
            // SAFETY: `output_dev` holds `m * n` fp16 values.
            unsafe {
                runtime.dtoh(as_bytes_mut(&mut got), output_dev).unwrap();
            }
            got
        };

        let tiled = run(false);
        let marlin_cold = run(true);
        let cold_safe = kernel.last_call_capture_safe.load(Ordering::Relaxed);
        let marlin_warm = run(true);
        let warm_safe = kernel.last_call_capture_safe.load(Ordering::Relaxed);
        // SAFETY: clear the flag so it cannot leak into other tests.
        unsafe {
            std::env::remove_var("ONNX_GENAI_MARLIN_M_GT_1");
        }

        // SAFETY: every pointer came from this runtime's alloc_raw, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_gate_dev).unwrap();
            runtime.free_raw(scales_gate_dev).unwrap();
            runtime.free_raw(packed_up_dev).unwrap();
            runtime.free_raw(scales_up_dev).unwrap();
            runtime.free_raw(zp_gate_dev).unwrap();
            runtime.free_raw(zp_up_dev).unwrap();
            runtime.free_raw(gamma_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut max_out = 0.0f32;
        for (mv, tv) in marlin_warm.iter().zip(tiled.iter()) {
            let mf = mv.to_f32();
            let tf = tv.to_f32();
            assert!(mf.is_finite(), "Marlin gate/up output must be finite");
            worst_abs = worst_abs.max((mf - tf).abs());
            max_out = max_out.max(tf.abs());
        }
        let tol = 3e-2 * max_out.max(1e-3);
        eprintln!(
            "Marlin gate/up parity (gamma={with_gamma}, decomposed={decomposed}): \
             worst_abs={worst_abs:.5}, max_out={max_out:.5}, tol={tol:.5}, \
             cold_safe={cold_safe}, warm_safe={warm_safe}"
        );
        assert!(
            worst_abs <= tol,
            "Marlin gate/up output diverges from tiled: worst_abs={worst_abs} > tol={tol}"
        );
        assert_eq!(
            marlin_cold, marlin_warm,
            "warm gate/up Marlin replay must be byte-identical to the cold run"
        );
        if check_capture {
            assert!(warm_safe, "warm gate/up call must remain capture-safe");
        }
    }

    #[test]
    #[ignore = "requires an SM80+ CUDA device"]
    fn marlin_gate_up_swiglu_matches_tiled_plain() {
        run_marlin_gate_up_parity(false, false, true);
    }

    #[test]
    #[ignore = "requires an SM80+ CUDA device"]
    fn marlin_gate_up_swiglu_matches_tiled_rmsnorm() {
        run_marlin_gate_up_parity(true, false, true);
    }

    #[test]
    #[ignore = "requires an SM80+ CUDA device"]
    fn marlin_gate_up_decomposed_swiglu_matches_tiled_rmsnorm() {
        run_marlin_gate_up_parity(true, true, false);
    }

    fn device_ptr(raw: CUdeviceptr) -> DevicePtr {
        DevicePtr(raw as usize as *const c_void)
    }

    fn device_ptr_mut(raw: CUdeviceptr) -> DevicePtrMut {
        DevicePtrMut(raw as usize as *mut c_void)
    }

    /// Direct fp16 GEMV parity against an f32/f64 dequant-and-matmul oracle that
    /// is fed the **same fp16-rounded** activations and the same (fp16- or
    /// f32-) rounded scales, so the residual covers only the kernel's documented
    /// accumulation precision and fp16 output rounding — not input quantization,
    /// which both sides share.
    fn run_parity(scales_fp16: bool, with_bias: bool) -> (f32, f32, f32, bool) {
        // K spans 128 block-32 groups (contraction depth 4096, near the model's
        // widest hidden path), N covers several 8-column CTAs plus a ragged tail.
        run_parity_dims(4096, 70, scales_fp16, with_bias, false)
    }

    /// Parametrized fp16 GEMV parity harness. `k` and `n` pick the projection
    /// shape so callers can pin the exact production dims (e.g. Qwen2.5-1.5B's
    /// gate/up K=1536,N=8960 and down-projection K=8960,N=1536) that select
    /// different GEMV variants and block-count boundaries. `explicit_zp` toggles
    /// the asymmetric per-block int4 zero-point path (see
    /// [`run_parity_dims_block`]). Delegates to [`run_parity_dims_block`] with
    /// the default block-32 layout.
    fn run_parity_dims(
        k: usize,
        n: usize,
        scales_fp16: bool,
        with_bias: bool,
        explicit_zp: bool,
    ) -> (f32, f32, f32, bool) {
        run_parity_dims_block(k, n, 32, scales_fp16, with_bias, explicit_zp)
    }

    /// Parametrized fp16 GEMV parity harness with an explicit `block_size`. The
    /// tuned block-32 kernels and the model-agnostic general-block-size kernel
    /// share this oracle; passing `block_size != 32` exercises the general
    /// decode GEMV (`matmul_nbits_gemv_f16_general_bs`) against the same f64
    /// dequant-and-matmul reference. `block_size` must be a power of two >= 16
    /// and must divide `k`. `explicit_zp` supplies a non-uniform per-block int4
    /// zero-point tensor (packed two block-nibbles per byte) instead of the
    /// symmetric zp=8 default, so a zero-point indexing regression in the
    /// general kernel's dequant path is caught.
    fn run_parity_dims_block(
        k: usize,
        n: usize,
        block_size: usize,
        scales_fp16: bool,
        with_bias: bool,
        explicit_zp: bool,
    ) -> (f32, f32, f32, bool) {
        let Some(runtime) = runtime() else {
            eprintln!("skipping MatMulNBits fp16 GEMV parity test: CUDA runtime unavailable");
            return (0.0, 0.0, 0.0, true);
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping MatMulNBits fp16 GEMV parity test: fp16 NVRTC headers unavailable");
            return (0.0, 0.0, 0.0, true);
        }

        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);

        // Deterministic LCG so the test is reproducible without extra crates.
        let mut state = 0x9e37_79b9_7f4a_7c15u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        // fp16 activations (device input) plus their fp16-value-as-f32 twin so
        // the oracle consumes identical inputs.
        let mut activation_f16 = vec![f16::ZERO; k];
        let mut activation_ref = vec![0.0f32; k];
        for (dst_h, dst_f) in activation_f16.iter_mut().zip(activation_ref.iter_mut()) {
            let h = f16::from_f32(next());
            *dst_h = h;
            *dst_f = h.to_f32();
        }

        // int4 quant codes (0..15), packed two nibbles per byte in the exact
        // symmetric block-32 layout the kernel unpacks.
        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for pair in 0..blob_size {
                    let low = quant[col * k + block * block_size + pair * 2] & 15;
                    let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                    packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                }
            }
        }

        // Explicit asymmetric int4 zero points: a non-uniform per-(col, block)
        // code in 0..15, packed two block-nibbles per byte exactly as the kernel
        // unpacks (`zp[col*zp_row_bytes + block/2]`, low nibble for even blocks).
        // The symmetric default (zp=8) is used when `explicit_zp` is false.
        let mut zp_codes = vec![8i32; n * k_blocks];
        let mut zp_packed = vec![0u8; n * zp_row_bytes];
        if explicit_zp {
            for code in zp_codes.iter_mut().take(n * k_blocks) {
                *code = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as i32;
            }
            for col in 0..n {
                for block in 0..k_blocks {
                    let code = (zp_codes[col * k_blocks + block] & 15) as u8;
                    let byte = &mut zp_packed[col * zp_row_bytes + block / 2];
                    if block & 1 == 0 {
                        *byte = (*byte & 0xf0) | code;
                    } else {
                        *byte = (*byte & 0x0f) | (code << 4);
                    }
                }
            }
        }

        // Per (col, block) scales, rounded to the storage dtype so both paths use
        // the same scale value.
        let mut scale_ref = vec![0.0f32; n * k_blocks];
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        let mut scale_f32 = vec![0.0f32; n * k_blocks];
        for i in 0..n * k_blocks {
            let raw = 0.015 + 0.01 * (next() * 0.5 + 0.5);
            if scales_fp16 {
                let h = f16::from_f32(raw);
                scale_f16[i] = h;
                scale_ref[i] = h.to_f32();
            } else {
                scale_f32[i] = raw;
                scale_ref[i] = raw;
            }
        }

        let mut bias_f16 = vec![f16::ZERO; n];
        let mut bias_ref = vec![0.0f32; n];
        if with_bias {
            for (h, f) in bias_f16.iter_mut().zip(bias_ref.iter_mut()) {
                let value = f16::from_f32(next());
                *h = value;
                *f = value.to_f32();
            }
        }

        // f64 dequant-and-matmul oracle over the shared fp16 activations.
        let mut expected = vec![0.0f32; n];
        for col in 0..n {
            let mut acc = 0.0f64;
            for block in 0..k_blocks {
                let scale = scale_ref[col * k_blocks + block] as f64;
                let zero_point = zp_codes[col * k_blocks + block];
                for within in 0..block_size {
                    let depth = block * block_size + within;
                    let q = quant[col * k + depth] as i32 - zero_point;
                    acc += activation_ref[depth] as f64 * q as f64 * scale;
                }
            }
            if with_bias {
                acc += bias_ref[col] as f64;
            }
            expected[col] = acc as f32;
        }

        let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime
            .alloc_raw(n * k_blocks * if scales_fp16 { 2 } else { 4 })
            .unwrap();
        let zp_dev = runtime.alloc_raw(zp_packed.len().max(1)).unwrap();
        let bias_dev = runtime.alloc_raw(n * 2).unwrap();
        let output_dev = runtime.alloc_raw(n * 2).unwrap();

        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime
                .htod(as_bytes(&activation_f16), activation_dev)
                .unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            if scales_fp16 {
                runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            } else {
                runtime.htod(as_bytes(&scale_f32), scales_dev).unwrap();
            }
            if explicit_zp {
                runtime.htod(&zp_packed, zp_dev).unwrap();
            }
            if with_bias {
                runtime.htod(as_bytes(&bias_f16), bias_dev).unwrap();
            }
        }

        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let bias_shape = [n];
        let bias_strides = [1i64];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];

        let scales_dtype = if scales_fp16 {
            DataType::Float16
        } else {
            DataType::Float32
        };
        let device = DeviceId::cuda(0);
        let mut inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                scales_dtype,
                &scales_shape,
                &scales_strides,
                device,
            ),
        ];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let zp_view = TensorView::new(
            device_ptr(zp_dev),
            DataType::Uint8,
            &zp_shape,
            &zp_strides,
            device,
        );
        // Slots: 3 = zero_points, 4 = g_idx, 5 = bias. Fill only up to the last
        // present optional input so the kernel's `optional_input` indexing holds.
        if explicit_zp {
            inputs.push(zp_view);
        } else if with_bias {
            inputs.push(TensorView::absent(DataType::Uint8));
        }
        if with_bias {
            inputs.push(TensorView::absent(DataType::Int32));
            inputs.push(TensorView::new(
                device_ptr(bias_dev),
                DataType::Float16,
                &bias_shape,
                &bias_strides,
                device,
            ));
        }

        let mut outputs = [TensorMut::new(
            device_ptr_mut(output_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        // The default decode GEMV launch is a static grid that allocates
        // nothing, so it is capture-safe on the very first call. That only holds
        // with the dispatch levers OFF: `ONNX_GENAI_INTERLEAVE_DEQUANT` routes
        // through `ensure_interleaved`, which allocates and interleaves the
        // packed weights on first sight and correctly reports that call
        // capture-unsafe. Hold the shared guard so the env-mutating interleave
        // test cannot flip the lever underneath this kernel run.
        let _levers = default_levers_guard();
        kernel.run(&inputs, &mut outputs, None).unwrap();
        runtime.synchronize().unwrap();

        assert!(
            kernel.last_call_capture_safe.load(Ordering::Relaxed),
            "fp16 decode GEMV must report capture-safe"
        );
        drop(_levers);

        let mut got_f16 = vec![f16::ZERO; n];
        // SAFETY: `output_dev` holds `n` fp16 values.
        unsafe {
            runtime
                .dtoh(as_bytes_mut(&mut got_f16), output_dev)
                .unwrap();
        }

        // SAFETY: each pointer came from this runtime's `alloc_raw` and is freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(bias_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut worst_rel = 0.0f32;
        let mut max_out = 0.0f32;
        let mut all_finite = true;
        for (g16, e) in got_f16.iter().zip(expected.iter()) {
            let g = g16.to_f32();
            if !g.is_finite() {
                all_finite = false;
            }
            let abs = (g - e).abs();
            let rel = abs / e.abs().max(1e-1);
            worst_abs = worst_abs.max(abs);
            worst_rel = worst_rel.max(rel);
            max_out = max_out.max(e.abs());
        }
        (worst_abs, worst_rel, max_out, all_finite)
    }

    /// Raw fp16 output of a symmetric (no zero-point, no bias) int4 decode GEMV
    /// at an explicit `block_size`, used by the interleaved-dequant byte-identity
    /// test. `interleave` toggles `ONNX_GENAI_INTERLEAVE_DEQUANT`; the general
    /// split-K heuristic is pinned OFF so the non-interleaved reference always
    /// takes the wide-load multicol kernel that the interleaved path replaces.
    /// Returns `None` when no CUDA device / fp16 NVRTC headers are available.
    // Eight parameters is the point: this helper exists to sweep a matrix of
    // independent route toggles, and naming each one at the call site is what
    // makes the A/B tests below readable. Bundling them into a struct would
    // move that matrix somewhere the reader has to go look for it.
    #[allow(clippy::too_many_arguments)]
    fn run_symmetric_block_raw(
        k: usize,
        n: usize,
        block_size: usize,
        scales_fp16: bool,
        interleave: bool,
        general_splitk: Option<bool>,
        pipeline: Option<bool>,
        prefetch: Option<bool>,
    ) -> Option<Vec<f16>> {
        let runtime = runtime()?;
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            return None;
        }

        let k_blocks = k / block_size;
        let blob_size = block_size / 2;

        let mut state = 0x1234_5678_9abc_def0u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation_f16 = vec![f16::ZERO; k];
        for dst_h in activation_f16.iter_mut() {
            *dst_h = f16::from_f32(next());
        }
        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for pair in 0..blob_size {
                    let low = quant[col * k + block * block_size + pair * 2] & 15;
                    let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                    packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                }
            }
        }
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        let mut scale_f32 = vec![0.0f32; n * k_blocks];
        for i in 0..n * k_blocks {
            let raw = 0.015 + 0.01 * (next() * 0.5 + 0.5);
            if scales_fp16 {
                scale_f16[i] = f16::from_f32(raw);
            } else {
                scale_f32[i] = raw;
            }
        }

        let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime
            .alloc_raw(n * k_blocks * if scales_fp16 { 2 } else { 4 })
            .unwrap();
        let output_dev = runtime.alloc_raw(n * 2).unwrap();
        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime
                .htod(as_bytes(&activation_f16), activation_dev)
                .unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            if scales_fp16 {
                runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            } else {
                runtime.htod(as_bytes(&scale_f32), scales_dev).unwrap();
            }
        }

        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];
        let scales_dtype = if scales_fp16 {
            DataType::Float16
        } else {
            DataType::Float32
        };
        let device = DeviceId::cuda(0);
        let inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                scales_dtype,
                &scales_shape,
                &scales_strides,
                device,
            ),
        ];
        let mut outputs = [TensorMut::new(
            device_ptr_mut(output_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        // Take the EXCLUSIVE side: the env writes below are visible to every
        // thread in the binary, so they must not overlap any test that expects
        // the levers at their default. SAFETY: the writes are confined to this
        // critical section and restored before the lock is released.
        let _guard = LeverEnvGuard::acquire();
        unsafe {
            match general_splitk {
                Some(true) => std::env::set_var("ONNX_GENAI_GENERAL_SPLITK", "on"),
                Some(false) => std::env::set_var("ONNX_GENAI_GENERAL_SPLITK", "off"),
                None => std::env::remove_var("ONNX_GENAI_GENERAL_SPLITK"),
            }
            if interleave {
                std::env::set_var("ONNX_GENAI_INTERLEAVE_DEQUANT", "1");
            } else {
                std::env::remove_var("ONNX_GENAI_INTERLEAVE_DEQUANT");
            }
            match pipeline {
                Some(true) => std::env::set_var("ONNX_GENAI_GEMV_PIPELINE", "1"),
                Some(false) => std::env::set_var("ONNX_GENAI_GEMV_PIPELINE", "0"),
                None => std::env::remove_var("ONNX_GENAI_GEMV_PIPELINE"),
            }
            match prefetch {
                Some(true) => std::env::set_var("ONNX_GENAI_ZP_SPLITK_PREFETCH", "1"),
                Some(false) => std::env::set_var("ONNX_GENAI_ZP_SPLITK_PREFETCH", "0"),
                None => std::env::remove_var("ONNX_GENAI_ZP_SPLITK_PREFETCH"),
            }
        }
        kernel.run(&inputs, &mut outputs, None).unwrap();
        runtime.synchronize().unwrap();
        // `_guard` clears the levers as it drops, on the unwind path too.
        drop(_guard);

        let mut got_f16 = vec![f16::ZERO; n];
        // SAFETY: `output_dev` holds `n` fp16 values.
        unsafe {
            runtime
                .dtoh(as_bytes_mut(&mut got_f16), output_dev)
                .unwrap();
            runtime.free_raw(activation_dev).unwrap();
            // NOTE: `packed_dev` is intentionally NOT freed. The interleave
            // cache is keyed by (source pointer, byte length); freeing the
            // packed buffer would return its address to `alloc_raw`'s size-class
            // free list, and the next same-size allocation on this runtime would
            // get it back with different contents behind the same key. Every
            // case here shares one runtime, so leaking the small test buffer is
            // what keeps each weight's address its own. Production weights are
            // graph initializers, which the executor never frees mid-session --
            // and the cache now dies with the runtime, so an address cannot
            // carry an entry into a later session either (#1726 class).
            // (Real allocations are reclaimed on process exit.)
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }
        Some(got_f16)
    }

    /// The opt-in TRT-LLM interleaved + biased int4 dequant
    /// (`ONNX_GENAI_INTERLEAVE_DEQUANT`) must be BYTE-IDENTICAL to the fp32
    /// wide-load multicol decode GEMV it replaces, on symmetric weights. The
    /// converter yields `(code - 8)` in fp16 exactly as the reference path, the
    /// eight products accumulate in the same ascending element order, and the
    /// offline nibble-interleave only changes *how* the codes are decoded, so
    /// the fp16 outputs must match bit-for-bit. Covers block-128 (glm) and
    /// block-64, fp16 and fp32 scales, and a ragged N tail.
    #[test]
    fn int4_interleaved_dequant_is_bit_identical_to_multicol() {
        let mut ran = false;
        for (k, n, block_size, scales_fp16) in [
            (4096usize, 256usize, 128usize, true),
            (4096, 256, 128, false),
            (4096, 70, 128, true),
            (8192, 512, 128, true),
            (4096, 256, 64, true),
        ] {
            let Some(base) = run_symmetric_block_raw(
                k,
                n,
                block_size,
                scales_fp16,
                false,
                Some(false),
                None,
                None,
            ) else {
                eprintln!(
                    "skipping interleaved dequant byte-identity test: CUDA runtime/headers \
                     unavailable"
                );
                return;
            };
            let inter = run_symmetric_block_raw(
                k,
                n,
                block_size,
                scales_fp16,
                true,
                Some(false),
                None,
                None,
            )
            .unwrap();
            ran = true;
            let mismatches = base
                .iter()
                .zip(inter.iter())
                .filter(|(b, i)| b.to_bits() != i.to_bits())
                .count();
            assert_eq!(
                mismatches, 0,
                "interleaved int4 dequant diverged from multicol at block-{block_size} K={k} \
                 N={n} scales_fp16={scales_fp16}: {mismatches}/{n} fp16 outputs differ"
            );
        }
        assert!(
            ran,
            "interleaved dequant byte-identity test did not execute any case"
        );
    }

    /// The opt-in interleaved+biased lever must also be BYTE-IDENTICAL on the
    /// grid-starved split-K WIDE path (`ONNX_GENAI_GENERAL_SPLITK=on`), which
    /// serves glm's narrow-N qkv/down projections. The offline nibble-interleave
    /// leaves each lane's fp32 partial bit-identical to the non-interleaved
    /// split-K wide kernel, and the K_SPLIT shared-memory reduction order is
    /// unchanged, so the fp16 outputs must match bit-for-bit.
    #[test]
    fn int4_interleaved_dequant_is_bit_identical_to_splitk_wide() {
        let mut ran = false;
        for (k, n, block_size, scales_fp16) in [
            (4096usize, 256usize, 128usize, true),
            (4096, 256, 128, false),
            (4096, 70, 128, true),
            (8192, 128, 128, true),
        ] {
            let Some(base) = run_symmetric_block_raw(
                k,
                n,
                block_size,
                scales_fp16,
                false,
                Some(true),
                None,
                None,
            ) else {
                eprintln!(
                    "skipping split-K wide interleaved byte-identity test: CUDA runtime/headers \
                     unavailable"
                );
                return;
            };
            let inter = run_symmetric_block_raw(
                k,
                n,
                block_size,
                scales_fp16,
                true,
                Some(true),
                None,
                None,
            )
            .unwrap();
            ran = true;
            let mismatches = base
                .iter()
                .zip(inter.iter())
                .filter(|(b, i)| b.to_bits() != i.to_bits())
                .count();
            assert_eq!(
                mismatches, 0,
                "interleaved int4 dequant diverged from split-K wide at block-{block_size} K={k} \
                 N={n} scales_fp16={scales_fp16}: {mismatches}/{n} fp16 outputs differ"
            );
        }
        assert!(
            ran,
            "split-K wide interleaved byte-identity test did not execute any case"
        );
    }

    /// Two providers on one device must not share interleaved weights.
    ///
    /// The cache is keyed by the source weight's device address, and an address
    /// is only a name for a buffer while the allocator that minted it is alive.
    /// While this cache was a process global, a weight freed with its session
    /// left an entry behind that the next session's same-size weight could hit
    /// at the recycled address -- the right kernel over somebody else's weights.
    /// The rule is now structural: an entry belongs to one runtime.
    ///
    /// The host-side falsifiers for the identity and lifetime rules, driven by a
    /// deterministic recycling allocator, are in `crate::interleave_cache`; this
    /// one checks the wiring on a real device.
    #[test]
    fn interleaved_weights_are_not_shared_between_runtimes() {
        const BYTES: usize = 4096;
        let Some(first) = crate::test_support::maybe_runtime() else {
            eprintln!("skipping interleave runtime-scoping test: no CUDA device");
            return;
        };
        let Some(second) = crate::test_support::maybe_runtime() else {
            return;
        };

        let packed = first.alloc_raw(BYTES).unwrap();
        let (built, warm) = ensure_interleaved(&first, packed, BYTES).unwrap();
        assert!(!warm, "the first sight of a weight must build it");
        assert_eq!(first.interleaved_weight_count(), 1);
        assert_eq!(
            second.interleaved_weight_count(),
            0,
            "a second runtime must not see the first runtime's entries"
        );

        // Same address, same length, other runtime: a global cache would serve
        // the buffer above.
        let (other, warm) = ensure_interleaved(&second, packed, BYTES).unwrap();
        assert!(
            !warm,
            "a runtime that has never interleaved this weight must build it"
        );
        assert_ne!(
            other, built,
            "two runtimes were served the same interleaved buffer for one address"
        );

        // SAFETY: allocated by `first` above and freed once.
        unsafe { first.free_raw(packed) }.unwrap();
    }

    /// Tearing a runtime down releases the interleaved copies it built.
    ///
    /// The map this replaced held 4096 entries, evicted only under an LRU its
    /// own documentation says never fills, and had no teardown at all: a full
    /// duplicate of every routed int4 weight stayed resident for the life of the
    /// process, across every session that ever loaded one.
    ///
    /// Exercises the same `release_all` that `Drop for CudaRuntime` calls, since
    /// a dropped runtime can no longer be asked what it holds. The assertion is
    /// that the entry is gone -- the next ask must build again rather than be
    /// served warm -- and not that the address came back from `alloc_raw`:
    /// `free_raw` may park a block in its size-class pool or return it to the
    /// driver depending on the pool budget, and either is correct here.
    #[test]
    fn tearing_down_a_runtime_releases_its_interleaved_weights() {
        const BYTES: usize = 2048;
        let Some(runtime) = crate::test_support::maybe_runtime() else {
            eprintln!("skipping interleave teardown test: no CUDA device");
            return;
        };
        let packed = runtime.alloc_raw(BYTES).unwrap();
        let (_, warm) = ensure_interleaved(&runtime, packed, BYTES).unwrap();
        assert!(!warm);
        assert_eq!(runtime.interleaved_weight_count(), 1);
        assert!(
            ensure_interleaved(&runtime, packed, BYTES).unwrap().1,
            "a cached weight must report warm before teardown"
        );

        runtime.release_interleaved_weights();

        assert_eq!(
            runtime.interleaved_weight_count(),
            0,
            "teardown left interleaved weights behind"
        );
        let (_, warm) = ensure_interleaved(&runtime, packed, BYTES).unwrap();
        assert!(
            !warm,
            "teardown dropped the buffer but left the entry, so a later weight \
             at this address would be served a freed pointer"
        );

        runtime.release_interleaved_weights();
        // SAFETY: allocated by this runtime above and freed once.
        unsafe { runtime.free_raw(packed).unwrap() };
    }

    /// The prefetch-pipelined single-warp block-32 scales-fp16 int4 decode GEMV
    /// (`matmul_nbits_gemv_f16_scales_f16_pipe`, default-on, `use_scales_f16_pipeline`)
    /// must be BYTE-IDENTICAL to the original single-load entry it replaces
    /// (`ONNX_GENAI_GEMV_PIPELINE=0`). The pipe variant only keeps extra weight
    /// loads in flight per lane (memory-level parallelism to hide the Long
    /// Scoreboard stall); it preserves the EXACT lane→nibble mapping, the same
    /// `accumulate_int4x8_f16_zp` calls with the same fp16 arguments in the same
    /// order, and the same fp16 accumulation — so every fp16 output must match
    /// bit-for-bit. A single differing bit means the reschedule reassociated the
    /// K-reduction and the byte-identity contract is broken. Covers the real
    /// block-32 decode projection widths (Qwen2.5-14B q/o K=N=5120, the wide MLP
    /// K=13824, a small attention shape, and a ragged-N tail) across fp16 and
    /// fp32 scales.
    #[test]
    fn scales_f16_pipeline_is_bit_identical_to_scalar() {
        let mut ran = false;
        for (k, n) in [
            (5120usize, 5120usize),
            (5120, 13824),
            (896, 896),
            (896, 4870),
        ] {
            for scales_fp16 in [true, false] {
                // The block-32 General single-warp path is the only one rerouted
                // to the pipe entry; confirm the dims select it before comparing.
                assert_eq!(
                    select_f16_gemv_variant(k, n, 32, scales_fp16, false).variant,
                    F16GemvVariant::General,
                    "K={k} N={n} scales_fp16={scales_fp16} must select the General variant"
                );
                let Some(scalar) =
                    run_symmetric_block_raw(k, n, 32, scales_fp16, false, None, Some(false), None)
                else {
                    eprintln!(
                        "skipping scales-fp16 pipeline byte-identity test: CUDA runtime/headers \
                         unavailable"
                    );
                    return;
                };
                let pipe =
                    run_symmetric_block_raw(k, n, 32, scales_fp16, false, None, Some(true), None)
                        .unwrap();
                ran = true;
                let mismatches = scalar
                    .iter()
                    .zip(pipe.iter())
                    .filter(|(s, p)| s.to_bits() != p.to_bits())
                    .count();
                assert_eq!(
                    mismatches, 0,
                    "prefetch-pipelined scales-fp16 GEMV diverged from the scalar entry at \
                     block-32 K={k} N={n} scales_fp16={scales_fp16}: {mismatches}/{n} fp16 \
                     outputs differ"
                );
            }
        }
        assert!(
            ran,
            "scales-fp16 pipeline byte-identity test did not execute any case"
        );
    }

    /// The prefetch-pipelined block-32 scales-fp16 split-K int4 GEMV
    /// (`ONNX_GENAI_ZP_SPLITK_PREFETCH`, default-on) keeps several weight-word
    /// loads in flight per lane to hide the Long-Scoreboard weight-load latency,
    /// but keeps the EXACT lane->nibble mapping, per-split accumulation order and
    /// K_SPLIT shared-memory reduction of the plain split-K kernel — so every
    /// fp16 output must match the plain split-K entry bit-for-bit. A single
    /// differing bit means the prefetch reschedule reassociated the reduction.
    /// Uses tiny-N, large-K shapes that are grid-starved on any GPU, so the
    /// symmetric split-K entry is provably selected (asserted below).
    #[test]
    fn scales_f16_zp_splitk_prefetch_is_bit_identical_to_splitk() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping split-K prefetch byte-identity test: CUDA runtime unavailable");
            return;
        };
        let sm = runtime.capabilities().multiprocessor_count();
        let max_threads = runtime.capabilities().max_threads_per_block();
        let mut ran = false;
        for (k, n) in [(5120usize, 8usize), (13824, 16), (5120, 64)] {
            for scales_fp16 in [true, false] {
                // Guard that these dims actually select the split-K entry the
                // prefetch swap targets; otherwise the comparison is vacuous.
                assert!(
                    use_f16_symmetric_splitk(k, n, sm, max_threads),
                    "K={k} N={n} must select the symmetric split-K entry (sm={sm})"
                );
                let Some(plain) =
                    run_symmetric_block_raw(k, n, 32, scales_fp16, false, None, None, Some(false))
                else {
                    eprintln!(
                        "skipping split-K prefetch byte-identity test: CUDA runtime/headers \
                         unavailable"
                    );
                    return;
                };
                let pf =
                    run_symmetric_block_raw(k, n, 32, scales_fp16, false, None, None, Some(true))
                        .unwrap();
                ran = true;
                let mismatches = plain
                    .iter()
                    .zip(pf.iter())
                    .filter(|(s, p)| s.to_bits() != p.to_bits())
                    .count();
                assert_eq!(
                    mismatches, 0,
                    "prefetch-pipelined split-K GEMV diverged from the plain split-K entry at \
                     block-32 K={k} N={n} scales_fp16={scales_fp16}: {mismatches}/{n} fp16 \
                     outputs differ"
                );
            }
        }
        assert!(
            ran,
            "split-K prefetch byte-identity test did not execute any case"
        );
    }

    /// GEMM. Drives the real `MatMulNBitsKernel::run` dispatch with
    /// `ONNX_GENAI_MARLIN_M_GT_1=1` so the `m > 1` seam routes to Marlin,
    /// exercising eligibility gating, the device repack + kernel-owned cache, and
    /// the launch. Validates the output against an f64 dequant→GEMM oracle
    /// (asymmetric zero points) within the relayout tolerance, and asserts the
    /// capture-safety contract: the first (cold) call repacks and reports
    /// NOT-capture-safe, while an identical second call hits the warm cache and
    /// reports capture-safe with byte-identical output.
    #[test]
    #[ignore = "requires an SM80+ CUDA device"]
    fn marlin_m_gt_1_op_parity_and_capture_safety() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping Marlin M>1 op parity: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("marlin_m_gt_1_op_parity")
            .is_err()
        {
            eprintln!("skipping Marlin M>1 op parity: fp16 NVRTC headers unavailable");
            return;
        }
        if !marlin_gemm::device_supports_marlin(runtime.capabilities().compute_capability()) {
            eprintln!("skipping Marlin M>1 op parity: device is pre-SM80");
            return;
        }

        // M=16 is the first height above the default looped-GEMV boundary, so
        // this exercises the Marlin dispatch rather than the M<=8 decode loop.
        let m = 16usize;
        let k = 4096usize;
        let n = 70usize;
        let block_size = 128usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);

        let mut state = 0x1234_5678_9abc_def0u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation_f16 = vec![f16::ZERO; m * k];
        let mut activation_ref = vec![0.0f32; m * k];
        for (h, f) in activation_f16.iter_mut().zip(activation_ref.iter_mut()) {
            let value = f16::from_f32(next());
            *h = value;
            *f = value.to_f32();
        }

        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for pair in 0..blob_size {
                    let low = quant[col * k + block * block_size + pair * 2] & 15;
                    let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                    packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                }
            }
        }

        // Asymmetric per-(col, block) zero points, nibble-packed as the kernel
        // unpacks them (low nibble for even blocks).
        let mut zp_codes = vec![0i32; n * k_blocks];
        let mut zp_packed = vec![0u8; n * zp_row_bytes];
        for code in zp_codes.iter_mut() {
            *code = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as i32;
        }
        for col in 0..n {
            for block in 0..k_blocks {
                let code = (zp_codes[col * k_blocks + block] & 15) as u8;
                let byte = &mut zp_packed[col * zp_row_bytes + block / 2];
                if block & 1 == 0 {
                    *byte = (*byte & 0xf0) | code;
                } else {
                    *byte = (*byte & 0x0f) | (code << 4);
                }
            }
        }

        let mut scale_ref = vec![0.0f32; n * k_blocks];
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        for i in 0..n * k_blocks {
            let h = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
            scale_f16[i] = h;
            scale_ref[i] = h.to_f32();
        }

        // f64 dequant→GEMM oracle: Y[row, col] = sum_k a[row,k] * (code-zp) * scale.
        let mut expected = vec![0.0f32; m * n];
        for row in 0..m {
            for col in 0..n {
                let mut acc = 0.0f64;
                for block in 0..k_blocks {
                    let scale = scale_ref[col * k_blocks + block] as f64;
                    let zp = zp_codes[col * k_blocks + block];
                    for within in 0..block_size {
                        let depth = block * block_size + within;
                        let q = quant[col * k + depth] as i32 - zp;
                        acc += activation_ref[row * k + depth] as f64 * q as f64 * scale;
                    }
                }
                expected[row * n + col] = acc as f32;
            }
        }

        let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scale_f16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zp_packed.len()).unwrap();
        let output_dev = runtime.alloc_raw(m * n * 2).unwrap();
        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime
                .htod(as_bytes(&activation_f16), activation_dev)
                .unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            runtime.htod(&zp_packed, zp_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];

        let inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        // Enable the opt-in Marlin path for the duration of this test.
        // SAFETY: this ignored GPU test runs serially; no other thread reads the
        // flag concurrently.
        unsafe {
            std::env::set_var("ONNX_GENAI_MARLIN_M_GT_1", "1");
        }

        let run_once = |capture_expectation: &str| -> Vec<f16> {
            let mut outputs = [TensorMut::new(
                device_ptr_mut(output_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            )];
            kernel.run(&inputs, &mut outputs, None).unwrap();
            runtime.synchronize().unwrap();
            let mut got = vec![f16::ZERO; m * n];
            // SAFETY: `output_dev` holds `m * n` fp16 values.
            unsafe {
                runtime.dtoh(as_bytes_mut(&mut got), output_dev).unwrap();
            }
            eprintln!(
                "Marlin M>1 op {capture_expectation}: capture_safe={}",
                kernel.last_call_capture_safe.load(Ordering::Relaxed)
            );
            got
        };

        // First call: cold repack ⇒ allocates ⇒ reported NOT capture-safe.
        let got_cold = run_once("cold");
        assert!(
            !kernel.last_call_capture_safe.load(Ordering::Relaxed),
            "cold Marlin call performs the repack allocation and must report NOT capture-safe"
        );

        // Second identical call: warm cache ⇒ no alloc ⇒ capture-safe, and the
        // static-grid kernel is deterministic so the bytes match exactly.
        let got_warm = run_once("warm");
        assert!(
            kernel.last_call_capture_safe.load(Ordering::Relaxed),
            "warm Marlin call reuses the cached repack and must report capture-safe"
        );
        assert_eq!(
            got_cold, got_warm,
            "warm replay of the static-grid Marlin kernel must be byte-identical to the cold run"
        );

        // SAFETY: reset the process-global flag so it cannot leak into other tests.
        unsafe {
            std::env::remove_var("ONNX_GENAI_MARLIN_M_GT_1");
        }

        // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut max_out = 0.0f32;
        for (g16, e) in got_warm.iter().zip(expected.iter()) {
            let g = g16.to_f32();
            assert!(g.is_finite(), "Marlin M>1 output must be finite");
            worst_abs = worst_abs.max((g - e).abs());
            max_out = max_out.max(e.abs());
        }
        let tol = 2e-2 * max_out.max(1e-3);
        eprintln!(
            "Marlin M>1 op parity: worst_abs={worst_abs:.5}, max_out={max_out:.5}, tol={tol:.5}"
        );
        assert!(
            worst_abs <= tol,
            "Marlin M>1 op output exceeds tolerance: worst_abs={worst_abs} > tol={tol}"
        );
    }

    /// The dequantize-to-fp16 + cuBLASLt tensor-core path taken at M>1, checked
    /// against the same f64 dequant→GEMM oracle the Marlin parity test uses and,
    /// in the same run, against Marlin itself.
    ///
    /// Two things are easy to get wrong here and neither shows up as a crash.
    /// The dequantize kernel writes `[N, K]` (matching the packed weight's own
    /// storage order, which is what makes its loads and stores coalesce), so the
    /// GEMM has to transpose it back — an error in that mapping silently
    /// produces a plausible-looking but wrong matrix. And the cuBLASLt call
    /// needs a declared workspace: when none is supplied the launch fails
    /// *after* the dequantize has already run and the caller quietly falls back
    /// to Marlin, so a test that only checked the numbers would pass while
    /// measuring the old path. This asserts the path actually ran.
    #[test]
    #[ignore = "requires an SM80+ CUDA device"]
    fn dequant_f16_cublas_m_gt_1_op_parity() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping dequant-f16 cuBLASLt parity: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("dequant_f16_cublas_m_gt_1_op_parity")
            .is_err()
        {
            eprintln!("skipping dequant-f16 cuBLASLt parity: fp16 NVRTC headers unavailable");
            return;
        }

        let m = 32usize;
        let k = 1024usize;
        let n = 96usize;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);

        let mut state = 0x0f1e_2d3c_4b5a_6978u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation_f16 = vec![f16::ZERO; m * k];
        let mut activation_ref = vec![0.0f32; m * k];
        for (h, f) in activation_f16.iter_mut().zip(activation_ref.iter_mut()) {
            let value = f16::from_f32(next());
            *h = value;
            *f = value.to_f32();
        }

        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for pair in 0..blob_size {
                    let low = quant[col * k + block * block_size + pair * 2] & 15;
                    let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                    packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                }
            }
        }

        let mut zp_codes = vec![0i32; n * k_blocks];
        let mut zp_packed = vec![0u8; n * zp_row_bytes];
        for code in zp_codes.iter_mut() {
            *code = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as i32;
        }
        for col in 0..n {
            for block in 0..k_blocks {
                let code = (zp_codes[col * k_blocks + block] & 15) as u8;
                let byte = &mut zp_packed[col * zp_row_bytes + block / 2];
                if block & 1 == 0 {
                    *byte = (*byte & 0xf0) | code;
                } else {
                    *byte = (*byte & 0x0f) | (code << 4);
                }
            }
        }

        let mut scale_ref = vec![0.0f32; n * k_blocks];
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        for i in 0..n * k_blocks {
            let h = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
            scale_f16[i] = h;
            scale_ref[i] = h.to_f32();
        }

        let mut expected = vec![0.0f32; m * n];
        for row in 0..m {
            for col in 0..n {
                let mut acc = 0.0f64;
                for block in 0..k_blocks {
                    let scale = scale_ref[col * k_blocks + block] as f64;
                    let zp = zp_codes[col * k_blocks + block];
                    for within in 0..block_size {
                        let depth = block * block_size + within;
                        let q = quant[col * k + depth] as i32 - zp;
                        acc += activation_ref[row * k + depth] as f64 * q as f64 * scale;
                    }
                }
                expected[row * n + col] = acc as f32;
            }
        }

        let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scale_f16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zp_packed.len()).unwrap();
        let output_dev = runtime.alloc_raw(m * n * 2).unwrap();
        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime
                .htod(as_bytes(&activation_f16), activation_dev)
                .unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            runtime.htod(&zp_packed, zp_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];

        let inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];

        let kernel = zc_kernel(&runtime, k, n, block_size);

        // Size the workspace exactly the way the executor does, through the
        // kernel's own declared requirement, so this also covers the plumbing
        // that denied the fused node a workspace in the first place.
        let metadata = [TensorMetadata {
            dtype: DataType::Float16,
            shape: &a_shape,
            present: true,
        }];
        let requirement = kernel.workspace_requirement_for(&metadata).unwrap();
        let workspace_bytes = requirement.bytes.max(1) as usize;
        let workspace_dev = runtime.alloc_raw(workspace_bytes).unwrap();

        let run_once = |dequant_f16: bool| -> Vec<f16> {
            // SAFETY: this ignored GPU test runs serially; no other thread reads
            // these flags concurrently.
            unsafe {
                std::env::set_var(
                    "ONNX_GENAI_DEQUANT_F16_GEMM",
                    if dequant_f16 { "1" } else { "0" },
                );
                std::env::set_var(
                    "ONNX_GENAI_MARLIN_M_GT_1",
                    if dequant_f16 { "0" } else { "1" },
                );
            }
            let mut outputs = [TensorMut::new(
                device_ptr_mut(output_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            )];
            let workspace = Some(WorkspaceView::new(
                device_ptr_mut(workspace_dev),
                workspace_bytes,
            ));
            kernel.run(&inputs, &mut outputs, workspace).unwrap();
            runtime.synchronize().unwrap();
            let mut got = vec![f16::ZERO; m * n];
            // SAFETY: `output_dev` holds `m * n` fp16 values.
            unsafe {
                runtime.dtoh(as_bytes_mut(&mut got), output_dev).unwrap();
            }
            got
        };

        assert!(
            requirement.bytes > 0,
            "the dequant-f16 path must declare a cuBLASLt workspace; a zero requirement means \
             the launch would fail and silently fall back to Marlin"
        );

        let got_dequant = run_once(true);
        let got_marlin = run_once(false);

        // SAFETY: reset the process-global flags so they cannot leak.
        unsafe {
            std::env::remove_var("ONNX_GENAI_DEQUANT_F16_GEMM");
            std::env::remove_var("ONNX_GENAI_MARLIN_M_GT_1");
        }
        // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
            runtime.free_raw(workspace_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut worst_vs_marlin = 0.0f32;
        let mut max_out = 0.0f32;
        for ((d16, m16), e) in got_dequant
            .iter()
            .zip(got_marlin.iter())
            .zip(expected.iter())
        {
            let d = d16.to_f32();
            assert!(d.is_finite(), "dequant-f16 output must be finite");
            worst_abs = worst_abs.max((d - e).abs());
            worst_vs_marlin = worst_vs_marlin.max((d - m16.to_f32()).abs());
            max_out = max_out.max(e.abs());
        }
        let tol = 2e-2 * max_out.max(1e-3);
        eprintln!(
            "dequant-f16 cuBLASLt parity: worst_abs={worst_abs:.5} vs_marlin={worst_vs_marlin:.5} \
             max_out={max_out:.5} tol={tol:.5} workspace={workspace_bytes}B"
        );
        assert!(
            worst_abs <= tol,
            "dequant-f16 cuBLASLt output exceeds oracle tolerance: {worst_abs} > {tol}"
        );
        assert!(
            worst_vs_marlin <= tol,
            "dequant-f16 cuBLASLt output diverged from Marlin: {worst_vs_marlin} > {tol}"
        );
    }

    fn zc_env_usize(key: &str, default: usize) -> usize {
        std::env::var(key)
            .ok()
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(default)
    }

    /// Deterministic int4/fp16 decode GEMV inputs for the #864 zero-copy probe.
    /// Mirrors the block-32 asymmetric (`zp`) layout the real `qwen14b-zp`
    /// decode path feeds `matmul_nbits_gemv_f16_scales_f16_zp` / its split-K
    /// sibling: `packed` is `n * k_blocks * blob_size` bytes (two int4 nibbles
    /// per byte), `scales` is fp16, `zero_points` is a per-(col, block) nibble.
    #[allow(clippy::type_complexity)]
    fn zc_make_inputs(
        k: usize,
        n: usize,
        block_size: usize,
    ) -> (Vec<f16>, Vec<u8>, Vec<f16>, Vec<u8>) {
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);

        let mut state = 0x9e37_79b9_7f4a_7c15u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation = vec![f16::ZERO; k];
        for slot in activation.iter_mut() {
            *slot = f16::from_f32(next());
        }

        // Packed int4 codes, two nibbles per byte, laid out exactly as the
        // kernel unpacks: `packed[(col * k_blocks + block) * blob_size + pair]`.
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for byte in packed.iter_mut() {
            let low = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
            let high = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
            *byte = low | (high << 4);
        }

        let mut scales = vec![f16::ZERO; n * k_blocks];
        for slot in scales.iter_mut() {
            *slot = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
        }

        // Asymmetric per-(col, block) int4 zero points, packed low/high nibble.
        let mut zp_packed = vec![0u8; n * zp_row_bytes];
        for col in 0..n {
            for block in 0..k_blocks {
                let code = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
                let byte = &mut zp_packed[col * zp_row_bytes + block / 2];
                if block & 1 == 0 {
                    *byte = (*byte & 0xf0) | code;
                } else {
                    *byte = (*byte & 0x0f) | (code << 4);
                }
            }
        }

        (activation, packed, scales, zp_packed)
    }

    fn zc_kernel(
        runtime: &Arc<CudaRuntime>,
        k: usize,
        n: usize,
        block_size: usize,
    ) -> MatMulNBitsKernel {
        MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        }
    }

    /// #864 — the decisive measurement this issue asks for. The 11.4 GB/s
    /// zero-copy figure on #864/#877 was an *upper bound* measured with a
    /// perfectly sequential `cuMemcpyDtoD` pull from mapped host memory. This
    /// runs the **real** int4/fp16 decode GEMV (`MatMulNBits`, the exact kernel
    /// plus launch config the engine selects) twice — once with its `packed`
    /// weight pointer from `cuMemAlloc` (VRAM) and once from
    /// `cuMemHostGetDevicePointer` over a `cuMemHostRegister(DEVICEMAP|
    /// READ_ONLY)` host buffer — with **only the weight pointer differing**.
    /// Everything else (activation, scales, zero-points, output) stays resident.
    ///
    /// It reports effective GB/s (packed_bytes / kernel_time, best-of-N) for
    /// both arms so the numbers are directly comparable to #877's table, and
    /// asserts the two arms' outputs are **bit-identical** (a zero-copy read
    /// that changes the result is a correctness failure, not a perf question).
    ///
    /// Sizes are swept because the ~11.9 MB average per-tensor page-in fits in
    /// this GPU's L2: at that size repeated VRAM reads are L2-cached and
    /// *overstate* device bandwidth, inflating the ratio in the hybrid's favour.
    /// The larger sizes exceed L2 and report the true cold DRAM-vs-PCIe rate the
    /// real 8.33 GB layer walk sees (each weight read once per step, evicted
    /// long before reuse). The honest ratio is the large-size one.
    ///
    /// `#[ignore]`: needs a live CUDA device and page-locks host RAM; it is a
    /// measurement, not a CI gate. Run solo with the GPU otherwise idle:
    ///   cargo test -p onnx-runtime-ep-cuda --features cuda --release \
    ///     zerocopy_kernel_host_mapped_vs_vram -- --ignored --nocapture --test-threads=1
    #[test]
    #[ignore]
    fn zerocopy_kernel_host_mapped_vs_vram_bandwidth() {
        use cudarc::driver::result::event;
        use cudarc::driver::sys;

        let Some(runtime) = runtime() else {
            eprintln!("skipping zero-copy kernel probe: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("zero-copy kernel probe")
            .is_err()
        {
            eprintln!("skipping zero-copy kernel probe: fp16 NVRTC headers unavailable");
            return;
        }
        runtime.bind().unwrap();

        const CU_MEMHOSTREGISTER_DEVICEMAP: u32 = 0x02;
        const CU_MEMHOSTREGISTER_READ_ONLY: u32 = 0x08;

        let k = zc_env_usize("ZC_K", 5120);
        let block_size = zc_env_usize("ZC_BLOCK", 32);
        let reps = zc_env_usize("ZC_REPS", 7).max(3);
        assert!(
            k.is_multiple_of(block_size),
            "K must be a multiple of block_size"
        );
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);
        let row_bytes = k_blocks * blob_size;

        let sizes_mib: Vec<usize> = std::env::var("ZC_SIZES_MIB")
            .ok()
            .map(|s| s.split(',').filter_map(|x| x.trim().parse().ok()).collect())
            .unwrap_or_else(|| vec![12, 64, 128, 256, 384]);

        let caps = runtime.capabilities();
        println!(
            "\n=== #864 zero-copy REAL-kernel bandwidth probe ===\n\
             SMs={} K={k} block_size={block_size} k_blocks={k_blocks} row_bytes/col={row_bytes} best-of-{reps}\n\
             (packed = int4 weights; only the packed pointer differs VRAM vs host-mapped)\n",
            caps.multiprocessor_count(),
        );
        println!(
            "{:>10} {:>9} {:>12} {:>12} {:>8} {:>10}",
            "packedMiB", "N", "VRAM GB/s", "host GB/s", "ratio", "match"
        );

        for mib in sizes_mib {
            let target = mib * (1usize << 20);
            let n = (target / row_bytes).max(1);
            let packed_bytes = n * row_bytes;
            let packed_mib = packed_bytes as f64 / (1u64 << 20) as f64;

            let (activation, packed, scales, zp_packed) = zc_make_inputs(k, n, block_size);

            // Resident buffers (identical for both arms).
            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let scales_dev = runtime.alloc_raw(scales.len() * 2).unwrap();
            let zp_dev = runtime.alloc_raw(zp_packed.len().max(1)).unwrap();
            let output_dev = runtime.alloc_raw(n * 2).unwrap();
            // VRAM copy of the weights (the arm the managed path streams into).
            let packed_vram = runtime.alloc_raw(packed_bytes).unwrap();

            // SAFETY: each device buffer was sized to its source slice.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(as_bytes(&scales), scales_dev).unwrap();
                runtime.htod(&zp_packed, zp_dev).unwrap();
                runtime.htod(&packed, packed_vram).unwrap();
            }

            // Host-mapped weights: page-lock the same bytes READ_ONLY and take a
            // device-addressable pointer into them (the zero-copy cold path).
            let host_ptr = packed.as_ptr() as *mut c_void;
            // SAFETY: `packed` outlives the registration; it is unregistered
            // below before `packed` is dropped, and never reallocated meanwhile.
            unsafe {
                sys::cuMemHostRegister_v2(
                    host_ptr,
                    packed_bytes,
                    CU_MEMHOSTREGISTER_DEVICEMAP | CU_MEMHOSTREGISTER_READ_ONLY,
                )
                .result()
                .expect("cuMemHostRegister(DEVICEMAP|READ_ONLY)");
            }
            let mut packed_host_dptr: CUdeviceptr = 0;
            // SAFETY: `host_ptr` was just registered with DEVICEMAP.
            unsafe {
                sys::cuMemHostGetDevicePointer_v2(&mut packed_host_dptr, host_ptr, 0)
                    .result()
                    .expect("cuMemHostGetDevicePointer");
            }

            let kernel = zc_kernel(&runtime, k, n, block_size);

            let a_shape = [1usize, k];
            let a_strides = [k as i64, 1];
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let s_shape = [n, k_blocks];
            let s_strides = [k_blocks as i64, 1];
            let zp_shape = [n, zp_row_bytes];
            let zp_strides = [zp_row_bytes as i64, 1];
            let y_shape = [1usize, n];
            let y_strides = [n as i64, 1];
            let device = DeviceId::cuda(0);

            let make_inputs = |packed_ptr: CUdeviceptr| {
                vec![
                    TensorView::new(
                        device_ptr(activation_dev),
                        DataType::Float16,
                        &a_shape,
                        &a_strides,
                        device,
                    ),
                    TensorView::new(
                        device_ptr(packed_ptr),
                        DataType::Uint8,
                        &b_shape,
                        &b_strides,
                        device,
                    ),
                    TensorView::new(
                        device_ptr(scales_dev),
                        DataType::Float16,
                        &s_shape,
                        &s_strides,
                        device,
                    ),
                    TensorView::new(
                        device_ptr(zp_dev),
                        DataType::Uint8,
                        &zp_shape,
                        &zp_strides,
                        device,
                    ),
                ]
            };

            let time_arm = |packed_ptr: CUdeviceptr| -> Vec<f32> {
                let inputs = make_inputs(packed_ptr);
                let mut outputs = [TensorMut::new(
                    device_ptr_mut(output_dev),
                    DataType::Float16,
                    &y_shape,
                    &y_strides,
                    device,
                )];
                // Warm up (first call also compiles the NVRTC module).
                kernel.run(&inputs, &mut outputs, None).unwrap();
                runtime.synchronize().unwrap();
                let mut times = Vec::with_capacity(reps);
                for _ in 0..reps {
                    let start = event::create(sys::CUevent_flags::CU_EVENT_DEFAULT).unwrap();
                    let end = event::create(sys::CUevent_flags::CU_EVENT_DEFAULT).unwrap();
                    // SAFETY: both events were just created on this context; the
                    // launch enqueues on the same stream between the records.
                    unsafe {
                        event::record(start, runtime.stream_ptr()).unwrap();
                        kernel.run(&inputs, &mut outputs, None).unwrap();
                        event::record(end, runtime.stream_ptr()).unwrap();
                        event::synchronize(end).unwrap();
                        times.push(event::elapsed(start, end).unwrap());
                        event::destroy(start).ok();
                        event::destroy(end).ok();
                    }
                }
                times
            };

            // VRAM arm, then read its output.
            let vram_times = time_arm(packed_vram);
            let mut got_vram = vec![f16::ZERO; n];
            // SAFETY: `output_dev` holds `n` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut got_vram), output_dev)
                    .unwrap()
            };

            // Host-mapped arm, then read its output.
            let host_times = time_arm(packed_host_dptr);
            let mut got_host = vec![f16::ZERO; n];
            // SAFETY: `output_dev` holds `n` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut got_host), output_dev)
                    .unwrap()
            };

            let best_ms = |t: &[f32]| t.iter().cloned().fold(f32::INFINITY, f32::min);
            let med_ms = |t: &[f32]| {
                let mut s = t.to_vec();
                s.sort_by(|a, b| a.partial_cmp(b).unwrap());
                s[s.len() / 2]
            };
            let gbps = |ms: f32| (packed_bytes as f64) / (ms as f64 / 1e3) / 1e9;
            let vram_gbps = gbps(best_ms(&vram_times));
            let host_gbps = gbps(best_ms(&host_times));

            let bit_match = got_vram
                .iter()
                .zip(got_host.iter())
                .all(|(a, b)| a.to_bits() == b.to_bits());

            println!(
                "{:>10.1} {:>9} {:>12.2} {:>12.2} {:>7.2}x {:>10}",
                packed_mib,
                n,
                vram_gbps,
                host_gbps,
                vram_gbps / host_gbps,
                if bit_match { "yes" } else { "NO" }
            );
            println!(
                "           spread: VRAM best={:.4} med={:.4} ms  host best={:.4} med={:.4} ms",
                best_ms(&vram_times),
                med_ms(&vram_times),
                best_ms(&host_times),
                med_ms(&host_times),
            );

            // Release this size's resources before the next (host RAM is
            // page-locked; VRAM is scarce). Not in a Drop guard — asserting in
            // Drop trips STATUS_STACK_BUFFER_OVERRUN in this tree.
            // SAFETY: `host_ptr` is still registered and `packed` still alive.
            unsafe {
                sys::cuMemHostUnregister(host_ptr)
                    .result()
                    .expect("cuMemHostUnregister");
            }
            // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
            unsafe {
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(scales_dev).unwrap();
                runtime.free_raw(zp_dev).unwrap();
                runtime.free_raw(output_dev).unwrap();
                runtime.free_raw(packed_vram).unwrap();
            }
            drop(packed);

            assert!(
                bit_match,
                "zero-copy host-mapped read produced a DIFFERENT result than the VRAM read \
                 (packed={packed_mib:.1} MiB, N={n}) — correctness failure"
            );
        }
    }

    /// #864 second question: can CUDA graph capture bake a **host-mapped**
    /// device pointer into a captured `MatMulNBits` launch and replay it
    /// correctly? Capture is a hard gate on the streaming path (`captures > 0`,
    /// `fallbacks == 0`, #796); if host-mapped pointers cannot be captured the
    /// hybrid's cold path is incompatible with capture. This captures the real
    /// decode GEMV reading its weights zero-copy from host memory, replays it,
    /// and asserts the replayed output matches an eager host-mapped run.
    ///
    /// `#[ignore]`: needs a live CUDA device. Run solo:
    ///   cargo test -p onnx-runtime-ep-cuda --features cuda --release \
    ///     zerocopy_kernel_capture_with_host_mapped_pointer -- --ignored --nocapture --test-threads=1
    #[test]
    #[ignore]
    fn zerocopy_kernel_capture_with_host_mapped_pointer() {
        use cudarc::driver::sys;

        let Some(runtime) = runtime() else {
            eprintln!("skipping capture probe: CUDA runtime unavailable");
            return;
        };
        if runtime.require_nvrtc_half_headers("capture probe").is_err() {
            eprintln!("skipping capture probe: fp16 NVRTC headers unavailable");
            return;
        }
        runtime.bind().unwrap();

        const CU_MEMHOSTREGISTER_DEVICEMAP: u32 = 0x02;
        const CU_MEMHOSTREGISTER_READ_ONLY: u32 = 0x08;

        let k = zc_env_usize("ZC_K", 5120);
        let block_size = zc_env_usize("ZC_BLOCK", 32);
        let n = zc_env_usize("ZC_CAPTURE_N", 4608);
        assert!(k.is_multiple_of(block_size));
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;
        let zp_row_bytes = k_blocks.div_ceil(2);
        let packed_bytes = n * k_blocks * blob_size;

        let (activation, packed, scales, zp_packed) = zc_make_inputs(k, n, block_size);

        let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
        let scales_dev = runtime.alloc_raw(scales.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zp_packed.len().max(1)).unwrap();
        let output_dev = runtime.alloc_raw(n * 2).unwrap();

        // SAFETY: each device buffer was sized to its source slice.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(as_bytes(&scales), scales_dev).unwrap();
            runtime.htod(&zp_packed, zp_dev).unwrap();
        }

        let host_ptr = packed.as_ptr() as *mut c_void;
        // SAFETY: `packed` outlives the registration and is unregistered below.
        unsafe {
            sys::cuMemHostRegister_v2(
                host_ptr,
                packed_bytes,
                CU_MEMHOSTREGISTER_DEVICEMAP | CU_MEMHOSTREGISTER_READ_ONLY,
            )
            .result()
            .expect("cuMemHostRegister(DEVICEMAP|READ_ONLY)");
        }
        let mut packed_host_dptr: CUdeviceptr = 0;
        // SAFETY: `host_ptr` was just registered with DEVICEMAP.
        unsafe {
            sys::cuMemHostGetDevicePointer_v2(&mut packed_host_dptr, host_ptr, 0)
                .result()
                .expect("cuMemHostGetDevicePointer");
        }

        let kernel = zc_kernel(&runtime, k, n, block_size);

        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let s_shape = [n, k_blocks];
        let s_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];
        let device = DeviceId::cuda(0);

        let inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_host_dptr),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::Float16,
                &s_shape,
                &s_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];
        let mut outputs = [TensorMut::new(
            device_ptr_mut(output_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];

        // Eager reference (also compiles the NVRTC module before capture).
        kernel.run(&inputs, &mut outputs, None).unwrap();
        runtime.synchronize().unwrap();
        let mut eager = vec![f16::ZERO; n];
        // SAFETY: `output_dev` holds `n` fp16 values.
        unsafe { runtime.dtoh(as_bytes_mut(&mut eager), output_dev).unwrap() };

        // Clobber the output so a broken replay cannot masquerade as a pass.
        // SAFETY: `output_dev` holds `n` fp16 values.
        unsafe {
            runtime
                .htod(as_bytes(&vec![f16::ONE; n]), output_dev)
                .unwrap()
        };

        let captured = runtime
            .begin_graph_capture(&[&kernel as &dyn Kernel])
            .is_ok();
        let mut replay_match = false;
        if captured {
            kernel.run(&inputs, &mut outputs, None).unwrap();
            match runtime.end_graph_capture() {
                Ok(()) => {
                    for _ in 0..4 {
                        runtime.replay_graph().unwrap();
                    }
                    runtime.synchronize().unwrap();
                    let mut got = vec![f16::ZERO; n];
                    // SAFETY: `output_dev` holds `n` fp16 values.
                    unsafe { runtime.dtoh(as_bytes_mut(&mut got), output_dev).unwrap() };
                    replay_match = got
                        .iter()
                        .zip(eager.iter())
                        .all(|(a, b)| a.to_bits() == b.to_bits());
                    runtime.reset_graph().ok();
                    println!(
                        "\n=== #864 capture-with-host-mapped-pointer probe ===\n\
                         capture: SUPPORTED; replay output bit-identical to eager: {}",
                        if replay_match { "YES" } else { "NO" }
                    );
                }
                Err(e) => {
                    runtime.abort_graph_capture().ok();
                    println!(
                        "\n=== #864 capture-with-host-mapped-pointer probe ===\n\
                         capture: end_graph_capture FAILED: {e:?}"
                    );
                }
            }
        } else {
            println!(
                "\n=== #864 capture-with-host-mapped-pointer probe ===\n\
                 capture: begin_graph_capture declined (kernel/audit not capturable in this build)"
            );
        }

        // SAFETY: `host_ptr` is still registered and `packed` still alive.
        unsafe {
            sys::cuMemHostUnregister(host_ptr)
                .result()
                .expect("cuMemHostUnregister");
        }
        // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }
        drop(packed);

        if captured {
            assert!(
                replay_match,
                "graph replay with a host-mapped weight pointer produced a different result \
                 than the eager host-mapped run"
            );
        }
    }

    /// Dequant-reference parity for the int8 (bits=8) fp16-activation decode
    /// GEMV at arbitrary `(k, n)`. Exercises the vectorised four-lane/eight-block
    /// path against an f64 oracle; `explicit_zp` toggles the symmetric zp=128
    /// default versus an explicit per-block uint8 zero point.
    fn run_int8_parity_dims(
        k: usize,
        n: usize,
        block_size: usize,
        scales_fp16: bool,
        with_bias: bool,
        explicit_zp: bool,
    ) -> (f32, f32, f32, bool) {
        let Some(runtime) = runtime() else {
            eprintln!("skipping MatMulNBits int8 fp16 GEMV parity test: CUDA runtime unavailable");
            return (0.0, 0.0, 0.0, true);
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!(
                "skipping MatMulNBits int8 fp16 GEMV parity test: fp16 NVRTC headers unavailable"
            );
            return (0.0, 0.0, 0.0, true);
        }

        let k_blocks = k / block_size;
        let blob_size = block_size; // one byte per weight for bits=8

        let mut state = 0x243f_6a88_85a3_08d3u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation_f16 = vec![f16::ZERO; k];
        let mut activation_ref = vec![0.0f32; k];
        for (dst_h, dst_f) in activation_f16.iter_mut().zip(activation_ref.iter_mut()) {
            let h = f16::from_f32(next());
            *dst_h = h;
            *dst_f = h.to_f32();
        }

        // int8 quant codes (0..255), one byte per weight in [n, k_blocks, 32].
        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for within in 0..block_size {
                    packed[(col * k_blocks + block) * blob_size + within] =
                        quant[col * k + block * block_size + within];
                }
            }
        }

        // Explicit per-block uint8 zero points, or the symmetric 128 default.
        let mut zero_points = vec![0u8; n * k_blocks];
        if explicit_zp {
            for zp in zero_points.iter_mut() {
                *zp = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
            }
        }
        let zp_ref = |col: usize, block: usize| -> i32 {
            if explicit_zp {
                zero_points[col * k_blocks + block] as i32
            } else {
                128
            }
        };

        let mut scale_ref = vec![0.0f32; n * k_blocks];
        let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
        let mut scale_f32 = vec![0.0f32; n * k_blocks];
        for i in 0..n * k_blocks {
            let raw = 0.015 + 0.01 * (next() * 0.5 + 0.5);
            if scales_fp16 {
                let h = f16::from_f32(raw);
                scale_f16[i] = h;
                scale_ref[i] = h.to_f32();
            } else {
                scale_f32[i] = raw;
                scale_ref[i] = raw;
            }
        }

        let mut bias_f16 = vec![f16::ZERO; n];
        let mut bias_ref = vec![0.0f32; n];
        if with_bias {
            for (h, f) in bias_f16.iter_mut().zip(bias_ref.iter_mut()) {
                let value = f16::from_f32(next());
                *h = value;
                *f = value.to_f32();
            }
        }

        let mut expected = vec![0.0f32; n];
        for col in 0..n {
            let mut acc = 0.0f64;
            for block in 0..k_blocks {
                let scale = scale_ref[col * k_blocks + block] as f64;
                let zp = zp_ref(col, block);
                for within in 0..block_size {
                    let depth = block * block_size + within;
                    let q = quant[col * k + depth] as i32 - zp;
                    acc += activation_ref[depth] as f64 * q as f64 * scale;
                }
            }
            if with_bias {
                acc += bias_ref[col] as f64;
            }
            expected[col] = acc as f32;
        }

        let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime
            .alloc_raw(n * k_blocks * if scales_fp16 { 2 } else { 4 })
            .unwrap();
        let zp_dev = runtime.alloc_raw(zero_points.len()).unwrap();
        let bias_dev = runtime.alloc_raw(n * 2).unwrap();
        let output_dev = runtime.alloc_raw(n * 2).unwrap();

        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime
                .htod(as_bytes(&activation_f16), activation_dev)
                .unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            if scales_fp16 {
                runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            } else {
                runtime.htod(as_bytes(&scale_f32), scales_dev).unwrap();
            }
            if explicit_zp {
                runtime.htod(&zero_points, zp_dev).unwrap();
            }
            if with_bias {
                runtime.htod(as_bytes(&bias_f16), bias_dev).unwrap();
            }
        }

        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, k_blocks];
        let zp_strides = [k_blocks as i64, 1];
        let bias_shape = [n];
        let bias_strides = [1i64];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];

        let scales_dtype = if scales_fp16 {
            DataType::Float16
        } else {
            DataType::Float32
        };
        let device = DeviceId::cuda(0);
        let mut inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                scales_dtype,
                &scales_shape,
                &scales_strides,
                device,
            ),
        ];
        if explicit_zp || with_bias {
            inputs.push(if explicit_zp {
                TensorView::new(
                    device_ptr(zp_dev),
                    DataType::Uint8,
                    &zp_shape,
                    &zp_strides,
                    device,
                )
            } else {
                TensorView::absent(DataType::Uint8)
            });
        }
        if with_bias {
            inputs.push(TensorView::absent(DataType::Int32));
            inputs.push(TensorView::new(
                device_ptr(bias_dev),
                DataType::Float16,
                &bias_shape,
                &bias_strides,
                device,
            ));
        }

        let mut outputs = [TensorMut::new(
            device_ptr_mut(output_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 8,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        kernel.run(&inputs, &mut outputs, None).unwrap();
        runtime.synchronize().unwrap();

        assert!(
            kernel.last_call_capture_safe.load(Ordering::Relaxed),
            "int8 decode GEMV must report capture-safe"
        );

        let mut got_f16 = vec![f16::ZERO; n];
        // SAFETY: `output_dev` holds `n` fp16 values.
        unsafe {
            runtime
                .dtoh(as_bytes_mut(&mut got_f16), output_dev)
                .unwrap();
        }

        // SAFETY: each pointer came from this runtime's `alloc_raw` and is freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(bias_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut worst_rel = 0.0f32;
        let mut max_out = 0.0f32;
        let mut all_finite = true;
        for (g16, e) in got_f16.iter().zip(expected.iter()) {
            let g = g16.to_f32();
            if !g.is_finite() {
                all_finite = false;
            }
            let abs = (g - e).abs();
            let rel = abs / e.abs().max(1e-1);
            worst_abs = worst_abs.max(abs);
            worst_rel = worst_rel.max(rel);
            max_out = max_out.max(e.abs());
        }
        (worst_abs, worst_rel, max_out, all_finite)
    }

    #[test]
    fn fp16_down_projection_is_bit_exact_to_staged_kernel() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping down-projection GEMV parity test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping down-projection GEMV parity test: fp16 NVRTC headers unavailable");
            return;
        }

        // Prove the specialization matches the general GEMV bit-numerically for
        // the Qwen down shape AND an unrelated non-Qwen tall-skinny shape, so
        // the generalized selection is correct beyond one architecture.
        for (k, n) in [
            (QWEN_DOWN_K, QWEN_DOWN_N),
            (5632usize, 2048usize),
            // K=16384, N=8192 selects the 4-column grid-fill entry on a 132-SM
            // device, so this covers the `_c4` variant bit-exactly too.
            (16_384usize, 8192usize),
        ] {
            assert_eq!(
                select_f16_gemv_variant(k, n, 32, true, false).variant,
                F16GemvVariant::DownProjection,
                "shape K={k}, N={n} must select the down variant under test"
            );
            let block_size = 32usize;
            let k_blocks = k / block_size;
            let blob_size = block_size / 2;

            let activation: Vec<f16> = (0..k)
                .map(|i| f16::from_f32(((i * 17 % 257) as f32 - 128.0) / 128.0))
                .collect();
            let packed: Vec<u8> = (0..n * k_blocks * blob_size)
                .map(|i| ((i * 29 + i / 7 + 13) & 0xff) as u8)
                .collect();
            let scales: Vec<f16> = (0..n * k_blocks)
                .map(|i| f16::from_f32(0.01 + (i % 17) as f32 * 0.0005))
                .collect();

            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
            let scales_dev = runtime.alloc_raw(scales.len() * 2).unwrap();
            let staged_output_dev = runtime.alloc_raw(n * 2).unwrap();
            let down_output_dev = runtime.alloc_raw(n * 2).unwrap();
            // SAFETY: device buffers exactly cover their source slices.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(&packed, packed_dev).unwrap();
                runtime.htod(as_bytes(&scales), scales_dev).unwrap();
            }

            let device = DeviceId::cuda(0);
            let a_shape = [1usize, k];
            let a_strides = [k as i64, 1];
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let scales_shape = [n, k_blocks];
            let scales_strides = [k_blocks as i64, 1];
            let y_shape = [1usize, n];
            let y_strides = [n as i64, 1];
            let activation_view = TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            );
            let packed_view = TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_view = TensorView::new(
                device_ptr(scales_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let mut down_output = TensorMut::new(
                device_ptr_mut(down_output_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            );
            let kernel = MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits: 4,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: false,
                gate_up_swiglu: false,
                decomposed_silu: false,
                rmsnorm_prologue: false,
                rmsnorm_epsilon: 1e-5,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };
            let staged_source = format!("{GEMV_F16_SRC}\n{STAGED_DOWN_REFERENCE_SRC}");
            let staged_function = runtime
                .nvrtc_function(
                    "matmul_nbits_gemv_f16_down_staged_reference",
                    &staged_source,
                    STAGED_DOWN_REFERENCE_ENTRY,
                )
                .unwrap();
            let activation_ptr = cuptr(activation_view.data_ptr::<u8>() as *const c_void);
            let packed_ptr = cuptr(packed_view.data_ptr::<u8>() as *const c_void);
            let scales_ptr = cuptr(scales_view.data_ptr::<u8>() as *const c_void);
            let zero_points_ptr: CUdeviceptr = 0;
            let bias_ptr: CUdeviceptr = 0;
            let staged_output_ptr = staged_output_dev;
            let k_i32 = as_i32("K", k).unwrap();
            let n_i32 = as_i32("N", n).unwrap();
            let block_size_i32 = as_i32("block_size", block_size).unwrap();
            let k_blocks_i32 = as_i32("K block count", k_blocks).unwrap();
            let blob_size_i32 = as_i32("block blob size", blob_size).unwrap();
            let zp_row_bytes_i32 =
                as_i32("zero-point row byte count", k_blocks.div_ceil(2)).unwrap();
            let scales_fp16_flag = 1i32;
            let bias_post_round_flag = 0i32;
            let mut staged_builder = runtime.stream().launch_builder(&staged_function);
            staged_builder
                .arg(&activation_ptr)
                .arg(&packed_ptr)
                .arg(&scales_ptr)
                .arg(&zero_points_ptr)
                .arg(&bias_ptr)
                .arg(&staged_output_ptr)
                .arg(&k_i32)
                .arg(&n_i32)
                .arg(&block_size_i32)
                .arg(&k_blocks_i32)
                .arg(&blob_size_i32)
                .arg(&zp_row_bytes_i32)
                .arg(&scales_fp16_flag)
                .arg(&bias_post_round_flag);
            // SAFETY: this launches the exact pre-change down-projection entry
            // over the same validated buffers used by the replacement below.
            unsafe {
                staged_builder
                    .launch(LaunchConfig {
                        grid_dim: (n.div_ceil(GEMV_F16_DOWN_COLUMNS_PER_BLOCK) as u32, 1, 1),
                        block_dim: (GEMV_F16_DOWN_THREADS, 1, 1),
                        shared_mem_bytes: (k * std::mem::size_of::<f16>()) as u32,
                    })
                    .unwrap();
            }
            kernel
                .launch_f16_gemv_variant(
                    &activation_view,
                    &packed_view,
                    &scales_view,
                    true,
                    None,
                    None,
                    &mut down_output,
                    k_blocks,
                    blob_size,
                    k_blocks.div_ceil(2),
                    select_f16_gemv_variant(k, n, block_size, true, false),
                )
                .unwrap();
            runtime.synchronize().unwrap();

            let mut staged = vec![f16::ZERO; n];
            let mut down = vec![f16::ZERO; n];
            // SAFETY: both output allocations hold `n` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut staged), staged_output_dev)
                    .unwrap();
                runtime
                    .dtoh(as_bytes_mut(&mut down), down_output_dev)
                    .unwrap();
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(packed_dev).unwrap();
                runtime.free_raw(scales_dev).unwrap();
                runtime.free_raw(staged_output_dev).unwrap();
                runtime.free_raw(down_output_dev).unwrap();
            }

            assert_eq!(
                as_bytes(&staged),
                as_bytes(&down),
                "register-loaded down projection must be bit-exact to the pre-change staged kernel \
                 at K={k}, N={n}"
            );
        }
    }

    #[test]
    fn fp16_gemv_variant_selection_is_structural() {
        // The down variant is selected by the tall-skinny (K>N) block-32 fp16
        // shape *class*, generalizing across models — not by a magic K/N.
        let qwen = select_f16_gemv_variant(QWEN_DOWN_K, QWEN_DOWN_N, 32, true, false);
        assert_eq!(qwen.variant, F16GemvVariant::DownProjection);
        assert_eq!(
            qwen.reason,
            "variant=down_projection;class=tall_skinny(K>N);block_size=32;\
             scales=fp16;K%32==0"
        );

        // Non-Qwen tall-skinny down/output projections, including contractions
        // larger than the former activation-staging limit, must also select it.
        for (k, n) in [
            (5632, 2048),
            (11008, 4096),
            (2048, 512),
            (4096, 4096 - 32),
            (32_768, 4096),
        ] {
            let selection = select_f16_gemv_variant(k, n, 32, true, false);
            assert_eq!(
                selection.variant,
                F16GemvVariant::DownProjection,
                "tall-skinny K={k}, N={n} must select the down variant"
            );
        }

        // Wide (N>=K) projections, non-multiple-of-32 K, and non-block-32 all
        // fall back.
        let general_cases = [
            (896, 4864, 32, true),    // gate/up: N > K
            (896, 896, 32, true),     // square: K == N is not tall-skinny
            (896, 151_936, 32, true), // lm_head: N >> K
            (4880, 896, 32, true),    // 4880 % 32 != 0
            (4864, 896, 64, true),    // block_size != 32
        ];
        for (k, n, block_size, scales_fp16) in general_cases {
            let selection = select_f16_gemv_variant(k, n, block_size, scales_fp16, false);
            assert_eq!(
                selection.variant,
                F16GemvVariant::General,
                "K={k}, N={n}, block_size={block_size} must retain the general GEMV"
            );
        }

        // fp32 scales are never down-eligible even for a tall-skinny shape.
        assert_eq!(
            select_f16_gemv_variant(QWEN_DOWN_K, QWEN_DOWN_N, 32, false, false).variant,
            F16GemvVariant::General,
        );

        let asymmetric = select_f16_gemv_variant(QWEN_DOWN_K, QWEN_DOWN_N, 32, true, true);
        assert_eq!(asymmetric.variant, F16GemvVariant::General);
        assert_eq!(
            asymmetric.reason,
            "variant=general;zero_points=explicit;down_projection requires symmetric zp=8"
        );
    }

    #[test]
    fn scales_f16_pipe_well_occupied_routes_lm_head_to_plain() {
        // The pipe-vs-plain occupancy gate keys only on N, the launch's
        // columns-per-CTA and the live SM count — no model-specific magic.
        // qwen3.5-0.8b measured shapes on an H200 (132 SMs, 8-warp large launch
        // => 8 columns per CTA):
        //   LM head  N=248320 -> grid 31040 (~235 CTAs/SM): WELL-OCCUPIED -> plain
        //   proj     N=4096   -> grid 512   (~3.9 CTAs/SM): grid-starved  -> pipe
        assert!(
            scales_f16_pipe_well_occupied(248_320, 8, 132),
            "the wide LM-head projection must be treated as well-occupied (plain)"
        );
        assert!(
            !scales_f16_pipe_well_occupied(4096, 8, 132),
            "a grid-starved N=4096 projection must keep the pipe entry"
        );

        // Device-derived, not a fixed N: the same width flips with the SM count.
        // grid = ceil(N/cols); well-occupied when grid >= mp_count*32.
        // N=8192, cols=8 -> grid 1024; threshold(mp)=mp*32.
        assert!(
            scales_f16_pipe_well_occupied(8192, 8, 32),
            "grid 1024 >= 32*32=1024 on a 32-SM device is well-occupied"
        );
        assert!(
            !scales_f16_pipe_well_occupied(8192, 8, 33),
            "grid 1024 < 33*32=1056 on a 33-SM device stays grid-starved"
        );

        // Degenerate inputs must not divide by zero.
        assert!(scales_f16_pipe_well_occupied(1_000_000, 0, 1));
        assert!(!scales_f16_pipe_well_occupied(1, 8, 0));
    }

    /// The asymmetric block-32 split-K gate recognises two separate reasons to
    /// split, so a saturated grid alone no longer vetoes it.
    ///
    /// The wide-N/large-K case is the one that regressed real decode: an
    /// occupancy-only rule sent a 26B model's N~5k-20k, K=6656/19968 projections
    /// to the single-warp pipe entry, which measured 5% slower in kernel time
    /// and issued 15% more launches per token than split-K on a 108-SM A100.
    #[test]
    fn asymmetric_splitk_gate_splits_for_bandwidth_as_well_as_for_occupancy() {
        let a100 = 108u32;
        let starved_n = 8; // far below SMs * 16
        let saturated_n = 19968;

        assert!(
            use_scales_f16_zp_splitk_gate(512, starved_n, a100),
            "a grid-starved projection must still split to fill idle SMs, \
             whatever K is"
        );
        assert!(
            use_scales_f16_zp_splitk_gate(6656, saturated_n, a100),
            "a saturated grid must still split when K is deep enough for the \
             halved load chain to pay for the extra reduction"
        );
        assert!(
            !use_scales_f16_zp_splitk_gate(512, saturated_n, a100),
            "a saturated grid with a shallow K keeps the occupancy-only rule, \
             which nothing has measured against"
        );
        assert!(
            use_scales_f16_zp_splitk_gate(ZP_SPLITK_BANDWIDTH_MIN_K, saturated_n, a100)
                && !use_scales_f16_zp_splitk_gate(ZP_SPLITK_BANDWIDTH_MIN_K - 1, saturated_n, a100),
            "the K threshold is inclusive at the measured depth and does not \
             extrapolate below it"
        );
    }

    #[test]
    fn symmetric_int8_splitk_gate_targets_grid_starved_only() {
        // The symmetric (no zero-point) int8 decode GEMV reuses the symmetric
        // int4 grid-fill predicate: split-K fires only when the single-warp grid
        // is too narrow to fill the device (N < mp_count * 16), so the
        // already-occupied wide projections keep the byte-identical single-warp
        // entry. qwen3.5-0.8b int8 shapes on an H200 (132 SMs => threshold 2112):
        //   N=1024 (down/o)  -> grid-starved  -> split-K
        //   N=2048           -> grid-starved  -> split-K
        //   N=3584 / N=6144  -> occupied      -> single-warp
        let (mp, max_threads) = (132u32, GEMV_F16_LARGE_THREADS);
        assert!(
            use_f16_symmetric_splitk(2048, 1024, mp, max_threads),
            "grid-starved N=1024 symmetric int8 must take split-K"
        );
        assert!(
            use_f16_symmetric_splitk(1024, 2048, mp, max_threads),
            "grid-starved N=2048 symmetric int8 must take split-K"
        );
        assert!(
            !use_f16_symmetric_splitk(1024, 3584, mp, max_threads),
            "occupied N=3584 symmetric int8 must keep the single-warp entry"
        );
        assert!(
            !use_f16_symmetric_splitk(1024, 6144, mp, max_threads),
            "occupied N=6144 symmetric int8 must keep the single-warp entry"
        );
        // K < 512 is ineligible (no whole 256-wide split step to spread).
        assert!(!use_f16_symmetric_splitk(256, 512, mp, max_threads));
        // Device-derived, not a fixed N: the same width flips with the SM count.
        assert!(use_f16_symmetric_splitk(1024, 3584, 256, max_threads));

        // The opt-out flag is default-on (enabled) when unset.
        // (Env-driven; asserted here only for the unset default to avoid racing
        // other tests that may set process-wide env.)
        if std::env::var_os("ONNX_GENAI_CUDA_DISABLE_INT8_SYMMETRIC_SPLITK").is_none() {
            assert!(int8_symmetric_splitk_enabled());
        }
    }

    #[test]
    fn splitk_smalln_single_column_is_shape_driven_and_general() {
        // A narrow (grid-starved) projection — e.g. a GQA k/v projection with
        // N = kv_heads * head_dim (2*128 = 256) — under-fills the device with the
        // multicol hybrid (grid = ceil(256/8) = 32 CTAs << 132 SMs), so it must
        // prefer the byte-identical single-column split-K wide entry whose 4x
        // larger grid fills the idle SMs.
        assert!(
            splitk_smalln_prefers_single_column(256, 132),
            "a narrow N=256 kv projection must fall back to the single-column entry"
        );
        // Larger GQA kv widths that still under-fill also flip (shape-driven, not
        // a single magic constant): N=512 -> grid 64 < 132.
        assert!(splitk_smalln_prefers_single_column(512, 132));

        // The medium/large projections (down_proj / q / o at N~4096) keep the
        // multicol hybrid: grid = ceil(4096/8) = 512 >= 132 SMs, so the register
        // blocking wins and the grid already fills the device.
        assert!(
            !splitk_smalln_prefers_single_column(4096, 132),
            "a wide N=4096 projection must keep the multicol hybrid"
        );
        assert!(!splitk_smalln_prefers_single_column(27_392, 132));

        // Device-derived, not model-specific: the same N flips on a bigger device
        // (more SMs to fill) and holds on a tiny one.
        assert!(
            splitk_smalln_prefers_single_column(1024, 132),
            "N=1024 -> grid 128 < 132 SMs still under-fills a large device"
        );
        assert!(
            !splitk_smalln_prefers_single_column(1024, 100),
            "N=1024 -> grid 128 >= 100 SMs fills a smaller device"
        );

        // Env override forces the decision for A/B measurement.
        // SAFETY: serial logic test (--test-threads=1); the flag is cleared below
        // so it cannot leak into other tests.
        unsafe {
            std::env::set_var("ONNX_GENAI_GEMV_SPLITK_SMALLN_SINGLECOL", "1");
        }
        assert!(splitk_smalln_prefers_single_column(4096, 132));
        unsafe {
            std::env::set_var("ONNX_GENAI_GEMV_SPLITK_SMALLN_SINGLECOL", "0");
        }
        assert!(!splitk_smalln_prefers_single_column(256, 132));
        unsafe {
            std::env::remove_var("ONNX_GENAI_GEMV_SPLITK_SMALLN_SINGLECOL");
        }
    }

    #[test]
    fn down_columns_fill_the_device_and_never_undersplit() {
        // Wide down projection: the 8-column grid already clears the ~2-wave
        // target, so keep the cheapest 8-column launch.
        assert_eq!(
            select_down_columns(65_536, 132),
            (8, GEMV_F16_DOWN_ENTRY),
            "a wide down projection must keep the 8-column launch"
        );
        // Mid-width: 8-column grid underfills but the 4-column one clears it.
        assert_eq!(
            select_down_columns(8192, 132),
            (4, GEMV_F16_DOWN_C4_ENTRY),
            "a mid-width down projection must split to 4 columns/CTA"
        );
        // Grid-starved (Qwen2.5-7B down N=3584 on an H200's 132 SMs): split to
        // the measured-optimal 2 columns/CTA.
        assert_eq!(
            select_down_columns(3584, 132),
            (2, GEMV_F16_DOWN_C2_ENTRY),
            "a grid-starved down projection must split to 2 columns/CTA"
        );
        // Even a tiny N never drops below 2 columns/CTA (1-column launches
        // over-subscribe and re-read the activation 8x, erasing the gain).
        assert_eq!(select_down_columns(64, 132).0, 2);
        // A tiny/degenerate device (clamped to >=1 SM) has a small target, so a
        // wide-enough N stays on the cheapest 8-column launch instead of
        // over-splitting.
        assert_eq!(select_down_columns(3584, 0), (8, GEMV_F16_DOWN_ENTRY));
    }

    #[test]
    fn accuracy4_stage64_is_limited_to_sub_wave_block32_grids() {
        assert!(use_accuracy4_stage64(4608, 132, (9, 0), 64 * 1024));
        assert!(!use_accuracy4_stage64(4608, 46, (8, 9), 48 * 1024));
        assert!(!use_accuracy4_stage64(4608, 28, (8, 6), 48 * 1024));
        assert!(!use_accuracy4_stage64(4608, 132, (9, 0), 1024));
        assert!(!use_accuracy4_stage64(65_536, 132, (9, 0), 64 * 1024));
    }

    /// Byte-identity guard for routing `use_accuracy4_stage64`'s resident-warp
    /// estimate through the arch layer: the arch helper must reproduce the exact
    /// pre-refactor inline ladder for every compute capability, so the stage-64
    /// decision (and therefore H200's selection) is provably unchanged.
    #[test]
    fn accuracy4_resident_warps_matches_prior_inline_ladder() {
        fn prior_inline_ladder(compute_capability: (u32, u32)) -> u32 {
            match compute_capability {
                (8, 0) | (9.., _) => 64,
                _ => 48,
            }
        }
        for major in 0u32..=13 {
            for minor in 0u32..=12 {
                let cc = (major, minor);
                assert_eq!(
                    crate::arch::decode_resident_warps_per_sm(cc),
                    prior_inline_ladder(cc),
                    "arch resident-warp ladder diverged from the frozen inline ladder at {cc:?}"
                );
            }
        }
        // And the full stage-64 decision is unchanged across a shape/arch sweep.
        for &(n, sms, cc, smem) in &[
            (4608usize, 132u32, (9u32, 0u32), 64 * 1024u32),
            (4608, 46, (8, 9), 48 * 1024),
            (4608, 28, (8, 6), 48 * 1024),
            (1024, 132, (9, 0), 64 * 1024),
            (65_536, 132, (9, 0), 64 * 1024),
            (2048, 84, (8, 9), 64 * 1024),
            (4096, 68, (8, 6), 64 * 1024),
        ] {
            let resident = prior_inline_ladder(cc) as usize;
            let resident_ctas = resident / (GEMV_ACCURACY4_THREADS as usize / 32);
            let one_wave = (sms.max(1) as usize).saturating_mul(resident_ctas);
            let expected = smem >= GEMV_ACCURACY4_STAGE64_SHARED_BYTES
                && n.div_ceil(GEMV_ACCURACY4_COLUMNS_PER_BLOCK) < one_wave;
            assert_eq!(
                use_accuracy4_stage64(n, sms, cc, smem),
                expected,
                "stage64 decision changed for n={n} sms={sms} cc={cc:?} smem={smem}"
            );
        }
    }

    #[test]
    fn symmetric_fp16_splitk_is_device_driven_and_falls_back_on_small_gpus() {
        assert!(use_f16_symmetric_splitk(896, 1152, 132, 1024));
        assert!(!use_f16_symmetric_splitk(896, 1152, 46, 1024));
        assert!(!use_f16_symmetric_splitk(896, 1152, 132, 128));
        assert!(!use_f16_symmetric_splitk(256, 1024, 132, 1024));
    }

    #[test]
    fn fp16_down_projection_loads_activation_directly_into_registers() {
        let start = GEMV_F16_SRC
            .find("void matmul_nbits_gemv_f16_scales_f16_down_tpl")
            .expect("down-projection template must exist");
        let body = &GEMV_F16_SRC[start..];
        let end = body
            .find("\n}\n\n// Default 8-column down projection")
            .expect("down-projection template must have a bounded body");
        let body = &body[..end];

        assert!(
            !body.contains("activation_shared"),
            "down projection must not round-trip activations through shared memory"
        );
        for offset in [
            "activation_block);",
            "activation_block + 8);",
            "activation_block + 16);",
            "activation_block + 24);",
        ] {
            assert!(
                body.contains(offset),
                "down projection must directly load the block-32 activation at {offset}"
            );
        }
    }

    #[test]
    fn fp16_gemv_matches_dequant_reference() {
        let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
            (0.0f32, 0.0f32, 0.0f32, true);
        for (scales_fp16, with_bias) in [(false, false), (true, false), (true, true)] {
            let (abs, rel, out, finite) = run_parity(scales_fp16, with_bias);
            worst_abs = worst_abs.max(abs);
            worst_rel = worst_rel.max(rel);
            max_out = max_out.max(out);
            all_finite &= finite;
        }
        // fp16 output ULP is 2^-11 (~4.9e-4) of a value's magnitude, so the
        // absolute error floor scales with the largest output component. Bound
        // the observed abs error against that magnitude with 2x headroom for the
        // fp32-vs-f64 reduction-order drift accumulated over K=4096.
        let abs_bound = (max_out * 1e-3).max(1e-3);
        eprintln!(
            "MatMulNBits fp16 GEMV parity: max_abs={worst_abs:.3e} max_rel={worst_rel:.3e} \
             max_out={max_out:.3e} abs_bound={abs_bound:.3e}"
        );
        assert!(all_finite, "fp16 GEMV produced a non-finite output");
        assert!(
            worst_abs < abs_bound,
            "fp16 GEMV diverged from dequant reference: max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
        );
        // Relative error (against a 1e-1 floor so near-zero columns do not
        // explode the ratio) isolates the per-element accuracy from the output
        // magnitude and must stay well under 5e-2.
        assert!(
            worst_rel < 5e-2,
            "fp16 GEMV diverged from dequant reference: max_rel={worst_rel:.3e}"
        );
    }

    /// Multi-request batch decode byte-identity guard for the looped fp16 decode
    /// GEMV (limiter B fix). For `1 < m <= decode_gemv_loop_max_m()`, `run_f16`
    /// runs the specialized single-row decode GEMV once per row instead of the
    /// portable tiled prefill GEMM. Because each row is dispatched through the
    /// *identical* `dispatch_f16_decode_gemv_row` path the M==1 decode step uses,
    /// row `r` of the batched output must be BIT-for-BIT equal to running that
    /// row alone as an M==1 GEMV. This is the strong form of the bit-identity
    /// claim: batched decode is byte-identical to single-stream decode, so a
    /// batch cannot change any user's logits. A regression that reintroduced a
    /// tiled-GEMM (fp32-accumulation, different reduction order) batch path — or
    /// mis-strided the per-row sub-views — would diverge here.
    #[test]
    fn decode_gemv_loop_is_byte_identical_to_per_row_singlestream() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping looped decode GEMV byte-identity test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!(
                "skipping looped decode GEMV byte-identity test: fp16 NVRTC headers unavailable"
            );
            return;
        }

        // Qwen2.5-0.5B-ish block-32 shapes: square attention proj and the wide
        // MLP (K<N general GEMV, K>N tall-skinny GEMV). m=4 sits inside the
        // default loop window (max_m=8).
        for (k, n) in [
            (896usize, 896usize),
            (896usize, 4864usize),
            (4864usize, 896usize),
        ] {
            let m = 4usize;
            let block_size = 32usize;
            let k_blocks = k / block_size;
            let blob_size = block_size / 2;

            let mut state = 0x0123_4567_89ab_cdefu64 ^ ((k as u64) << 20) ^ (n as u64);
            let mut next = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
            };

            // m distinct activation rows, contiguous [m, k].
            let mut activation_f16 = vec![f16::ZERO; m * k];
            for h in activation_f16.iter_mut() {
                *h = f16::from_f32(next());
            }

            // Symmetric int4 weights (implicit zp=8), block-32, no bias.
            let mut quant = vec![0u8; n * k];
            for value in quant.iter_mut() {
                *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
            }
            let mut packed = vec![0u8; n * k_blocks * blob_size];
            for col in 0..n {
                for block in 0..k_blocks {
                    for pair in 0..blob_size {
                        let low = quant[col * k + block * block_size + pair * 2] & 15;
                        let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                        packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                    }
                }
            }
            let mut scale_f16 = vec![f16::ZERO; n * k_blocks];
            for s in scale_f16.iter_mut() {
                *s = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
            }

            let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
            let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
            let scales_dev = runtime.alloc_raw(scale_f16.len() * 2).unwrap();
            let loop_out_dev = runtime.alloc_raw(m * n * 2).unwrap();
            let ref_out_dev = runtime.alloc_raw(n * 2).unwrap();
            // SAFETY: device buffers were sized to hold each source slice.
            unsafe {
                runtime
                    .htod(as_bytes(&activation_f16), activation_dev)
                    .unwrap();
                runtime.htod(&packed, packed_dev).unwrap();
                runtime.htod(as_bytes(&scale_f16), scales_dev).unwrap();
            }

            let device = DeviceId::cuda(0);
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let scales_shape = [n, k_blocks];
            let scales_strides = [k_blocks as i64, 1];
            let packed_view = TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_view = TensorView::new(
                device_ptr(scales_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );

            let kernel = MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits: 4,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: false,
                gate_up_swiglu: false,
                decomposed_silu: false,
                rmsnorm_prologue: false,
                rmsnorm_epsilon: 1e-5,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };

            // Batched path: m>1 routes through the looped single-row decode GEMV.
            let a_shape_m = [m, k];
            let a_strides_m = [k as i64, 1];
            let y_shape_m = [m, n];
            let y_strides_m = [n as i64, 1];
            let inputs_m = vec![
                TensorView::new(
                    device_ptr(activation_dev),
                    DataType::Float16,
                    &a_shape_m,
                    &a_strides_m,
                    device,
                ),
                packed_view,
                scales_view,
            ];
            {
                let mut outputs_m = [TensorMut::new(
                    device_ptr_mut(loop_out_dev),
                    DataType::Float16,
                    &y_shape_m,
                    &y_strides_m,
                    device,
                )];
                // Warm once so scratch pools are allocated, then the measured run
                // must report capture-safe (mirrors the M==1 decode contract).
                kernel.run(&inputs_m, &mut outputs_m, None).unwrap();
                kernel.run(&inputs_m, &mut outputs_m, None).unwrap();
                runtime.synchronize().unwrap();
            }
            assert!(
                kernel.last_call_capture_safe.load(Ordering::Relaxed),
                "warm looped decode GEMV must report capture-safe (K={k} N={n})"
            );
            let mut loop_out = vec![f16::ZERO; m * n];
            // SAFETY: `loop_out_dev` holds `m * n` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut loop_out), loop_out_dev)
                    .unwrap();
            }

            // Reference: run each row alone as an independent M==1 GEMV over the
            // same weights and the same (offset) activation row.
            let mut ref_out = vec![f16::ZERO; m * n];
            for r in 0..m {
                let a_off = (r * k * 2) as CUdeviceptr;
                let a_shape_1 = [1usize, k];
                let a_strides_1 = [k as i64, 1];
                let y_shape_1 = [1usize, n];
                let y_strides_1 = [n as i64, 1];
                let inputs_1 = vec![
                    TensorView::new(
                        device_ptr(activation_dev + a_off),
                        DataType::Float16,
                        &a_shape_1,
                        &a_strides_1,
                        device,
                    ),
                    packed_view,
                    scales_view,
                ];
                let mut outputs_1 = [TensorMut::new(
                    device_ptr_mut(ref_out_dev),
                    DataType::Float16,
                    &y_shape_1,
                    &y_strides_1,
                    device,
                )];
                kernel.run(&inputs_1, &mut outputs_1, None).unwrap();
                runtime.synchronize().unwrap();
                // SAFETY: `ref_out_dev` holds `n` fp16 values.
                unsafe {
                    runtime
                        .dtoh(as_bytes_mut(&mut ref_out[r * n..(r + 1) * n]), ref_out_dev)
                        .unwrap();
                }
            }

            // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
            unsafe {
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(packed_dev).unwrap();
                runtime.free_raw(scales_dev).unwrap();
                runtime.free_raw(loop_out_dev).unwrap();
                runtime.free_raw(ref_out_dev).unwrap();
            }

            let mismatches = loop_out
                .iter()
                .zip(ref_out.iter())
                .filter(|(a, b)| a.to_bits() != b.to_bits())
                .count();
            assert_eq!(
                mismatches,
                0,
                "looped batch-{m} decode GEMV diverged from per-row single-stream decode at \
                 K={k} N={n}: {mismatches}/{} fp16 outputs differ",
                m * n
            );
        }
    }

    /// Multi-request batch decode byte-identity guard for the **fused gate/up
    /// SwiGLU with an RMS-norm prologue** — the node whose small-batch decode is
    /// routed through the per-row capture-safe loop by this fix. For
    /// `1 < m <= decode_gemv_loop_max_m()` and a present gamma, the production
    /// path (`run_f16_gate_up_swiglu`) dispatches `launch_gate_up_swiglu_rmsnorm`
    /// once per row over a 1×K sub-view, which is the *identical* kernel an M==1
    /// rmsnorm decode step runs. Therefore row `r` of the batched output must be
    /// BIT-for-BIT equal to running that row alone as an M==1 fused rmsnorm
    /// decode. This is THE batching-contract invariant this change must protect:
    /// a request batched with others produces the same tokens as if it had run
    /// alone. (The two-op ULP sweeps bound accuracy vs a different reference;
    /// this asserts exact single-stream equivalence.) A regression that routed
    /// M>1 through the tiled prefill GEMM / Marlin (different reduction order), or
    /// mis-strided the per-row sub-views, would diverge here.
    #[test]
    fn gate_up_swiglu_rmsnorm_loop_is_byte_identical_to_per_row_singlestream() {
        let Some(runtime) = runtime() else {
            eprintln!(
                "skipping rmsnorm gate/up SwiGLU byte-identity test: CUDA runtime unavailable"
            );
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!(
                "skipping rmsnorm gate/up SwiGLU byte-identity test: fp16 NVRTC headers unavailable"
            );
            return;
        }

        // Qwen2.5-0.5B-ish gate/up shapes (K<N wide MLP and a square case).
        // m=4 sits inside the default per-row loop window (max_m=8).
        for (k, n) in [(896usize, 4864usize), (896usize, 896usize)] {
            let m = 4usize;
            let block_size = 32usize;
            let k_blocks = k / block_size;
            let blob_size = block_size / 2;

            let mut state = 0x51ed_2701_c0ff_ee11u64 ^ ((k as u64) << 20) ^ (n as u64);
            let mut next = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
            };

            // m distinct activation rows, contiguous [m, k].
            let mut activation_f16 = vec![f16::ZERO; m * k];
            for h in activation_f16.iter_mut() {
                *h = f16::from_f32(next());
            }
            // fp16 gamma, length k.
            let mut gamma_f16 = vec![f16::ZERO; k];
            for g in gamma_f16.iter_mut() {
                *g = f16::from_f32(0.75 + 0.5 * (next() * 0.5 + 0.5));
            }

            // Symmetric int4 gate and up weights (implicit zp=8), block-32.
            let pack = |next: &mut dyn FnMut() -> f32| {
                let mut quant = vec![0u8; n * k];
                for value in quant.iter_mut() {
                    *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
                }
                let mut packed = vec![0u8; n * k_blocks * blob_size];
                for col in 0..n {
                    for block in 0..k_blocks {
                        for pair in 0..blob_size {
                            let low = quant[col * k + block * block_size + pair * 2] & 15;
                            let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                            packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                        }
                    }
                }
                packed
            };
            let packed_gate = pack(&mut next);
            let packed_up = pack(&mut next);
            let mut scales_gate = vec![f16::ZERO; n * k_blocks];
            for s in scales_gate.iter_mut() {
                *s = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
            }
            let mut scales_up = vec![f16::ZERO; n * k_blocks];
            for s in scales_up.iter_mut() {
                *s = f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5));
            }

            let activation_dev = runtime.alloc_raw(activation_f16.len() * 2).unwrap();
            let gamma_dev = runtime.alloc_raw(gamma_f16.len() * 2).unwrap();
            let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
            let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
            let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
            let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
            let loop_out_dev = runtime.alloc_raw(m * n * 2).unwrap();
            let ref_out_dev = runtime.alloc_raw(n * 2).unwrap();
            // SAFETY: device buffers were sized to hold each source slice.
            unsafe {
                runtime
                    .htod(as_bytes(&activation_f16), activation_dev)
                    .unwrap();
                runtime.htod(as_bytes(&gamma_f16), gamma_dev).unwrap();
                runtime.htod(&packed_gate, packed_gate_dev).unwrap();
                runtime.htod(&packed_up, packed_up_dev).unwrap();
                runtime
                    .htod(as_bytes(&scales_gate), scales_gate_dev)
                    .unwrap();
                runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
            }

            let device = DeviceId::cuda(0);
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let scales_shape = [n, k_blocks];
            let scales_strides = [k_blocks as i64, 1];
            let packed_gate_view = TensorView::new(
                device_ptr(packed_gate_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let packed_up_view = TensorView::new(
                device_ptr(packed_up_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_gate_view = TensorView::new(
                device_ptr(scales_gate_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let scales_up_view = TensorView::new(
                device_ptr(scales_up_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let gamma_shape = [k];
            let gamma_strides = [1i64];
            let gamma_view = TensorView::new(
                device_ptr(gamma_dev),
                DataType::Float16,
                &gamma_shape,
                &gamma_strides,
                device,
            );

            let kernel = MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits: 4,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: false,
                gate_up_swiglu: true,
                decomposed_silu: false,
                rmsnorm_prologue: true,
                rmsnorm_epsilon: 1e-5,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };

            // Batched path: m>1 with gamma present routes through the looped
            // single-row fused rmsnorm decode GEMV.
            let a_shape_m = [m, k];
            let a_strides_m = [k as i64, 1];
            let y_shape_m = [m, n];
            let y_strides_m = [n as i64, 1];
            let inputs_m = [
                TensorView::new(
                    device_ptr(activation_dev),
                    DataType::Float16,
                    &a_shape_m,
                    &a_strides_m,
                    device,
                ),
                packed_gate_view,
                scales_gate_view,
                packed_up_view,
                scales_up_view,
                gamma_view,
            ];
            {
                let mut outputs_m = [TensorMut::new(
                    device_ptr_mut(loop_out_dev),
                    DataType::Float16,
                    &y_shape_m,
                    &y_strides_m,
                    device,
                )];
                kernel
                    .run_f16_gate_up_swiglu(&inputs_m, &mut outputs_m, None)
                    .unwrap();
                runtime.synchronize().unwrap();
            }
            assert!(
                kernel.last_call_capture_safe.load(Ordering::Relaxed),
                "looped rmsnorm gate/up SwiGLU decode must report capture-safe (K={k} N={n})"
            );
            let mut loop_out = vec![f16::ZERO; m * n];
            // SAFETY: `loop_out_dev` holds `m * n` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut loop_out), loop_out_dev)
                    .unwrap();
            }

            // Reference: run each row alone as an independent M==1 fused rmsnorm
            // gate/up SwiGLU decode over the same weights, gamma, and the same
            // (offset) activation row.
            let mut ref_out = vec![f16::ZERO; m * n];
            for r in 0..m {
                let a_off = (r * k * 2) as CUdeviceptr;
                let a_shape_1 = [1usize, k];
                let a_strides_1 = [k as i64, 1];
                let y_shape_1 = [1usize, n];
                let y_strides_1 = [n as i64, 1];
                let inputs_1 = [
                    TensorView::new(
                        device_ptr(activation_dev + a_off),
                        DataType::Float16,
                        &a_shape_1,
                        &a_strides_1,
                        device,
                    ),
                    packed_gate_view,
                    scales_gate_view,
                    packed_up_view,
                    scales_up_view,
                    gamma_view,
                ];
                let mut outputs_1 = [TensorMut::new(
                    device_ptr_mut(ref_out_dev),
                    DataType::Float16,
                    &y_shape_1,
                    &y_strides_1,
                    device,
                )];
                kernel
                    .run_f16_gate_up_swiglu(&inputs_1, &mut outputs_1, None)
                    .unwrap();
                runtime.synchronize().unwrap();
                // SAFETY: `ref_out_dev` holds `n` fp16 values.
                unsafe {
                    runtime
                        .dtoh(as_bytes_mut(&mut ref_out[r * n..(r + 1) * n]), ref_out_dev)
                        .unwrap();
                }
            }

            // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
            unsafe {
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(gamma_dev).unwrap();
                runtime.free_raw(packed_gate_dev).unwrap();
                runtime.free_raw(packed_up_dev).unwrap();
                runtime.free_raw(scales_gate_dev).unwrap();
                runtime.free_raw(scales_up_dev).unwrap();
                runtime.free_raw(loop_out_dev).unwrap();
                runtime.free_raw(ref_out_dev).unwrap();
            }

            let mismatches = loop_out
                .iter()
                .zip(ref_out.iter())
                .filter(|(a, b)| a.to_bits() != b.to_bits())
                .count();
            assert_eq!(
                mismatches,
                0,
                "looped batch-{m} rmsnorm gate/up SwiGLU decode diverged from per-row \
                 single-stream decode at K={k} N={n}: {mismatches}/{} fp16 outputs differ",
                m * n
            );
        }
    }

    /// no other Qwen2.5 size hits: gate/up is K=1536,N=8960 (K<N → *general*
    /// GEMV) and the down-projection is K=8960,N=1536 (K>N → *tall-skinny*
    /// specialized GEMV). K=1536 is 48 block-32 groups and N=8960 is a whole
    /// multiple of the 8-column CTA width, exercising the block-count and column
    /// tiling boundaries at the exact production shapes. Both variants must track
    /// the f64 dequant-and-matmul oracle within the fp16 accumulation floor so a
    /// future kernel change cannot silently reintroduce a decode-step logit
    /// divergence at these dims.
    #[test]
    fn fp16_gemv_matches_dequant_reference_qwen_1_5b_dims() {
        // (k, n) → (gate/up general GEMV, down-projection tall-skinny GEMV).
        for (k, n) in [(1536usize, 8960usize), (8960usize, 1536usize)] {
            let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
                (0.0f32, 0.0f32, 0.0f32, true);
            for (scales_fp16, with_bias) in [(false, false), (true, false), (true, true)] {
                let (abs, rel, out, finite) = run_parity_dims(k, n, scales_fp16, with_bias, false);
                worst_abs = worst_abs.max(abs);
                worst_rel = worst_rel.max(rel);
                max_out = max_out.max(out);
                all_finite &= finite;
            }
            // Same fp16-ULP-scaled magnitude bound as the general parity test.
            // K here runs deeper (up to 8960), but the observed error stays
            // within that floor, so no extra slack is needed.
            let abs_bound = (max_out * 1e-3).max(1e-3);
            eprintln!(
                "MatMulNBits fp16 GEMV parity K={k} N={n}: max_abs={worst_abs:.3e} \
                 max_rel={worst_rel:.3e} max_out={max_out:.3e} abs_bound={abs_bound:.3e}"
            );
            assert!(
                all_finite,
                "fp16 GEMV produced a non-finite output (K={k} N={n})"
            );
            assert!(
                worst_abs < abs_bound,
                "fp16 GEMV diverged from dequant reference at K={k} N={n}: \
                 max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
            );
            assert!(
                worst_rel < 5e-2,
                "fp16 GEMV diverged from dequant reference at K={k} N={n}: max_rel={worst_rel:.3e}"
            );
        }
    }

    /// Model-agnostic block-size guard: the general-block-size fp16 decode GEMV
    /// (`matmul_nbits_gemv_f16_general_bs`, selected for any `block_size != 32`)
    /// must track the same f64 dequant-and-matmul oracle as the tuned block-32
    /// path. Exercised at `block_size = 128` — the Qwen2.5-0.5B **v4-bs128**
    /// foundry package's layout that previously failed to load — across the
    /// exact q/k/v/o/gate/up/down projection dims (K=896, and the wide MLP
    /// K=4864), a ragged-N tail, and both fp16/fp32 scales with and without a
    /// folded bias. It also drives an explicit **asymmetric** per-block int4
    /// zero-point tensor so a zero-point indexing regression in the general
    /// kernel's dequant path is caught (plausible for zp-bearing non-32-block
    /// models). A regression in the general block-index math (scale/zp stride,
    /// K-stepping, or nibble unpack) would diverge here.
    #[test]
    fn fp16_gemv_matches_dequant_reference_block128() {
        // (block_size, k, n): block-128 covers the Qwen2.5-0.5B bs128 attention
        // and MLP projection shapes (K=896, wide MLP K=4864) plus a ragged N
        // (70) spanning several 8-column CTAs with a partial tail; block-64
        // proves the block index math generalizes beyond a single width. All K
        // are whole multiples of their block size.
        for (block_size, k, n) in [
            (128usize, 896usize, 896usize),
            (128usize, 896usize, 4864usize),
            (128usize, 4864usize, 896usize),
            (128usize, 896usize, 70usize),
            (64usize, 896usize, 896usize),
            (64usize, 896usize, 70usize),
        ] {
            // Any block_size != 32 must route through the general kernel.
            assert_eq!(
                select_f16_gemv_variant(k, n, block_size, true, false).variant,
                F16GemvVariant::General,
                "block_size={block_size} K={k} N={n} must select the general variant"
            );
            let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
                (0.0f32, 0.0f32, 0.0f32, true);
            // (scales_fp16, with_bias, explicit_zp): the last two rows exercise
            // the general kernel's asymmetric int4 zero-point dequant path.
            for (scales_fp16, with_bias, explicit_zp) in [
                (false, false, false),
                (true, false, false),
                (true, true, false),
                (false, false, true),
                (true, true, true),
            ] {
                let (abs, rel, out, finite) =
                    run_parity_dims_block(k, n, block_size, scales_fp16, with_bias, explicit_zp);
                worst_abs = worst_abs.max(abs);
                worst_rel = worst_rel.max(rel);
                max_out = max_out.max(out);
                all_finite &= finite;
            }
            // Same fp16-ULP-scaled magnitude bound as the block-32 parity tests;
            // a wider block shares one scale across more K-elements but the oracle
            // uses the identical dequant, so the accumulation floor is unchanged.
            let abs_bound = (max_out * 1e-3).max(1e-3);
            eprintln!(
                "MatMulNBits fp16 GEMV block-{block_size} parity K={k} N={n}: \
                 max_abs={worst_abs:.3e} max_rel={worst_rel:.3e} max_out={max_out:.3e} \
                 abs_bound={abs_bound:.3e}"
            );
            assert!(
                all_finite,
                "block-{block_size} fp16 GEMV produced a non-finite output (K={k} N={n})"
            );
            assert!(
                worst_abs < abs_bound,
                "block-{block_size} fp16 GEMV diverged from dequant reference at K={k} N={n}: \
                 max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
            );
            assert!(
                worst_rel < 5e-2,
                "block-{block_size} fp16 GEMV diverged from dequant reference at K={k} N={n}: \
                 max_rel={worst_rel:.3e}"
            );
        }
    }

    /// Asymmetric-zero-point int4 fp16 decode GEMV at Phi-4-mini's int4 dims
    /// must track an f64 dequant oracle that honors the per-block zero point.
    /// Phi carries explicit zero points on every MatMulNBits, so the vectorized
    /// `scales_f16` GEMV that decode routes to (o_proj K=3072,N=3072 and the
    /// gate/up projection K=3072,N=8192) must dequantize `(code - zp) * scale`,
    /// not the symmetric `(code - 8)`. This is the mutation guard for the shared
    /// `int4x8_to_half2x4_sub` primitive: a kernel that ignored the zero point
    /// (subtracting the implicit 8) would diverge from the oracle far beyond the
    /// fp16 floor and fail here.
    #[test]
    fn fp16_gemv_matches_dequant_reference_phi_int4_zp_dims() {
        // (K, N): Phi o_proj (K==N general GEMV) and gate/up (K<N general GEMV).
        for (k, n) in [(3072usize, 3072usize), (3072, 8192)] {
            let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
                (0.0f32, 0.0f32, 0.0f32, true);
            // Exercise both the plain asymmetric GEMV and the folded-bias
            // (residual) epilogue that the skip-rmsnorm fusion produces on the
            // preceding projection. Routed through `run_parity_dims` (block-32
            // default) so the `explicit_zp` delegation is actually driven.
            for (with_bias, explicit_zp) in [(false, true), (true, true)] {
                let (abs, rel, out, finite) = run_parity_dims(k, n, true, with_bias, explicit_zp);
                worst_abs = worst_abs.max(abs);
                worst_rel = worst_rel.max(rel);
                max_out = max_out.max(out);
                all_finite &= finite;
            }
            let abs_bound = (max_out * 1e-3).max(1e-3);
            eprintln!(
                "MatMulNBits int4 asymmetric-zp GEMV parity K={k} N={n}: max_abs={worst_abs:.3e} \
                 max_rel={worst_rel:.3e} max_out={max_out:.3e} abs_bound={abs_bound:.3e}"
            );
            assert!(
                all_finite,
                "int4 asymmetric-zp GEMV produced a non-finite output (K={k} N={n})"
            );
            assert!(
                worst_abs < abs_bound,
                "int4 asymmetric-zp GEMV diverged from dequant reference at K={k} N={n}: \
                 max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
            );
            assert!(
                worst_rel < 5e-2,
                "int4 asymmetric-zp GEMV diverged from dequant reference at K={k} N={n}: \
                 max_rel={worst_rel:.3e}"
            );
        }
    }

    /// The GQA k/v projection routes to the deep-split asymmetric GEMV entry, so
    /// it needs its own oracle check: `K_SPLIT=8` adds a second level of fp32
    /// partial accumulation that `K_SPLIT=2` does not have, and a wrong
    /// `columns_per_block` there does not crash -- it silently drops output
    /// columns, which the oracle catches at `max_rel = 1.0` (verified by
    /// building the mismatch on purpose). Note what it does NOT catch: making
    /// the kernel's `K_SPLIT` SMALLER than the launch believes is numerically
    /// benign, because every column still gets computed, just redundantly. Only
    /// the column-dropping direction is a correctness bug, and only that
    /// direction is guarded here.
    ///
    /// K=6656, N=256 is this repo's 30B model, whose grouped-query attention
    /// makes the k and v projections 16x narrower than q.
    #[test]
    fn fp16_gemv_matches_dequant_reference_gqa_kv_deep_split_dims() {
        let (k, n) = (6656usize, 256usize);
        let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
            (0.0f32, 0.0f32, 0.0f32, true);
        for (with_bias, explicit_zp) in [(false, true), (true, true)] {
            let (abs, rel, out, finite) = run_parity_dims(k, n, true, with_bias, explicit_zp);
            worst_abs = worst_abs.max(abs);
            worst_rel = worst_rel.max(rel);
            max_out = max_out.max(out);
            all_finite &= finite;
        }
        let abs_bound = (max_out * 1e-3).max(1e-3);
        eprintln!(
            "MatMulNBits GQA k/v deep-split GEMV parity K={k} N={n}: max_abs={worst_abs:.3e} \
             max_rel={worst_rel:.3e} max_out={max_out:.3e} abs_bound={abs_bound:.3e}"
        );
        assert!(
            all_finite,
            "GQA k/v deep-split GEMV produced a non-finite output"
        );
        assert!(
            worst_abs < abs_bound,
            "GQA k/v deep-split GEMV diverged from dequant reference: \
             max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
        );
        assert!(
            worst_rel < 5e-2,
            "GQA k/v deep-split GEMV diverged from dequant reference: max_rel={worst_rel:.3e}"
        );
    }

    /// `scales_f16_zp_split_factor` must never ask for more K-slices than the
    /// launch has warps, because the launch derives `columns_per_block` by
    /// dividing one by the other and a zero there produces a zero-sized grid --
    /// a kernel that never runs, leaving the output tensor holding stale bytes.
    /// It must also actually deepen on the shape it exists for, and leave the
    /// shapes that already fill the device alone.
    #[test]
    fn zp_split_factor_deepens_only_for_starved_grids_and_keeps_a_column_per_block() {
        let warps = (GEMV_F16_LARGE_THREADS / 32) as usize;
        // The GQA k/v projection: 64 blocks at the default factor on an A100.
        assert_eq!(
            scales_f16_zp_split_factor(256, 108),
            GEMV_F16_SCALES_F16_ZP_SPLITK8
        );
        // q and the wider projections already saturate; leave them at the tuned
        // default rather than paying for partial reductions they do not need.
        for n in [4096usize, 6656, 19968, 202048] {
            assert_eq!(
                scales_f16_zp_split_factor(n, 108),
                GEMV_F16_SCALES_F16_ZP_SPLITK,
                "N={n} fills the grid at the default split and must not deepen"
            );
        }
        // Invariant across every width and every plausible device size.
        for mp in [1u32, 16, 80, 108, 132, 148, 256] {
            for n in [1usize, 2, 8, 64, 256, 257, 431, 432, 433, 4096, 202048] {
                let factor = scales_f16_zp_split_factor(n, mp);
                assert!(
                    factor <= warps && warps.is_multiple_of(factor),
                    "N={n} mp={mp} produced factor {factor}, which does not divide {warps} warps"
                );
            }
        }
    }

    /// Int8 (bits=8) fp16 decode GEMV must track an f64 dequant oracle at Phi's
    /// GEMV dims — the shapes ORT beat us on. QKV (K=3072, N=5120), down
    /// projection (K=8192, N=3072), and the lm_head slice (K=3072, wide N) all
    /// exercise the vectorised four-lane/eight-block path; a ragged N tail and
    /// an explicit-zero-point case guard the reduction and dequant edges.
    #[test]
    fn int8_fp16_gemv_matches_dequant_reference_phi_dims() {
        let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
            (0.0f32, 0.0f32, 0.0f32, true);
        // (K, N, scales_fp16, with_bias, explicit_zp)
        let cases = [
            (3072usize, 5120usize, true, false, false), // Phi QKV int8
            (8192, 3072, true, false, false),           // Phi down projection int8
            (3072, 5120, true, true, false),            // QKV with folded bias
            (3072, 5120, true, false, true),            // explicit per-block zero points
            (8192, 3072, true, false, true),            // down-proj zp: exercises split-K at K=8192
            (3072, 5121, true, false, false),           // ragged N tail (not warp-tile aligned)
            (8192, 3072, false, false, false),          // fp32 scales
        ];
        for (k, n, scales_fp16, with_bias, explicit_zp) in cases {
            let (abs, rel, out, finite) =
                run_int8_parity_dims(k, n, 32, scales_fp16, with_bias, explicit_zp);
            worst_abs = worst_abs.max(abs);
            worst_rel = worst_rel.max(rel);
            max_out = max_out.max(out);
            all_finite &= finite;
        }
        // int8 quant codes span 0..255 so accumulated magnitudes (and thus the
        // fp16 output ULP floor) are larger than the int4 case; keep the same
        // magnitude-relative bound shape with headroom for K up to 8192.
        let abs_bound = (max_out * 2e-3).max(1e-3);
        eprintln!(
            "MatMulNBits int8 fp16 GEMV parity: max_abs={worst_abs:.3e} max_rel={worst_rel:.3e} \
             max_out={max_out:.3e} abs_bound={abs_bound:.3e}"
        );
        assert!(all_finite, "int8 fp16 GEMV produced a non-finite output");
        assert!(
            worst_abs < abs_bound,
            "int8 fp16 GEMV diverged from dequant reference: max_abs={worst_abs:.3e} \
             bound={abs_bound:.3e}"
        );
        assert!(
            worst_rel < 5e-2,
            "int8 fp16 GEMV diverged from dequant reference: max_rel={worst_rel:.3e}"
        );
    }

    /// Int8 (bits=8) fp16 decode GEMV at non-block-32 power-of-two block widths
    /// must route through the model-agnostic general-block-size kernel and track
    /// an f64 dequant oracle. This is the coverage guard for the Foundry
    /// Qwen3-0.6B artifact, whose 105 `MatMulNBits(bits=8, block_size=128)` nodes
    /// (e.g. the wide MLP down projection K=3072, and QKV/attention shapes) the
    /// old factory rejected — forcing the whole session onto the CPU EP. The
    /// block-64 rows prove the block-index math generalizes beyond a single
    /// width, and the ragged-N / explicit-zero-point rows guard the reduction
    /// tail and the asymmetric uint8 zero-point dequant.
    #[test]
    fn int8_fp16_gemv_matches_dequant_reference_block128() {
        // (block_size, k, n): all K are whole multiples of their block size.
        for (block_size, k, n) in [
            (128usize, 1024usize, 1024usize), // Qwen3-style square projection
            (128, 3072, 1024),                // tall-skinny down projection (K > N)
            (128, 1024, 3072),                // wide projection (N > K)
            (128, 1024, 1030),                // ragged N tail across CTAs
            (64, 1024, 1024),                 // block-64 generalization
        ] {
            // Any block_size != 32 must select the general variant.
            assert_eq!(
                select_f16_gemv_variant(k, n, block_size, true, false).variant,
                F16GemvVariant::General,
                "int8 block_size={block_size} K={k} N={n} must select the general variant"
            );
            let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
                (0.0f32, 0.0f32, 0.0f32, true);
            // (scales_fp16, with_bias, explicit_zp): cover fp16/fp32 scales, the
            // folded-bias epilogue, and the asymmetric uint8 zero-point path.
            for (scales_fp16, with_bias, explicit_zp) in [
                (true, false, false),
                (false, false, false),
                (true, true, false),
                (true, false, true),
            ] {
                let (abs, rel, out, finite) =
                    run_int8_parity_dims(k, n, block_size, scales_fp16, with_bias, explicit_zp);
                worst_abs = worst_abs.max(abs);
                worst_rel = worst_rel.max(rel);
                max_out = max_out.max(out);
                all_finite &= finite;
            }
            let abs_bound = (max_out * 2e-3).max(1e-3);
            eprintln!(
                "MatMulNBits int8 fp16 GEMV block-{block_size} parity K={k} N={n}: \
                 max_abs={worst_abs:.3e} max_rel={worst_rel:.3e} max_out={max_out:.3e} \
                 abs_bound={abs_bound:.3e}"
            );
            assert!(
                all_finite,
                "int8 block-{block_size} fp16 GEMV produced a non-finite output (K={k} N={n})"
            );
            assert!(
                worst_abs < abs_bound,
                "int8 block-{block_size} fp16 GEMV diverged from dequant reference at K={k} \
                 N={n}: max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
            );
            assert!(
                worst_rel < 5e-2,
                "int8 block-{block_size} fp16 GEMV diverged from dequant reference at K={k} \
                 N={n}: max_rel={worst_rel:.3e}"
            );
        }
    }

    /// Int8 (bits=8) **fp32-activation** decode GEMV harness. The Foundry
    /// Qwen3-0.6B artifact emits fp32 activations, so its 105
    /// `MatMulNBits(bits=8, block_size=128)` decode nodes take the fp32 `run`
    /// path (`launch_f32_gemv` → `matmul_nbits_gemv_f32`), not the fp16
    /// `run_f16` path. This exercises the general-block-size fp32 kernel branch
    /// against an f64 dequant oracle and asserts the launch stays capture-safe.
    fn run_int8_f32_parity_dims(
        k: usize,
        n: usize,
        block_size: usize,
        with_bias: bool,
        explicit_zp: bool,
    ) -> (f32, f32, f32, bool) {
        let Some(runtime) = runtime() else {
            eprintln!("skipping MatMulNBits int8 f32 GEMV parity test: CUDA runtime unavailable");
            return (0.0, 0.0, 0.0, true);
        };

        let k_blocks = k / block_size;
        let blob_size = block_size; // one byte per weight for bits=8

        let mut state = 0x1234_5678_9abc_def0u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation = vec![0.0f32; k];
        for value in activation.iter_mut() {
            *value = next();
        }

        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for within in 0..block_size {
                    packed[(col * k_blocks + block) * blob_size + within] =
                        quant[col * k + block * block_size + within];
                }
            }
        }

        let mut zero_points = vec![0u8; n * k_blocks];
        if explicit_zp {
            for zp in zero_points.iter_mut() {
                *zp = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
            }
        }
        let zp_ref = |col: usize, block: usize| -> i32 {
            if explicit_zp {
                zero_points[col * k_blocks + block] as i32
            } else {
                128
            }
        };

        let mut scale = vec![0.0f32; n * k_blocks];
        for value in scale.iter_mut() {
            *value = 0.015 + 0.01 * (next() * 0.5 + 0.5);
        }

        let mut bias = vec![0.0f32; n];
        if with_bias {
            for value in bias.iter_mut() {
                *value = next();
            }
        }

        let mut expected = vec![0.0f32; n];
        for col in 0..n {
            let mut acc = 0.0f64;
            for block in 0..k_blocks {
                let s = scale[col * k_blocks + block] as f64;
                let zp = zp_ref(col, block);
                for within in 0..block_size {
                    let depth = block * block_size + within;
                    let q = quant[col * k + depth] as i32 - zp;
                    acc += activation[depth] as f64 * q as f64 * s;
                }
            }
            if with_bias {
                acc += bias[col] as f64;
            }
            expected[col] = acc as f32;
        }

        let activation_dev = runtime.alloc_raw(activation.len() * 4).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scale.len() * 4).unwrap();
        let zp_dev = runtime.alloc_raw(zero_points.len().max(1)).unwrap();
        let bias_dev = runtime.alloc_raw(n * 4).unwrap();
        let output_dev = runtime.alloc_raw(n * 4).unwrap();

        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scale), scales_dev).unwrap();
            if explicit_zp {
                runtime.htod(&zero_points, zp_dev).unwrap();
            }
            if with_bias {
                runtime.htod(as_bytes(&bias), bias_dev).unwrap();
            }
        }

        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, k_blocks];
        let zp_strides = [k_blocks as i64, 1];
        let bias_shape = [n];
        let bias_strides = [1i64];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];

        let device = DeviceId::cuda(0);
        let mut inputs = vec![
            TensorView::new(
                device_ptr(activation_dev),
                DataType::Float32,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::Float32,
                &scales_shape,
                &scales_strides,
                device,
            ),
        ];
        if explicit_zp || with_bias {
            inputs.push(if explicit_zp {
                TensorView::new(
                    device_ptr(zp_dev),
                    DataType::Uint8,
                    &zp_shape,
                    &zp_strides,
                    device,
                )
            } else {
                TensorView::absent(DataType::Uint8)
            });
        }
        if with_bias {
            inputs.push(TensorView::absent(DataType::Int32));
            inputs.push(TensorView::new(
                device_ptr(bias_dev),
                DataType::Float32,
                &bias_shape,
                &bias_strides,
                device,
            ));
        }

        let mut outputs = [TensorMut::new(
            device_ptr_mut(output_dev),
            DataType::Float32,
            &y_shape,
            &y_strides,
            device,
        )];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 8,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        kernel.run(&inputs, &mut outputs, None).unwrap();
        runtime.synchronize().unwrap();

        assert!(
            kernel.last_call_capture_safe.load(Ordering::Relaxed),
            "int8 f32 decode GEMV must report capture-safe"
        );

        let mut got = vec![0.0f32; n];
        // SAFETY: `output_dev` holds `n` fp32 values.
        unsafe {
            runtime.dtoh(as_bytes_mut(&mut got), output_dev).unwrap();
        }

        // SAFETY: each pointer came from this runtime's `alloc_raw` and is freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(bias_dev).unwrap();
            runtime.free_raw(output_dev).unwrap();
        }

        let mut worst_abs = 0.0f32;
        let mut worst_rel = 0.0f32;
        let mut max_out = 0.0f32;
        let mut all_finite = true;
        for (g, e) in got.iter().zip(expected.iter()) {
            if !g.is_finite() {
                all_finite = false;
            }
            let abs = (g - e).abs();
            let rel = abs / e.abs().max(1e-1);
            worst_abs = worst_abs.max(abs);
            worst_rel = worst_rel.max(rel);
            max_out = max_out.max(e.abs());
        }
        (worst_abs, worst_rel, max_out, all_finite)
    }

    /// The Foundry Qwen3-0.6B fp32-activation int8/block-128 decode GEMV must
    /// track an f64 dequant oracle through the general-block-size fp32 kernel.
    /// This is the direct unit guard for the path the real artifact takes at
    /// decode (fp32 activations, `bits=8`, `block_size=128`).
    #[test]
    fn int8_f32_gemv_matches_dequant_reference_block128() {
        for (block_size, k, n) in [
            (128usize, 1024usize, 1024usize), // Qwen3-style square projection
            (128, 3072, 1024),                // tall-skinny down projection (K > N)
            (128, 1024, 3072),                // wide projection (N > K)
            (128, 1024, 1030),                // ragged N tail across CTAs
            (64, 1024, 1024),                 // block-64 generalization
        ] {
            let (mut worst_abs, mut worst_rel, mut max_out, mut all_finite) =
                (0.0f32, 0.0f32, 0.0f32, true);
            for (with_bias, explicit_zp) in [(false, false), (true, false), (false, true)] {
                let (abs, rel, out, finite) =
                    run_int8_f32_parity_dims(k, n, block_size, with_bias, explicit_zp);
                worst_abs = worst_abs.max(abs);
                worst_rel = worst_rel.max(rel);
                max_out = max_out.max(out);
                all_finite &= finite;
            }
            let abs_bound = (max_out * 2e-3).max(1e-3);
            eprintln!(
                "MatMulNBits int8 f32 GEMV block-{block_size} parity K={k} N={n}: \
                 max_abs={worst_abs:.3e} max_rel={worst_rel:.3e} max_out={max_out:.3e} \
                 abs_bound={abs_bound:.3e}"
            );
            assert!(
                all_finite,
                "int8 block-{block_size} f32 GEMV produced a non-finite output (K={k} N={n})"
            );
            assert!(
                worst_abs < abs_bound,
                "int8 block-{block_size} f32 GEMV diverged from dequant reference at K={k} \
                 N={n}: max_abs={worst_abs:.3e} bound={abs_bound:.3e}"
            );
            assert!(
                worst_rel < 5e-2,
                "int8 block-{block_size} f32 GEMV diverged from dequant reference at K={k} \
                 N={n}: max_rel={worst_rel:.3e}"
            );
        }
    }

    /// Runs a structurally-selected block-128 specialization and the generic
    /// `matmul_nbits_gemv_f32` kernel on identical device buffers and
    /// returns `(mismatching_columns, all_finite)`. The specialization only
    /// rewrites address arithmetic (shift instead of divide/modulo, hoisted
    /// per-column base, dropped bit-width branch) — the per-thread depth stride,
    /// per-element fp32 expression, and block reduction are unchanged, so every
    /// output column must be **bit-for-bit identical**. Includes partial final
    /// K-blocks (`k` not a multiple of 128) to exercise the padded weight row.
    fn run_f32_block128_byte_identity(
        bits: usize,
        k: usize,
        n: usize,
        with_bias: bool,
        explicit_zp: bool,
    ) -> (usize, bool) {
        let Some(runtime) = runtime() else {
            eprintln!(
                "skipping MatMulNBits int{bits} f32 block-128 byte-identity test: CUDA runtime unavailable"
            );
            return (0, true);
        };

        let block_size = 128usize;
        let k_blocks = k.div_ceil(block_size);
        let blob_size = block_size * bits / 8;
        let zp_row_bytes = (k_blocks * bits).div_ceil(8);

        let mut state = 0x0bad_c0de_1234_5678u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let mut activation = vec![0.0f32; k];
        for value in activation.iter_mut() {
            *value = next();
        }

        // Packed weights are stored per padded K-block row (`k_blocks * blob_size`
        // bytes per column); only depths `< k` are ever read.
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for value in packed.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
        }

        let mut zero_points = vec![0u8; n * zp_row_bytes];
        if explicit_zp {
            for zp in zero_points.iter_mut() {
                *zp = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
            }
        }

        let mut scale = vec![0.0f32; n * k_blocks];
        for value in scale.iter_mut() {
            *value = 0.015 + 0.01 * (next() * 0.5 + 0.5);
        }

        let mut bias = vec![0.0f32; n];
        if with_bias {
            for value in bias.iter_mut() {
                *value = next();
            }
        }

        let activation_dev = runtime.alloc_raw(activation.len() * 4).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scale.len() * 4).unwrap();
        let zp_dev = runtime.alloc_raw(zero_points.len().max(1)).unwrap();
        let bias_dev = runtime.alloc_raw(n * 4).unwrap();
        let spec_dev = runtime.alloc_raw(n * 4).unwrap();
        let generic_dev = runtime.alloc_raw(n * 4).unwrap();

        // SAFETY: device buffers were sized to hold each source slice.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scale), scales_dev).unwrap();
            if explicit_zp {
                runtime.htod(&zero_points, zp_dev).unwrap();
            }
            if with_bias {
                runtime.htod(as_bytes(&bias), bias_dev).unwrap();
            }
        }

        let device = DeviceId::cuda(0);
        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, zp_row_bytes];
        let zp_strides = [zp_row_bytes as i64, 1];
        let bias_shape = [n];
        let bias_strides = [1i64];

        let activation_view = TensorView::new(
            device_ptr(activation_dev),
            DataType::Float32,
            &a_shape,
            &a_strides,
            device,
        );
        let packed_view = TensorView::new(
            device_ptr(packed_dev),
            DataType::Uint8,
            &b_shape,
            &b_strides,
            device,
        );
        let scales_view = TensorView::new(
            device_ptr(scales_dev),
            DataType::Float32,
            &scales_shape,
            &scales_strides,
            device,
        );
        let zp_view = explicit_zp.then(|| {
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            )
        });
        let bias_view = with_bias.then(|| {
            TensorView::new(
                device_ptr(bias_dev),
                DataType::Float32,
                &bias_shape,
                &bias_strides,
                device,
            )
        });

        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];
        let mut spec_out = TensorMut::new(
            device_ptr_mut(spec_dev),
            DataType::Float32,
            &y_shape,
            &y_strides,
            device,
        );
        let mut generic_out = TensorMut::new(
            device_ptr_mut(generic_dev),
            DataType::Float32,
            &y_shape,
            &y_strides,
            device,
        );

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        match bits {
            4 => kernel
                .launch_int4_f32_gemv_block128(
                    &activation_view,
                    &packed_view,
                    &scales_view,
                    zp_view
                        .as_ref()
                        .expect("int4 block-128 specialization requires zero points"),
                    bias_view.as_ref(),
                    &mut spec_out,
                    k_blocks,
                )
                .unwrap(),
            8 => kernel
                .launch_int8_f32_gemv_block128(
                    &activation_view,
                    &packed_view,
                    &scales_view,
                    zp_view.as_ref(),
                    bias_view.as_ref(),
                    &mut spec_out,
                    k_blocks,
                )
                .unwrap(),
            _ => unreachable!("byte-identity harness only supports int4/int8"),
        }
        kernel
            .launch_f32_gemv(
                &activation_view,
                &packed_view,
                &scales_view,
                zp_view.as_ref(),
                bias_view.as_ref(),
                &mut generic_out,
                k_blocks,
                blob_size,
                zp_row_bytes,
            )
            .unwrap();
        runtime.synchronize().unwrap();

        let mut spec = vec![0.0f32; n];
        let mut generic = vec![0.0f32; n];
        // SAFETY: both device buffers hold `n` fp32 values.
        unsafe {
            runtime.dtoh(as_bytes_mut(&mut spec), spec_dev).unwrap();
            runtime
                .dtoh(as_bytes_mut(&mut generic), generic_dev)
                .unwrap();
        }

        // SAFETY: each pointer came from this runtime's `alloc_raw`, freed once.
        unsafe {
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(zp_dev).unwrap();
            runtime.free_raw(bias_dev).unwrap();
            runtime.free_raw(spec_dev).unwrap();
            runtime.free_raw(generic_dev).unwrap();
        }

        let mut mismatches = 0usize;
        let mut all_finite = true;
        for (s, g) in spec.iter().zip(generic.iter()) {
            if !s.is_finite() {
                all_finite = false;
            }
            if s.to_bits() != g.to_bits() {
                mismatches += 1;
            }
        }
        (mismatches, all_finite)
    }

    /// The specialized int8/block-128 asymmetric decode GEMV must be
    /// **bit-for-bit identical** to the generic `matmul_nbits_gemv_f32` it
    /// replaces for Qwen3-0.6B's dominant projection — greedy decode tokens must
    /// not shift. Covers square/tall/wide projections, ragged-N tails, and
    /// partial final K-blocks, with and without an explicit asymmetric zero
    /// point and bias.
    #[test]
    fn int8_f32_block128_specialization_is_bit_identical_to_generic() {
        for (k, n) in [
            (1024usize, 1024usize), // Qwen3-style square projection
            (3072, 1024),           // tall-skinny down projection (K > N)
            (1024, 3072),           // wide projection (N > K)
            (1024, 1030),           // ragged N tail across CTAs
            (1000, 1024),           // partial final K-block (k % 128 != 0)
            (896, 1027),            // partial N and exact K-blocks
        ] {
            for (with_bias, explicit_zp) in [(true, true), (false, true), (true, false)] {
                let (mismatches, all_finite) =
                    run_f32_block128_byte_identity(8, k, n, with_bias, explicit_zp);
                assert!(
                    all_finite,
                    "int8 block-128 specialization produced a non-finite output \
                     (K={k} N={n} bias={with_bias} zp={explicit_zp})"
                );
                assert_eq!(
                    mismatches, 0,
                    "int8 block-128 specialization diverged from the generic GEMV in \
                     {mismatches} column(s) (K={k} N={n} bias={with_bias} zp={explicit_zp}) — \
                     output must be bit-for-bit identical"
                );
            }
        }
    }

    /// The asymmetric int4/block-128 specialization must exactly match the
    /// generic fp32 GEMV, including a partial final K-block.
    #[test]
    fn int4_f32_block128_specialization_is_bit_identical_to_generic() {
        let (mismatches, all_finite) = run_f32_block128_byte_identity(4, 259, 37, true, true);
        assert!(
            all_finite,
            "int4 block-128 specialization produced non-finite output"
        );
        assert_eq!(
            mismatches, 0,
            "int4 block-128 specialization diverged from generic GEMV in \
             {mismatches} column(s)"
        );
    }

    /// Folding a standalone `Add(MatMulNBits, bias)` into the GEMV epilogue must
    /// stay **byte-identical** to the original two-op path so greedy decode
    /// tokens do not shift. The two-op path is `fp16(fp16(acc) + bias)`: the
    /// GEMV first rounds its accumulator to fp16, then the elementwise `Add`
    /// rounds again after an fp16 add. This reproduces that exactly by running
    /// the real kernel with no bias (the fp16 GEMV output) and adding the fp16
    /// bias on the host, then asserting the folded-bias kernel matches bit-for-
    /// bit across every output column.
    #[test]
    fn fp16_folded_bias_is_bit_exact_to_two_op_path() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping folded-bias bit-exactness test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping folded-bias bit-exactness test: fp16 NVRTC headers unavailable");
            return;
        }

        // QKV decode shape: K=896, N=1152, symmetric block-32, fp16 scales.
        let k = 896usize;
        let n = 1152usize;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;

        let mut state = 0x1234_5678_9abc_def0u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let activation: Vec<f16> = (0..k).map(|_| f16::from_f32(next())).collect();
        let mut quant = vec![0u8; n * k];
        for value in quant.iter_mut() {
            *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
        }
        let mut packed = vec![0u8; n * k_blocks * blob_size];
        for col in 0..n {
            for block in 0..k_blocks {
                for pair in 0..blob_size {
                    let low = quant[col * k + block * block_size + pair * 2] & 15;
                    let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                    packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                }
            }
        }
        let scales: Vec<f16> = (0..n * k_blocks)
            .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        // Bias with a wide magnitude range so the second fp16 round is exercised.
        let bias: Vec<f16> = (0..n).map(|_| f16::from_f32(next() * 4.0)).collect();

        let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scales.len() * 2).unwrap();
        let bias_dev = runtime.alloc_raw(bias.len() * 2).unwrap();
        let nobias_output_dev = runtime.alloc_raw(n * 2).unwrap();
        let fused_output_dev = runtime.alloc_raw(n * 2).unwrap();
        // SAFETY: device buffers exactly cover their source slices.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scales), scales_dev).unwrap();
            runtime.htod(as_bytes(&bias), bias_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let bias_shape = [n];
        let bias_strides = [1i64];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];
        let activation_view = TensorView::new(
            device_ptr(activation_dev),
            DataType::Float16,
            &a_shape,
            &a_strides,
            device,
        );
        let packed_view = TensorView::new(
            device_ptr(packed_dev),
            DataType::Uint8,
            &b_shape,
            &b_strides,
            device,
        );
        let scales_view = TensorView::new(
            device_ptr(scales_dev),
            DataType::Float16,
            &scales_shape,
            &scales_strides,
            device,
        );
        let bias_view = TensorView::new(
            device_ptr(bias_dev),
            DataType::Float16,
            &bias_shape,
            &bias_strides,
            device,
        );
        let mut nobias_output = TensorMut::new(
            device_ptr_mut(nobias_output_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );
        let mut fused_output = TensorMut::new(
            device_ptr_mut(fused_output_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );

        let selection = select_f16_gemv_variant(k, n, block_size, true, false);
        let kernel_nobias = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        let kernel_fold = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: true,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        kernel_nobias
            .launch_f16_gemv_variant(
                &activation_view,
                &packed_view,
                &scales_view,
                true,
                None,
                None,
                &mut nobias_output,
                k_blocks,
                blob_size,
                k_blocks.div_ceil(2),
                selection,
            )
            .unwrap();
        kernel_fold
            .launch_f16_gemv_variant(
                &activation_view,
                &packed_view,
                &scales_view,
                true,
                None,
                Some(&bias_view),
                &mut fused_output,
                k_blocks,
                blob_size,
                k_blocks.div_ceil(2),
                selection,
            )
            .unwrap();
        runtime.synchronize().unwrap();

        let mut gemv_out = vec![f16::ZERO; n];
        let mut fused_out = vec![f16::ZERO; n];
        // SAFETY: both output allocations hold `n` fp16 values.
        unsafe {
            runtime
                .dtoh(as_bytes_mut(&mut gemv_out), nobias_output_dev)
                .unwrap();
            runtime
                .dtoh(as_bytes_mut(&mut fused_out), fused_output_dev)
                .unwrap();
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_dev).unwrap();
            runtime.free_raw(scales_dev).unwrap();
            runtime.free_raw(bias_dev).unwrap();
            runtime.free_raw(nobias_output_dev).unwrap();
            runtime.free_raw(fused_output_dev).unwrap();
        }

        for col in 0..n {
            // Two-op reference: fp16(fp16(acc) + bias). gemv_out is already the
            // fp16-rounded accumulator, so add the fp16 bias in f32 and round.
            let two_op = f16::from_f32(gemv_out[col].to_f32() + bias[col].to_f32());
            assert_eq!(
                fused_out[col].to_bits(),
                two_op.to_bits(),
                "folded bias diverged at column {col}: fused={:?} two_op={:?} (gemv={:?} bias={:?})",
                fused_out[col],
                two_op,
                gemv_out[col],
                bias[col]
            );
        }
    }

    // Faithful replica of the elementwise `silu_mul_f16` scalar path (which is
    // byte-identical to its half2 path): `fp16(silu(f32(g)) * f32(u))`. Used to
    // build the two-op reference the paired kernel must reproduce bit-for-bit.
    const REF_SILU_MUL_SRC: &str = r#"
#include <cuda_fp16.h>
__device__ float ref_op_silu(float x) {
    if (x >= 0.0f) {
        const float denominator = __fadd_rn(1.0f, (float)exp((double)-x));
        return __fdiv_rn(x, denominator);
    }
    const float e = (float)exp((double)x);
    const float numerator = __fmul_rn(x, e);
    return __fdiv_rn(numerator, __fadd_rn(1.0f, e));
}
extern "C" __global__ void ref_silu_mul_f16(
    const __half* g, const __half* u, __half* y, const int n) {
    const int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        y[i] = __float2half_rn(
            __fmul_rn(ref_op_silu(__half2float(g[i])), __half2float(u[i])));
    }
}
"#;

    /// The paired gate/up SwiGLU path must be byte-identical to running two
    /// standalone MatMulNBits projections and then `silu_mul_f16`. Decode covers
    /// the Qwen shape and an unrelated shape; prefill covers the reported
    /// five-token Qwen case plus M/N tails on a small unrelated shape.
    #[test]
    fn fp16_gate_up_swiglu_is_bit_exact_to_two_op_path() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping gate/up SwiGLU bit-exactness test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping gate/up SwiGLU bit-exactness test: fp16 NVRTC headers unavailable");
            return;
        }

        // (M, K=hidden, N=intermediate): preserve both decode cases, then add
        // Qwen M=5 prefill and unrelated row/column tails.
        for (m, k, n) in [
            (1usize, QWEN_DOWN_N, QWEN_DOWN_K),
            (1, 2048, 5632),
            (5, QWEN_DOWN_N, QWEN_DOWN_K),
            (3, 96, 77),
        ] {
            let block_size = 32usize;
            let k_blocks = k / block_size;
            let blob_size = block_size / 2;

            let mut state = 0x0bad_c0de_dead_beefu64;
            let mut next = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
            };

            let pack = |next: &mut dyn FnMut() -> f32| -> Vec<u8> {
                let mut quant = vec![0u8; n * k];
                for value in quant.iter_mut() {
                    *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
                }
                let mut packed = vec![0u8; n * k_blocks * blob_size];
                for col in 0..n {
                    for block in 0..k_blocks {
                        for pair in 0..blob_size {
                            let low = quant[col * k + block * block_size + pair * 2] & 15;
                            let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                            packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                        }
                    }
                }
                packed
            };

            let activation: Vec<f16> = (0..m * k).map(|_| f16::from_f32(next())).collect();
            let packed_gate = pack(&mut next);
            let scales_gate: Vec<f16> = (0..n * k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();
            let packed_up = pack(&mut next);
            let scales_up: Vec<f16> = (0..n * k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();

            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
            let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
            let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
            let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
            let output_elements = m * n;
            let gate_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
            let up_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
            let ref_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
            let fused_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
            // SAFETY: device buffers exactly cover their source slices.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(&packed_gate, packed_gate_dev).unwrap();
                runtime
                    .htod(as_bytes(&scales_gate), scales_gate_dev)
                    .unwrap();
                runtime.htod(&packed_up, packed_up_dev).unwrap();
                runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
            }

            let device = DeviceId::cuda(0);
            let a_shape = [m, k];
            let a_strides = [k as i64, 1];
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let scales_shape = [n, k_blocks];
            let scales_strides = [k_blocks as i64, 1];
            let y_shape = [m, n];
            let y_strides = [n as i64, 1];
            let activation_view = TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            );
            let packed_gate_view = TensorView::new(
                device_ptr(packed_gate_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_gate_view = TensorView::new(
                device_ptr(scales_gate_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let packed_up_view = TensorView::new(
                device_ptr(packed_up_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_up_view = TensorView::new(
                device_ptr(scales_up_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let mut gate_out = TensorMut::new(
                device_ptr_mut(gate_out_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            );
            let mut up_out = TensorMut::new(
                device_ptr_mut(up_out_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            );
            let fused_out = TensorMut::new(
                device_ptr_mut(fused_out_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            );

            let gemv_kernel = MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits: 4,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: false,
                gate_up_swiglu: false,
                decomposed_silu: false,
                rmsnorm_prologue: false,
                rmsnorm_epsilon: 1e-5,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };
            // Reference: two standalone MatMulNBits projections.
            if m == 1 {
                let selection = select_f16_gemv_variant(k, n, block_size, true, false);
                assert_eq!(
                    selection.variant,
                    F16GemvVariant::General,
                    "gate/up decode projections must use the general GEMV as the reference"
                );
                gemv_kernel
                    .launch_f16_gemv_variant(
                        &activation_view,
                        &packed_gate_view,
                        &scales_gate_view,
                        true,
                        None,
                        None,
                        &mut gate_out,
                        k_blocks,
                        blob_size,
                        k_blocks.div_ceil(2),
                        selection,
                    )
                    .unwrap();
                gemv_kernel
                    .launch_f16_gemv_variant(
                        &activation_view,
                        &packed_up_view,
                        &scales_up_view,
                        true,
                        None,
                        None,
                        &mut up_out,
                        k_blocks,
                        blob_size,
                        k_blocks.div_ceil(2),
                        selection,
                    )
                    .unwrap();
            } else {
                gemv_kernel
                    .launch_f16_gemm(
                        &activation_view,
                        &packed_gate_view,
                        &scales_gate_view,
                        true,
                        None,
                        None,
                        &mut gate_out,
                        m,
                        k_blocks,
                        gemv_kernel.block_size * gemv_kernel.bits / 8,
                        0,
                    )
                    .unwrap();
                gemv_kernel
                    .launch_f16_gemm(
                        &activation_view,
                        &packed_up_view,
                        &scales_up_view,
                        true,
                        None,
                        None,
                        &mut up_out,
                        m,
                        k_blocks,
                        gemv_kernel.block_size * gemv_kernel.bits / 8,
                        0,
                    )
                    .unwrap();
            }
            // Then the reference silu_mul (byte-identical to silu_mul_f16).
            let ref_function = runtime
                .nvrtc_function(
                    "matmul_nbits_ref_silu_mul",
                    REF_SILU_MUL_SRC,
                    "ref_silu_mul_f16",
                )
                .unwrap();
            let gate_out_ptr = cuptr(device_ptr(gate_out_dev).0);
            let up_out_ptr = cuptr(device_ptr(up_out_dev).0);
            let ref_out_ptr = cuptr(device_ptr(ref_out_dev).0);
            let output_elements_i32 = output_elements as i32;
            let mut ref_builder = runtime.stream().launch_builder(&ref_function);
            ref_builder
                .arg(&gate_out_ptr)
                .arg(&up_out_ptr)
                .arg(&ref_out_ptr)
                .arg(&output_elements_i32);
            // SAFETY: all three buffers hold `output_elements` fp16 values.
            unsafe {
                ref_builder.launch(LaunchConfig {
                    grid_dim: (output_elements.div_ceil(256) as u32, 1, 1),
                    block_dim: (256, 1, 1),
                    shared_mem_bytes: 0,
                })
            }
            .unwrap();

            // Subject: exercise the fused node's real M=1/M>1 dispatch.
            let inputs = [
                activation_view,
                packed_gate_view,
                scales_gate_view,
                packed_up_view,
                scales_up_view,
            ];
            let mut outputs = [fused_out];
            gemv_kernel
                .run_f16_gate_up_swiglu(&inputs, &mut outputs, None)
                .unwrap();
            // Plain (gamma=None) gate/up SwiGLU keeps the original strict
            // invariant: ONLY M==1 decode is advertised capture-safe. Unlike the
            // rmsnorm-prologue path (see the companion assertion in
            // `run_fused_gate_up_swiglu_rmsnorm_parity`, narrowed to the per-row
            // decode-GEMV loop window), the plain path is deliberately NOT routed
            // through the small-M per-row loop: a plain fused decode GEMV is
            // measured up to 2 ULP off the two-op decode reference even at M==1
            // (`fp16_gate_up_swiglu_two_op_ulp_bound_sweep`), so looping it at M>1
            // would move plain-path logits by >1 ULP vs the reference two-op path.
            // Plain M>1 therefore still falls to the prefill/Marlin GEMM
            // (capture-unsafe unless Marlin's warm path advertises otherwise),
            // and this invariant stays `m == 1`. Tracked in #1334.
            assert_eq!(
                gemv_kernel.last_call_capture_safe.load(Ordering::Relaxed),
                m == 1,
                "only M=1 decode may be advertised capture-safe"
            );
            runtime.synchronize().unwrap();

            let mut reference = vec![f16::ZERO; output_elements];
            let mut fused = vec![f16::ZERO; output_elements];
            // SAFETY: both output allocations hold `output_elements` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut reference), ref_out_dev)
                    .unwrap();
                runtime
                    .dtoh(as_bytes_mut(&mut fused), fused_out_dev)
                    .unwrap();
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(packed_gate_dev).unwrap();
                runtime.free_raw(scales_gate_dev).unwrap();
                runtime.free_raw(packed_up_dev).unwrap();
                runtime.free_raw(scales_up_dev).unwrap();
                runtime.free_raw(gate_out_dev).unwrap();
                runtime.free_raw(up_out_dev).unwrap();
                runtime.free_raw(ref_out_dev).unwrap();
                runtime.free_raw(fused_out_dev).unwrap();
            }

            let marlin_prefill = m > 1
                && marlin_gemm::marlin_m_gt_1_enabled()
                && marlin_gemm::device_supports_marlin(runtime.capabilities().compute_capability())
                && k.is_multiple_of(16)
                && k.is_multiple_of(block_size);
            let mut max_ulp = 0i64;
            let mut worst = 0usize;
            for index in 0..output_elements {
                let ulp = f16_ulp_diff(fused[index].to_bits(), reference[index].to_bits());
                if ulp > max_ulp {
                    max_ulp = ulp;
                    worst = index;
                }
                if !marlin_prefill {
                    assert_eq!(
                        fused[index].to_bits(),
                        reference[index].to_bits(),
                        "paired gate/up SwiGLU diverged at M={m}, K={k}, N={n}, row={}, \
                         column={}: fused={:?} reference={:?}",
                        index / n,
                        index % n,
                        fused[index],
                        reference[index]
                    );
                }
            }
            if marlin_prefill {
                // On SM80+ the default M>1 gate/up dispatch is the Marlin
                // `mma.sync.aligned.m16n8k16` tensor-core GEMM, while the
                // two-op reference above is the portable 16x16 CUDA-core tiled
                // GEMM. Those are different reduction trees (tensor-core K=16
                // fragments, with per-group scaling around the mma accumulator,
                // vs scalar CUDA-core accumulation), so byte identity is not a
                // valid contract for this branch. Keep this sentinel tight: the
                // deterministic Marlin-vs-tiled gate/up cases covered here are
                // expected to stay within two fp16 representable values.
                assert!(
                    max_ulp <= 2,
                    "paired gate/up SwiGLU Marlin prefill exceeded the measured 2-ULP \
                     sentinel bound at M={m}, K={k}, N={n}, row={}, column={}: fused={:?} \
                     reference={:?}, max_ulp={max_ulp}",
                    worst / n,
                    worst % n,
                    fused[worst],
                    reference[worst]
                );
            }
        }
    }

    /// fp16 ULP distance between two half-precision bit patterns, using a
    /// sign-magnitude → monotone-integer key so that adjacent representable
    /// values are exactly 1 apart. Not meaningful for NaN/Inf; the SwiGLU
    /// sweep bounds its activations so those do not arise.
    fn f16_ulp_diff(a: u16, b: u16) -> i64 {
        let key = |bits: u16| -> i64 {
            let mag = (bits & 0x7fff) as i64;
            if bits & 0x8000 != 0 { -mag } else { mag }
        };
        (key(a) - key(b)).abs()
    }

    /// One (M, K, N, seed) case of the fused gate/up SwiGLU vs two-op reference
    /// comparison. Reference construction is IDENTICAL to
    /// [`fp16_gate_up_swiglu_is_bit_exact_to_two_op_path`]: M==1 uses two
    /// standalone General decode GEMVs, M>1 uses the tiled prefill GEMM, both
    /// followed by the reference silu_mul. Returns
    /// `(max_ulp, elements_with_nonzero_ulp, total_elements)`.
    fn gate_up_swiglu_two_op_ulp_case(
        runtime: &Arc<CudaRuntime>,
        m: usize,
        k: usize,
        n: usize,
        seed: u64,
    ) -> (i64, usize, usize) {
        const REF_SILU_MUL_SRC: &str = r#"
#include <cuda_fp16.h>
__device__ float ref_op_silu(float x) {
    if (x >= 0.0f) {
        const float denominator = __fadd_rn(1.0f, (float)exp((double)-x));
        return __fdiv_rn(x, denominator);
    }
    const float e = (float)exp((double)x);
    const float numerator = __fmul_rn(x, e);
    return __fdiv_rn(numerator, __fadd_rn(1.0f, e));
}
extern "C" __global__ void ref_silu_mul_f16(
    const __half* g, const __half* u, __half* y, const int n) {
    const int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        y[i] = __float2half_rn(
            __fmul_rn(ref_op_silu(__half2float(g[i])), __half2float(u[i])));
    }
}
"#;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;

        let mut state = seed;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };
        let pack = |next: &mut dyn FnMut() -> f32| -> Vec<u8> {
            let mut quant = vec![0u8; n * k];
            for value in quant.iter_mut() {
                *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
            }
            let mut packed = vec![0u8; n * k_blocks * blob_size];
            for col in 0..n {
                for block in 0..k_blocks {
                    for pair in 0..blob_size {
                        let low = quant[col * k + block * block_size + pair * 2] & 15;
                        let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                        packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                    }
                }
            }
            packed
        };

        let activation: Vec<f16> = (0..m * k).map(|_| f16::from_f32(next())).collect();
        let packed_gate = pack(&mut next);
        let scales_gate: Vec<f16> = (0..n * k_blocks)
            .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        let packed_up = pack(&mut next);
        let scales_up: Vec<f16> = (0..n * k_blocks)
            .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();

        let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
        let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
        let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
        let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
        let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
        let output_elements = m * n;
        let gate_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        let up_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        let ref_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        let fused_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        // SAFETY: device buffers exactly cover their source slices.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed_gate, packed_gate_dev).unwrap();
            runtime
                .htod(as_bytes(&scales_gate), scales_gate_dev)
                .unwrap();
            runtime.htod(&packed_up, packed_up_dev).unwrap();
            runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];
        let activation_view = TensorView::new(
            device_ptr(activation_dev),
            DataType::Float16,
            &a_shape,
            &a_strides,
            device,
        );
        let packed_gate_view = TensorView::new(
            device_ptr(packed_gate_dev),
            DataType::Uint8,
            &b_shape,
            &b_strides,
            device,
        );
        let scales_gate_view = TensorView::new(
            device_ptr(scales_gate_dev),
            DataType::Float16,
            &scales_shape,
            &scales_strides,
            device,
        );
        let packed_up_view = TensorView::new(
            device_ptr(packed_up_dev),
            DataType::Uint8,
            &b_shape,
            &b_strides,
            device,
        );
        let scales_up_view = TensorView::new(
            device_ptr(scales_up_dev),
            DataType::Float16,
            &scales_shape,
            &scales_strides,
            device,
        );
        let mut gate_out = TensorMut::new(
            device_ptr_mut(gate_out_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );
        let mut up_out = TensorMut::new(
            device_ptr_mut(up_out_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );
        let fused_out = TensorMut::new(
            device_ptr_mut(fused_out_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );

        let gemv_kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        if m == 1 {
            let selection = select_f16_gemv_variant(k, n, block_size, true, false);
            gemv_kernel
                .launch_f16_gemv_variant(
                    &activation_view,
                    &packed_gate_view,
                    &scales_gate_view,
                    true,
                    None,
                    None,
                    &mut gate_out,
                    k_blocks,
                    blob_size,
                    k_blocks.div_ceil(2),
                    selection,
                )
                .unwrap();
            gemv_kernel
                .launch_f16_gemv_variant(
                    &activation_view,
                    &packed_up_view,
                    &scales_up_view,
                    true,
                    None,
                    None,
                    &mut up_out,
                    k_blocks,
                    blob_size,
                    k_blocks.div_ceil(2),
                    selection,
                )
                .unwrap();
        } else {
            gemv_kernel
                .launch_f16_gemm(
                    &activation_view,
                    &packed_gate_view,
                    &scales_gate_view,
                    true,
                    None,
                    None,
                    &mut gate_out,
                    m,
                    k_blocks,
                    gemv_kernel.block_size * gemv_kernel.bits / 8,
                    0,
                )
                .unwrap();
            gemv_kernel
                .launch_f16_gemm(
                    &activation_view,
                    &packed_up_view,
                    &scales_up_view,
                    true,
                    None,
                    None,
                    &mut up_out,
                    m,
                    k_blocks,
                    gemv_kernel.block_size * gemv_kernel.bits / 8,
                    0,
                )
                .unwrap();
        }
        let ref_function = runtime
            .nvrtc_function(
                "matmul_nbits_ref_silu_mul",
                REF_SILU_MUL_SRC,
                "ref_silu_mul_f16",
            )
            .unwrap();
        let gate_out_ptr = cuptr(device_ptr(gate_out_dev).0);
        let up_out_ptr = cuptr(device_ptr(up_out_dev).0);
        let ref_out_ptr = cuptr(device_ptr(ref_out_dev).0);
        let output_elements_i32 = output_elements as i32;
        let mut ref_builder = runtime.stream().launch_builder(&ref_function);
        ref_builder
            .arg(&gate_out_ptr)
            .arg(&up_out_ptr)
            .arg(&ref_out_ptr)
            .arg(&output_elements_i32);
        // SAFETY: all three buffers hold `output_elements` fp16 values.
        unsafe {
            ref_builder.launch(LaunchConfig {
                grid_dim: (output_elements.div_ceil(256) as u32, 1, 1),
                block_dim: (256, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .unwrap();

        let inputs = [
            activation_view,
            packed_gate_view,
            scales_gate_view,
            packed_up_view,
            scales_up_view,
        ];
        let mut outputs = [fused_out];
        gemv_kernel
            .run_f16_gate_up_swiglu(&inputs, &mut outputs, None)
            .unwrap();
        runtime.synchronize().unwrap();

        let mut reference = vec![f16::ZERO; output_elements];
        let mut fused = vec![f16::ZERO; output_elements];
        // SAFETY: both output allocations hold `output_elements` fp16 values.
        unsafe {
            runtime
                .dtoh(as_bytes_mut(&mut reference), ref_out_dev)
                .unwrap();
            runtime
                .dtoh(as_bytes_mut(&mut fused), fused_out_dev)
                .unwrap();
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_gate_dev).unwrap();
            runtime.free_raw(scales_gate_dev).unwrap();
            runtime.free_raw(packed_up_dev).unwrap();
            runtime.free_raw(scales_up_dev).unwrap();
            runtime.free_raw(gate_out_dev).unwrap();
            runtime.free_raw(up_out_dev).unwrap();
            runtime.free_raw(ref_out_dev).unwrap();
            runtime.free_raw(fused_out_dev).unwrap();
        }

        let mut max_ulp = 0i64;
        let mut nonzero = 0usize;
        for index in 0..output_elements {
            let d = f16_ulp_diff(fused[index].to_bits(), reference[index].to_bits());
            if d > 0 {
                nonzero += 1;
            }
            if d > max_ulp {
                max_ulp = d;
            }
        }
        (max_ulp, nonzero, output_elements)
    }

    /// Measured ULP bound of the *plain* (no rmsnorm prologue) fused gate/up
    /// SwiGLU decode GEMV against the two-op reference (two standalone
    /// MatMulNBits projections + reference silu_mul), swept across activations
    /// (many seeds) and shapes at **M==1**.
    ///
    /// WHY THIS EXISTS — and why it is M==1-only:
    /// `fp16_gate_up_swiglu_is_bit_exact_to_two_op_path` asserts *byte* equality
    /// against the two-op reference. That identity holds only for the particular
    /// activations its four tuples happen to sample. The fused decode GEMV
    /// carries gate/up in fp32 and the two-op reference rounds each projection to
    /// fp16 before silu_mul, so the two differ by up to **2 ULP** depending on
    /// the activation — *even at M==1*, the apples-to-apples decode comparison.
    /// This measurement is the decision-rule input that HARD-STOPPED the plain
    /// half of the batch-decode capture-safe fix: because the plain fused decode
    /// GEMV is not within 1 ULP of the two-op path even at M==1, the production
    /// per-row decode-GEMV loop is gated to the rmsnorm-prologue path only
    /// (`gamma.is_some()`), and plain M>1 stays on the prefill/Marlin GEMM.
    /// See the byte-identical rmsnorm analog
    /// `fp16_gate_up_swiglu_rmsnorm_two_op_ulp_bound_sweep` (0 ULP at M==1) and
    /// issue #1334.
    ///
    /// Restricted to M==1 on purpose. With the plain path no longer looped, the
    /// plain M>1 fused gate/up runs through the direct Marlin int4 tensor-core
    /// GEMM (`marlin_m_gt_1_enabled()`, default **ON**; split-K
    /// `ONNX_GENAI_MARLIN_SPLITK` is a separate, default-OFF, deterministic
    /// path and does not engage here). That direct kernel accumulates in a
    /// different order than the tiled two-op reference and is documented
    /// *non-byte-identical* to it (its parity tests assert a `2e-2 * max_out`
    /// tolerance, not equality — see `marlin_gemm::marlin_m_gt_1_enabled`). So an
    /// M>1 plain sweep would measure Marlin's accumulation offset, not this
    /// node's decode-vs-two-op bound. It is also why `main` does not actually
    /// hold "M>1 is bit-exact to the two-op reference" under the default config:
    /// `fp16_gate_up_swiglu_is_bit_exact_to_two_op_path` reds at M=5 with Marlin
    /// default-on and only passes under `ONNX_GENAI_MARLIN_M_GT_1=0` (tiled).
    #[test]
    fn fp16_gate_up_swiglu_two_op_ulp_bound_sweep() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping gate/up SwiGLU ULP sweep: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping gate/up SwiGLU ULP sweep: fp16 NVRTC headers unavailable");
            return;
        }

        // (K=hidden, N=intermediate), K divisible by block_size (32).
        let shapes = [
            (QWEN_DOWN_N, QWEN_DOWN_K), // Qwen2.5-0.5B gate/up: 896 -> 4864
            (2048usize, 5632usize),     // Llama-7B-ish MLP
            (1024, 2816),
            (896, 896), // square
            (512, 1536),
            (128, 256), // small, grid-starved
            (96, 77),   // odd tail (matches the existing test's small case)
        ];
        // M==1 only: see the doc comment. Plain M>1 routes through the direct
        // Marlin int4 tensor-core GEMM (non-byte-identical to the two-op
        // reference by a different accumulation order), not this node's decode
        // GEMV.
        let ms = [1usize];
        let seeds: [u64; 8] = [
            0x0bad_c0de_dead_beef,
            0x1234_5678_9abc_def0,
            0xdead_beef_cafe_babe,
            0x0f0f_0f0f_f0f0_f0f0,
            0xa5a5_5a5a_1111_2222,
            0x9e37_79b9_7f4a_7c15,
            0xc2b2_ae3d_27d4_eb4f,
            0xff51_afd7_ed55_8ccd,
        ];

        let mut global_max = 0i64;
        let mut m1_max = 0i64;
        let mut m1_nonzero_cases = 0usize;
        let mut m1_cases = 0usize;
        let mut worst = (0usize, 0usize, 0usize, 0u64); // (m,k,n,seed)
        for (k, n) in shapes {
            for m in ms {
                for seed in seeds {
                    let (max_ulp, nonzero, total) =
                        gate_up_swiglu_two_op_ulp_case(&runtime, m, k, n, seed);
                    assert!(total > 0);
                    if m == 1 {
                        m1_cases += 1;
                        if nonzero > 0 {
                            m1_nonzero_cases += 1;
                        }
                        if max_ulp > m1_max {
                            m1_max = max_ulp;
                        }
                    }
                    if max_ulp > global_max {
                        global_max = max_ulp;
                        worst = (m, k, n, seed);
                    }
                }
            }
        }

        eprintln!(
            "gate/up SwiGLU two-op ULP sweep: max_ulp={global_max} \
             (worst: M={} K={} N={} seed={:#018x}); \
             M==1: max_ulp={m1_max}, {m1_nonzero_cases}/{m1_cases} cases had >=1 ULP divergence",
            worst.0, worst.1, worst.2, worst.3
        );

        // Decision-rule input (HARD STOP): the plain fused decode GEMV is a
        // deterministic approximation of the two-op reference, but NOT within
        // 1 ULP even at M==1 — the measured bound is 2 ULP. This is exactly why
        // the plain path is not routed through the M>1 per-row decode loop
        // (that would move plain-path logits >1 ULP vs the two-op path). The
        // bound is asserted at its measured value so a *regression past it*
        // (e.g. a kernel change widening the gap) still fails loudly; loosening
        // this number must be a deliberate, measured edit, not an accident.
        // The rmsnorm half, by contrast, is byte-identical at M==1 (0 ULP) and
        // IS landed — see `fp16_gate_up_swiglu_rmsnorm_two_op_ulp_bound_sweep`.
        assert_eq!(
            global_max, m1_max,
            "sweep is M==1-only; global and M==1 maxima must coincide"
        );
        assert!(
            global_max <= 2,
            "plain fused gate/up SwiGLU exceeded the measured 2 ULP bound vs the \
             two-op reference: max_ulp={global_max} at M={} K={} N={} seed={:#018x}",
            worst.0,
            worst.1,
            worst.2,
            worst.3
        );
    }

    /// One (M, K, N, seed, gamma_dtype) case of the fused gate/up SwiGLU *with an
    /// RMS-norm prologue* vs the two-op reference. Reference: normalize the
    /// activation with the production prefill norm kernel, then two standalone
    /// projections (M==1 → General GEMV, M>1 → tiled GEMM) + reference silu_mul
    /// on the normalized activation. Subject: the fused rmsnorm-prologue kernel
    /// over the raw activation with gamma at slot 5. Returns
    /// `(max_ulp, elements_with_nonzero_ulp, total_elements)`.
    ///
    /// This is the RMS-norm analog of [`gate_up_swiglu_two_op_ulp_case`]: it
    /// measures whether the rmsnorm decode-GEMV loop is byte-identical to the
    /// two-op (prefill-equivalent) rmsnorm path, i.e. whether the "rmsnorm half"
    /// is genuinely a byte-safe substitute for what `main` ships, or only
    /// byte-identical to a loop-vs-loop reference.
    fn gate_up_swiglu_rmsnorm_two_op_ulp_case(
        runtime: &Arc<CudaRuntime>,
        m: usize,
        k: usize,
        n: usize,
        seed: u64,
        gamma_dtype: DataType,
    ) -> (i64, usize, usize) {
        const REF_SILU_MUL_SRC: &str = r#"
#include <cuda_fp16.h>
__device__ float ref_op_silu(float x) {
    if (x >= 0.0f) {
        const float denominator = __fadd_rn(1.0f, (float)exp((double)-x));
        return __fdiv_rn(x, denominator);
    }
    const float e = (float)exp((double)x);
    const float numerator = __fmul_rn(x, e);
    return __fdiv_rn(numerator, __fadd_rn(1.0f, e));
}
extern "C" __global__ void ref_silu_mul_f16(
    const __half* g, const __half* u, __half* y, const int n) {
    const int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        y[i] = __float2half_rn(
            __fmul_rn(ref_op_silu(__half2float(g[i])), __half2float(u[i])));
    }
}
"#;
        let epsilon = 1e-5f32;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;

        let mut state = seed;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };
        let pack = |next: &mut dyn FnMut() -> f32| -> Vec<u8> {
            let mut quant = vec![0u8; n * k];
            for value in quant.iter_mut() {
                *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
            }
            let mut packed = vec![0u8; n * k_blocks * blob_size];
            for col in 0..n {
                for block in 0..k_blocks {
                    for pair in 0..blob_size {
                        let low = quant[col * k + block * block_size + pair * 2] & 15;
                        let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                        packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                    }
                }
            }
            packed
        };

        let activation: Vec<f16> = (0..m * k).map(|_| f16::from_f32(next())).collect();
        let packed_gate = pack(&mut next);
        let scales_gate: Vec<f16> = (0..n * k_blocks)
            .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        let packed_up = pack(&mut next);
        let scales_up: Vec<f16> = (0..n * k_blocks)
            .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        let gamma_is_f32 = gamma_dtype == DataType::Float32;
        let gamma_f32: Vec<f32> = (0..k).map(|_| 0.5 + 0.5 * (next() * 0.5 + 0.5)).collect();
        let gamma_bytes: Vec<u8> = if gamma_is_f32 {
            gamma_f32.iter().flat_map(|v| v.to_le_bytes()).collect()
        } else {
            gamma_f32
                .iter()
                .flat_map(|v| f16::from_f32(*v).to_le_bytes())
                .collect()
        };

        let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
        let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
        let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
        let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
        let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
        let gamma_dev = runtime.alloc_raw(gamma_bytes.len()).unwrap();
        let normalized_dev = runtime.alloc_raw(m * k * 2).unwrap();
        let output_elements = m * n;
        let gate_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        let up_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        let ref_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        let fused_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
        // SAFETY: device buffers exactly cover their source slices.
        unsafe {
            runtime.htod(as_bytes(&activation), activation_dev).unwrap();
            runtime.htod(&packed_gate, packed_gate_dev).unwrap();
            runtime
                .htod(as_bytes(&scales_gate), scales_gate_dev)
                .unwrap();
            runtime.htod(&packed_up, packed_up_dev).unwrap();
            runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
            runtime.htod(&gamma_bytes, gamma_dev).unwrap();
        }

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let gamma_shape = [k];
        let gamma_strides = [1i64];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];
        let activation_view = TensorView::new(
            device_ptr(activation_dev),
            DataType::Float16,
            &a_shape,
            &a_strides,
            device,
        );
        let normalized_view = TensorView::new(
            device_ptr(normalized_dev),
            DataType::Float16,
            &a_shape,
            &a_strides,
            device,
        );
        let packed_gate_view = TensorView::new(
            device_ptr(packed_gate_dev),
            DataType::Uint8,
            &b_shape,
            &b_strides,
            device,
        );
        let scales_gate_view = TensorView::new(
            device_ptr(scales_gate_dev),
            DataType::Float16,
            &scales_shape,
            &scales_strides,
            device,
        );
        let packed_up_view = TensorView::new(
            device_ptr(packed_up_dev),
            DataType::Uint8,
            &b_shape,
            &b_strides,
            device,
        );
        let scales_up_view = TensorView::new(
            device_ptr(scales_up_dev),
            DataType::Float16,
            &scales_shape,
            &scales_strides,
            device,
        );
        let gamma_view = TensorView::new(
            device_ptr(gamma_dev),
            gamma_dtype,
            &gamma_shape,
            &gamma_strides,
            device,
        );
        let mut gate_out = TensorMut::new(
            device_ptr_mut(gate_out_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );
        let mut up_out = TensorMut::new(
            device_ptr_mut(up_out_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );
        let fused_out = TensorMut::new(
            device_ptr_mut(fused_out_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        );

        let plain_kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: epsilon,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };
        let fused_kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 4,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: true,
            decomposed_silu: false,
            rmsnorm_prologue: true,
            rmsnorm_epsilon: epsilon,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        // Reference: normalize with the production prefill norm, then two-op on
        // the normalized activation (main's prefill-equivalent rmsnorm path).
        plain_kernel
            .launch_rmsnorm_prefill(
                &activation_view,
                &gamma_view,
                cuptr(device_ptr(normalized_dev).0),
                m,
            )
            .unwrap();
        if m == 1 {
            let selection = select_f16_gemv_variant(k, n, block_size, true, false);
            plain_kernel
                .launch_f16_gemv_variant(
                    &normalized_view,
                    &packed_gate_view,
                    &scales_gate_view,
                    true,
                    None,
                    None,
                    &mut gate_out,
                    k_blocks,
                    blob_size,
                    k_blocks.div_ceil(2),
                    selection,
                )
                .unwrap();
            plain_kernel
                .launch_f16_gemv_variant(
                    &normalized_view,
                    &packed_up_view,
                    &scales_up_view,
                    true,
                    None,
                    None,
                    &mut up_out,
                    k_blocks,
                    blob_size,
                    k_blocks.div_ceil(2),
                    selection,
                )
                .unwrap();
        } else {
            plain_kernel
                .launch_f16_gemm(
                    &normalized_view,
                    &packed_gate_view,
                    &scales_gate_view,
                    true,
                    None,
                    None,
                    &mut gate_out,
                    m,
                    k_blocks,
                    plain_kernel.block_size * plain_kernel.bits / 8,
                    0,
                )
                .unwrap();
            plain_kernel
                .launch_f16_gemm(
                    &normalized_view,
                    &packed_up_view,
                    &scales_up_view,
                    true,
                    None,
                    None,
                    &mut up_out,
                    m,
                    k_blocks,
                    plain_kernel.block_size * plain_kernel.bits / 8,
                    0,
                )
                .unwrap();
        }
        let ref_function = runtime
            .nvrtc_function(
                "matmul_nbits_ref_silu_mul",
                REF_SILU_MUL_SRC,
                "ref_silu_mul_f16",
            )
            .unwrap();
        let gate_out_ptr = cuptr(device_ptr(gate_out_dev).0);
        let up_out_ptr = cuptr(device_ptr(up_out_dev).0);
        let ref_out_ptr = cuptr(device_ptr(ref_out_dev).0);
        let output_elements_i32 = output_elements as i32;
        let mut ref_builder = runtime.stream().launch_builder(&ref_function);
        ref_builder
            .arg(&gate_out_ptr)
            .arg(&up_out_ptr)
            .arg(&ref_out_ptr)
            .arg(&output_elements_i32);
        // SAFETY: all three buffers hold `output_elements` fp16 values.
        unsafe {
            ref_builder.launch(LaunchConfig {
                grid_dim: (output_elements.div_ceil(256) as u32, 1, 1),
                block_dim: (256, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .unwrap();

        // Subject: the fused rmsnorm-prologue kernel over the RAW activation.
        let inputs = [
            activation_view,
            packed_gate_view,
            scales_gate_view,
            packed_up_view,
            scales_up_view,
            gamma_view,
        ];
        let mut outputs = [fused_out];
        fused_kernel
            .run_f16_gate_up_swiglu(&inputs, &mut outputs, None)
            .unwrap();
        runtime.synchronize().unwrap();

        let mut reference = vec![f16::ZERO; output_elements];
        let mut fused = vec![f16::ZERO; output_elements];
        // SAFETY: both output allocations hold `output_elements` fp16 values.
        unsafe {
            runtime
                .dtoh(as_bytes_mut(&mut reference), ref_out_dev)
                .unwrap();
            runtime
                .dtoh(as_bytes_mut(&mut fused), fused_out_dev)
                .unwrap();
            runtime.free_raw(activation_dev).unwrap();
            runtime.free_raw(packed_gate_dev).unwrap();
            runtime.free_raw(scales_gate_dev).unwrap();
            runtime.free_raw(packed_up_dev).unwrap();
            runtime.free_raw(scales_up_dev).unwrap();
            runtime.free_raw(gamma_dev).unwrap();
            runtime.free_raw(normalized_dev).unwrap();
            runtime.free_raw(gate_out_dev).unwrap();
            runtime.free_raw(up_out_dev).unwrap();
            runtime.free_raw(ref_out_dev).unwrap();
            runtime.free_raw(fused_out_dev).unwrap();
        }

        let mut max_ulp = 0i64;
        let mut nonzero = 0usize;
        for index in 0..output_elements {
            let d = f16_ulp_diff(fused[index].to_bits(), reference[index].to_bits());
            if d > 0 {
                nonzero += 1;
            }
            if d > max_ulp {
                max_ulp = d;
            }
        }
        (max_ulp, nonzero, output_elements)
    }

    /// RMS-norm analog of [`fp16_gate_up_swiglu_two_op_ulp_bound_sweep`]. The
    /// rmsnorm parity tests (`fused_gate_up_swiglu_rmsnorm_*`) are byte-exact,
    /// but their reference reuses a *per-row plain decode-GEMV loop* as its
    /// second step, so they only prove `rmsnorm-loop == normalize + plain-loop`,
    /// NOT that the rmsnorm loop matches a genuine two-op path. This sweep
    /// compares the fused rmsnorm loop against a real two-op reference (prefill
    /// normalize + standalone projections + silu_mul), across gamma dtypes,
    /// shapes, seeds, and M. ANSWER: byte-identical (0 ULP) at M==1 only when
    /// the standalone projections use the same single-warp block-32 reduction as
    /// the paired fused kernel. On many-SM devices the standalone general GEMV
    /// may select its grid-fill split-K variant for narrow N; that intentionally
    /// reassociates the K reduction and is bounded separately below.
    #[test]
    fn fp16_gate_up_swiglu_rmsnorm_two_op_ulp_bound_sweep() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping gate/up SwiGLU rmsnorm ULP sweep: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping gate/up SwiGLU rmsnorm ULP sweep: fp16 NVRTC headers unavailable");
            return;
        }

        // (K=hidden, N=intermediate); K % 128 == 0 for the warp_half4 norm.
        let shapes = [
            (QWEN_DOWN_N, QWEN_DOWN_K), // 896 -> 4864
            (2048usize, 5632usize),
            (1024, 2816),
            (896, 896),
            (512, 1536),
        ];
        let ms = [1usize, 2, 5, 8];
        let seeds: [u64; 6] = [
            0x0bad_c0de_dead_beef,
            0x1234_5678_9abc_def0,
            0xdead_beef_cafe_babe,
            0xa5a5_5a5a_1111_2222,
            0x9e37_79b9_7f4a_7c15,
            0xff51_afd7_ed55_8ccd,
        ];
        let gammas = [DataType::Float16, DataType::Float32];

        let mut global_max = 0i64;
        let mut m1_max = 0i64;
        let mut m1_single_warp_max = 0i64;
        let mut m1_splitk_max = 0i64;
        let mut m1_nonzero_cases = 0usize;
        let mut m1_cases = 0usize;
        let mut m1_worst = (0usize, 0usize, 0u64, DataType::Float16);
        let mut worst = (0usize, 0usize, 0usize, 0u64, DataType::Float16);
        let caps = runtime.capabilities();
        for gamma in gammas {
            for (k, n) in shapes {
                let reference_uses_splitk = use_f16_symmetric_splitk(
                    k,
                    n,
                    caps.multiprocessor_count(),
                    caps.max_threads_per_block(),
                );
                for m in ms {
                    for seed in seeds {
                        let (max_ulp, nonzero, total) =
                            gate_up_swiglu_rmsnorm_two_op_ulp_case(&runtime, m, k, n, seed, gamma);
                        assert!(total > 0);
                        if m == 1 {
                            m1_cases += 1;
                            if nonzero > 0 {
                                m1_nonzero_cases += 1;
                            }
                            if max_ulp > m1_max {
                                m1_max = max_ulp;
                                m1_worst = (k, n, seed, gamma);
                            }
                            if reference_uses_splitk {
                                m1_splitk_max = m1_splitk_max.max(max_ulp);
                            } else {
                                m1_single_warp_max = m1_single_warp_max.max(max_ulp);
                            }
                        }
                        if max_ulp > global_max {
                            global_max = max_ulp;
                            worst = (m, k, n, seed, gamma);
                        }
                    }
                }
            }
        }

        eprintln!(
            "gate/up SwiGLU rmsnorm two-op ULP sweep: max_ulp={global_max} \
             (worst: M={} K={} N={} seed={:#018x} gamma={:?}); \
             M==1: max_ulp={m1_max} (worst: K={} N={} seed={:#018x} gamma={:?}), \
             {m1_nonzero_cases}/{m1_cases} cases had >=1 ULP divergence",
            worst.0,
            worst.1,
            worst.2,
            worst.3,
            worst.4,
            m1_worst.0,
            m1_worst.1,
            m1_worst.2,
            m1_worst.3
        );

        // DECISION-RULE OUTPUT: at M==1 — the apples-to-apples decode
        // comparison — the fused rmsnorm decode GEMV is BYTE-IDENTICAL to the
        // two-op reference only when the two standalone projections use the same
        // single-warp block-32 reduction shape. On this A100/sm_80, the
        // device-property selector routes narrow standalone projections
        // (`N < SM_count * F16_SYMMETRIC_SPLITK_TARGET_WARPS_PER_SM`, e.g.
        // 896/1536 < 108*16) to `matmul_nbits_gemv_f16_scales_f16_splitk`:
        // two warps own disjoint K-block ranges for one column and reduce their
        // fp32 partials through shared memory. The paired gate/up RMS kernel has
        // no split-K sibling; it keeps one warp per column and therefore cannot
        // be byte-identical to that reference reduction tree on such shapes.
        // Preserve the strict invariant where the reduction shape matches, and
        // separately bound the named split-K reassociation observed on sm_80.
        assert_eq!(
            m1_single_warp_max, 0,
            "rmsnorm fused gate/up SwiGLU decode GEMV must be byte-identical to \
             the two-op reference at M==1 when both use the single-warp reduction, \
             but observed {m1_single_warp_max} ULP"
        );
        assert!(
            m1_splitk_max <= 3,
            "rmsnorm fused gate/up SwiGLU decode GEMV exceeded the measured 3-ULP \
             bound vs the standalone split-K two-op reference at M==1: \
             max_ulp={m1_splitk_max}"
        );
        // M>1 compares the per-row decode GEMV loop against a tiled two-op GEMM
        // reference; they differ by a few ULP purely from GEMV-vs-GEMM reduction
        // order (NOT a batching-contract violation — that is guarded by the
        // per-row == single-stream byte identity test). Bound recorded, not 0.
        assert!(
            global_max <= 4,
            "rmsnorm fused gate/up SwiGLU ULP vs two-op unexpectedly large: \
             max_ulp={global_max}"
        );
    }

    /// Byte-for-byte parity of the fused gate/up SwiGLU kernel *with an RMS
    /// prologue* against the standalone two-step sequence
    /// (`RMS-normalize the activation` → `paired gate/up SwiGLU`). The reference
    /// normalizes with the production prefill norm kernel
    /// (`matmul_nbits_rmsnorm_f16_warp_half4`) and then runs the already-proven
    /// non-prologue paired kernel, so any divergence isolates the fused
    /// prologue. Exercising M==1 (the single fused decode kernel) and M>1 (the
    /// normalize-into-scratch prefill path) keeps both dispatches honest.
    #[test]
    fn fused_gate_up_swiglu_rmsnorm_is_bit_exact_to_two_step_path() {
        run_fused_gate_up_swiglu_rmsnorm_parity(DataType::Float16, false);
    }

    /// Same gate/up SwiGLU RMS-norm fusion parity, but with an fp32 gamma (as
    /// Phi-4-mini exports it). The fused decode/prefill kernels must read the
    /// fp32 gamma at full precision and stay bit-identical to the two-step path.
    #[test]
    fn fused_gate_up_swiglu_rmsnorm_fp32_gamma_is_bit_exact_to_two_step_path() {
        run_fused_gate_up_swiglu_rmsnorm_parity(DataType::Float32, false);
    }

    /// Same gate/up SwiGLU RMS-norm fusion parity, but with asymmetric int4
    /// zero points on BOTH the gate and up projections (as Phi-4-mini exports
    /// them). The fused prologue kernel and the reference non-prologue paired
    /// kernel are independently written, so byte-identity here proves both honor
    /// the per-block zero point in the packed dequant. A fused kernel that
    /// ignored the zero point would diverge from the reference and fail. fp32
    /// gamma is paired with the zero points to mirror Phi's actual export.
    #[test]
    fn fused_gate_up_swiglu_rmsnorm_zero_points_is_bit_exact_to_two_step_path() {
        run_fused_gate_up_swiglu_rmsnorm_parity(DataType::Float32, true);
    }

    fn run_fused_gate_up_swiglu_rmsnorm_parity(gamma_dtype: DataType, explicit_zp: bool) {
        let Some(runtime) = runtime() else {
            eprintln!("skipping gate/up SwiGLU RMS-norm parity test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!(
                "skipping gate/up SwiGLU RMS-norm parity test: fp16 NVRTC headers unavailable"
            );
            return;
        }

        let epsilon = 1e-5f32;
        // (M, K=hidden, N=intermediate); hidden % 128 == 0 for the warp_half4
        // reduction. Decode is the capture-safe fused kernel; M=5 prefill routes
        // through the normalize-into-scratch path.
        for (m, k, n) in [
            (1usize, 896usize, 2432usize),
            (1, 3584, 4864),
            (5, 896, 2432),
        ] {
            let block_size = 32usize;
            let k_blocks = k / block_size;
            let blob_size = block_size / 2;

            let mut state = 0xf00d_1ceb_00da_5555u64;
            let mut next = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
            };

            let pack = |next: &mut dyn FnMut() -> f32| -> Vec<u8> {
                let mut quant = vec![0u8; n * k];
                for value in quant.iter_mut() {
                    *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
                }
                let mut packed = vec![0u8; n * k_blocks * blob_size];
                for col in 0..n {
                    for block in 0..k_blocks {
                        for pair in 0..blob_size {
                            let low = quant[col * k + block * block_size + pair * 2] & 15;
                            let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                            packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                        }
                    }
                }
                packed
            };

            let activation: Vec<f16> = (0..m * k).map(|_| f16::from_f32(next())).collect();
            let packed_gate = pack(&mut next);
            let scales_gate: Vec<f16> = (0..n * k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();
            let packed_up = pack(&mut next);
            let scales_up: Vec<f16> = (0..n * k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();

            // Optional asymmetric zero points, nibble-packed [n, zp_row_bytes]
            // exactly as `int4_block_zero_point` reads them. Symmetric weights
            // use the implicit zp == 8 and carry no zero-point input.
            let zp_row_bytes = k_blocks.div_ceil(2);
            let pack_zp = |next: &mut dyn FnMut() -> f32| -> Vec<u8> {
                let mut zp = vec![0u8; n * zp_row_bytes];
                for col in 0..n {
                    for block in 0..k_blocks {
                        let nibble =
                            (((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8) & 15;
                        let byte = &mut zp[col * zp_row_bytes + (block >> 1)];
                        if block & 1 == 1 {
                            *byte = (*byte & 0x0f) | (nibble << 4);
                        } else {
                            *byte = (*byte & 0xf0) | nibble;
                        }
                    }
                }
                zp
            };
            let zp_gate = pack_zp(&mut next);
            let zp_up = pack_zp(&mut next);
            let gamma_is_f32 = gamma_dtype == DataType::Float32;
            let gamma_f32: Vec<f32> = (0..k).map(|_| 0.5 + 0.5 * (next() * 0.5 + 0.5)).collect();
            let gamma_bytes: Vec<u8> = if gamma_is_f32 {
                gamma_f32.iter().flat_map(|v| v.to_le_bytes()).collect()
            } else {
                gamma_f32
                    .iter()
                    .flat_map(|v| f16::from_f32(*v).to_le_bytes())
                    .collect()
            };

            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
            let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
            let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
            let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
            let gamma_dev = runtime.alloc_raw(gamma_bytes.len()).unwrap();
            let zp_gate_dev = runtime.alloc_raw(zp_gate.len()).unwrap();
            let zp_up_dev = runtime.alloc_raw(zp_up.len()).unwrap();
            let normalized_dev = runtime.alloc_raw(m * k * 2).unwrap();
            let output_elements = m * n;
            let ref_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
            let fused_out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
            // SAFETY: device buffers exactly cover their source slices.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(&packed_gate, packed_gate_dev).unwrap();
                runtime
                    .htod(as_bytes(&scales_gate), scales_gate_dev)
                    .unwrap();
                runtime.htod(&packed_up, packed_up_dev).unwrap();
                runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
                runtime.htod(&gamma_bytes, gamma_dev).unwrap();
                if explicit_zp {
                    runtime.htod(&zp_gate, zp_gate_dev).unwrap();
                    runtime.htod(&zp_up, zp_up_dev).unwrap();
                }
            }

            let device = DeviceId::cuda(0);
            let a_shape = [m, k];
            let a_strides = [k as i64, 1];
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let scales_shape = [n, k_blocks];
            let scales_strides = [k_blocks as i64, 1];
            let gamma_shape = [k];
            let gamma_strides = [1i64];
            let y_shape = [m, n];
            let y_strides = [n as i64, 1];

            let activation_view = TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            );
            let _normalized_view = TensorView::new(
                device_ptr(normalized_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            );
            let packed_gate_view = TensorView::new(
                device_ptr(packed_gate_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_gate_view = TensorView::new(
                device_ptr(scales_gate_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let packed_up_view = TensorView::new(
                device_ptr(packed_up_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_up_view = TensorView::new(
                device_ptr(scales_up_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let gamma_view = TensorView::new(
                device_ptr(gamma_dev),
                gamma_dtype,
                &gamma_shape,
                &gamma_strides,
                device,
            );
            let zp_shape = [n, zp_row_bytes];
            let zp_strides = [zp_row_bytes as i64, 1];
            let zp_gate_view = TensorView::new(
                device_ptr(zp_gate_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            );
            let zp_up_view = TensorView::new(
                device_ptr(zp_up_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            );
            let fused_out = TensorMut::new(
                device_ptr_mut(fused_out_dev),
                DataType::Float16,
                &y_shape,
                &y_strides,
                device,
            );

            let plain_swiglu = MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits: 4,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: false,
                gate_up_swiglu: true,
                decomposed_silu: false,
                rmsnorm_prologue: false,
                rmsnorm_epsilon: epsilon,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };
            let fused_swiglu = MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits: 4,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: false,
                gate_up_swiglu: true,
                decomposed_silu: false,
                rmsnorm_prologue: true,
                rmsnorm_epsilon: epsilon,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };

            // Reference: normalize the activation (production prefill norm
            // kernel), then run the proven non-prologue paired gate/up SwiGLU.
            plain_swiglu
                .launch_rmsnorm_prefill(
                    &activation_view,
                    &gamma_view,
                    cuptr(device_ptr(normalized_dev).0),
                    m,
                )
                .unwrap();
            {
                // The reference GEMV is looped per row (M==1 each) rather than
                // run once over all M rows. RMS norm is a per-row reduction and
                // a plain M==1 gate/up SwiGLU always dispatches the capture-safe
                // fused decode GEMV, so row r of this reference is exactly a
                // standalone M==1 normalize+SwiGLU of row r. That keeps the
                // reference byte-identical to the fused rmsnorm per-row decode
                // loop under test even though the plain (gamma=None) path no
                // longer loops M>1 (it falls to the prefill/Marlin GEMM, which
                // is ~3 ULP off a decode GEMV; see the two-op ULP sweep and
                // #1334). Running the plain reference over all M rows here would
                // route through that GEMM and spuriously red this parity test.
                let norm_row_shape = [1usize, k];
                let norm_row_strides = [k as i64, 1];
                let out_row_shape = [1usize, n];
                let out_row_strides = [n as i64, 1];
                let norm_row_bytes = (k * 2) as CUdeviceptr; // fp16
                let out_row_bytes = (n * 2) as CUdeviceptr; // fp16
                for row in 0..m {
                    let norm_row = TensorView::new(
                        device_ptr(normalized_dev + row as CUdeviceptr * norm_row_bytes),
                        DataType::Float16,
                        &norm_row_shape,
                        &norm_row_strides,
                        device,
                    );
                    let out_row = TensorMut::new(
                        device_ptr_mut(ref_out_dev + row as CUdeviceptr * out_row_bytes),
                        DataType::Float16,
                        &out_row_shape,
                        &out_row_strides,
                        device,
                    );
                    let mut ref_outputs = [out_row];
                    let ref_inputs_base = [
                        norm_row,
                        packed_gate_view,
                        scales_gate_view,
                        packed_up_view,
                        scales_up_view,
                    ];
                    if explicit_zp {
                        // Slot 5 gamma absent (already normalized), slots 6/7 zp.
                        let ref_inputs = [
                            ref_inputs_base[0],
                            ref_inputs_base[1],
                            ref_inputs_base[2],
                            ref_inputs_base[3],
                            ref_inputs_base[4],
                            TensorView::absent(DataType::Float16),
                            zp_gate_view,
                            zp_up_view,
                        ];
                        plain_swiglu
                            .run_f16_gate_up_swiglu(&ref_inputs, &mut ref_outputs, None)
                            .unwrap();
                    } else {
                        plain_swiglu
                            .run_f16_gate_up_swiglu(&ref_inputs_base, &mut ref_outputs, None)
                            .unwrap();
                    }
                }
            }

            // Subject: the fused prologue kernel over the raw (residual sum)
            // activation with gamma at slot 5.
            {
                let mut fused_outputs = [fused_out];
                let fused_inputs_base = [
                    activation_view,
                    packed_gate_view,
                    scales_gate_view,
                    packed_up_view,
                    scales_up_view,
                    gamma_view,
                ];
                if explicit_zp {
                    let fused_inputs = [
                        fused_inputs_base[0],
                        fused_inputs_base[1],
                        fused_inputs_base[2],
                        fused_inputs_base[3],
                        fused_inputs_base[4],
                        fused_inputs_base[5],
                        zp_gate_view,
                        zp_up_view,
                    ];
                    fused_swiglu
                        .run_f16_gate_up_swiglu(&fused_inputs, &mut fused_outputs, None)
                        .unwrap();
                } else {
                    fused_swiglu
                        .run_f16_gate_up_swiglu(&fused_inputs_base, &mut fused_outputs, None)
                        .unwrap();
                }
            }
            // Capture-safety tracks the decode-GEMV *routing*, not a fixed
            // M==1 rule (see the companion note on the non-rmsnorm assertion
            // above). `05e1fd10` could only capture M==1 because every M>1
            // fused gate/up-SwiGLU with an RMS-norm prologue reached
            // `launch_gate_up_swiglu_rmsnorm_prefill`, which normalizes into
            // freshly `alloc_raw`'d scratch and so cannot be graph-recorded.
            // The small-M loop now dispatches `1 < m <= decode_gemv_loop_max_m()`
            // as per-row capture-safe M==1 fused kernels (each byte-identical
            // to M==1), making those M genuinely capture-safe; only
            // `m > decode_gemv_loop_max_m()` still reaches the scratch prefill
            // path. Narrowed to exactly that range, not deleted.
            assert_eq!(
                fused_swiglu.last_call_capture_safe.load(Ordering::Relaxed),
                (1..=decode_gemv_loop_max_m()).contains(&m),
                "capture-safe iff the decode-GEMV routing is per-row M==1 \
                 launches: M==1 or small-batch M<=decode_gemv_loop_max_m(); \
                 M>window still reaches the uncapturable prefill GEMM"
            );
            runtime.synchronize().unwrap();

            let mut reference = vec![f16::ZERO; output_elements];
            let mut fused = vec![f16::ZERO; output_elements];
            // SAFETY: both output allocations hold `output_elements` fp16 values.
            unsafe {
                runtime
                    .dtoh(as_bytes_mut(&mut reference), ref_out_dev)
                    .unwrap();
                runtime
                    .dtoh(as_bytes_mut(&mut fused), fused_out_dev)
                    .unwrap();
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(packed_gate_dev).unwrap();
                runtime.free_raw(scales_gate_dev).unwrap();
                runtime.free_raw(packed_up_dev).unwrap();
                runtime.free_raw(scales_up_dev).unwrap();
                runtime.free_raw(gamma_dev).unwrap();
                runtime.free_raw(zp_gate_dev).unwrap();
                runtime.free_raw(zp_up_dev).unwrap();
                runtime.free_raw(normalized_dev).unwrap();
                runtime.free_raw(ref_out_dev).unwrap();
                runtime.free_raw(fused_out_dev).unwrap();
            }

            for index in 0..output_elements {
                assert_eq!(
                    fused[index].to_bits(),
                    reference[index].to_bits(),
                    "fused gate/up SwiGLU RMS prologue diverged at M={m}, K={k}, N={n}, \
                     row={}, column={}: fused={:?} reference={:?}",
                    index / n,
                    index % n,
                    fused[index],
                    reference[index]
                );
            }
        }
    }

    /// The fused-symmetric gate/up SwiGLU decode entries (`..gate_up*_vec`,
    /// opt-in via `ONNX_GENAI_GATEUP_VEC=1`) must be RAW-16-BIT IDENTICAL to the
    /// default symmetric entries. The `_vec` entries only fold the `- 8`
    /// symmetric zero point into the dequant bias constants (see
    /// `int4x8_to_half2x4_sym8`); every `q[i]` value is unchanged, so the fp16
    /// multiply-add accumulation, the RMS-norm prologue, the SwiGLU rounding, and
    /// thus `silu(gate)*up` must match bit-for-bit — and hence match M
    /// independent M=1 greedy `_dsilu` GEMVs. A single argmax flip downstream
    /// would start here. Covers plain + RMS-norm-fused, decomposed +
    /// non-decomposed SiLU, fp16 AND fp32 gamma, the real Qwen2.5-14b gate/up
    /// dims (K=5120, N=13824), and M in {1,4,6,8}. Also asserts the
    /// occupancy-raised `_vec_occ` path (`ONNX_GENAI_GATEUP_OCC`,
    /// `__launch_bounds__(256, 8)`) is bit-identical to the scalar reference for
    /// the symmetric RMS-norm-fused kernels it applies to (it is a no-op for the
    /// non-RMS launch) — `__launch_bounds__` only constrains register
    /// allocation, so the math is unchanged.
    #[test]
    fn gate_up_swiglu_vec_is_bit_identical_to_scalar() {
        let Some(runtime) = runtime() else {
            eprintln!("skipping gate/up SwiGLU _vec bit-identity test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!(
                "skipping gate/up SwiGLU _vec bit-identity test: fp16 NVRTC headers unavailable"
            );
            return;
        }

        let epsilon = 1e-5f32;
        for (m, k, n) in [
            (1usize, 896usize, 2432usize),
            (4, 3584, 4864),
            (6, 5120, 13824),
            (8, 5120, 13824),
        ] {
            let block_size = 32usize;
            let k_blocks = k / block_size;
            let blob_size = block_size / 2;

            let mut state = 0x51de_face_c0de_1234u64 ^ ((m as u64) << 40);
            let mut next = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
            };

            let pack = |next: &mut dyn FnMut() -> f32| -> Vec<u8> {
                let mut quant = vec![0u8; n * k];
                for value in quant.iter_mut() {
                    *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
                }
                let mut packed = vec![0u8; n * k_blocks * blob_size];
                for col in 0..n {
                    for block in 0..k_blocks {
                        for pair in 0..blob_size {
                            let low = quant[col * k + block * block_size + pair * 2] & 15;
                            let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                            packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                        }
                    }
                }
                packed
            };

            let activation: Vec<f16> = (0..m * k).map(|_| f16::from_f32(next())).collect();
            let packed_gate = pack(&mut next);
            let scales_gate: Vec<f16> = (0..n * k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();
            let packed_up = pack(&mut next);
            let scales_up: Vec<f16> = (0..n * k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();
            let gamma_f32: Vec<f32> = (0..k).map(|_| 0.5 + 0.5 * (next() * 0.5 + 0.5)).collect();

            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let packed_gate_dev = runtime.alloc_raw(packed_gate.len()).unwrap();
            let scales_gate_dev = runtime.alloc_raw(scales_gate.len() * 2).unwrap();
            let packed_up_dev = runtime.alloc_raw(packed_up.len()).unwrap();
            let scales_up_dev = runtime.alloc_raw(scales_up.len() * 2).unwrap();
            // SAFETY: device buffers exactly cover their source slices.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(&packed_gate, packed_gate_dev).unwrap();
                runtime
                    .htod(as_bytes(&scales_gate), scales_gate_dev)
                    .unwrap();
                runtime.htod(&packed_up, packed_up_dev).unwrap();
                runtime.htod(as_bytes(&scales_up), scales_up_dev).unwrap();
            }

            let device = DeviceId::cuda(0);
            let a_shape = [m, k];
            let a_strides = [k as i64, 1];
            let b_shape = [n, k_blocks, blob_size];
            let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
            let scales_shape = [n, k_blocks];
            let scales_strides = [k_blocks as i64, 1];
            let gamma_shape = [k];
            let gamma_strides = [1i64];
            let y_shape = [m, n];
            let y_strides = [n as i64, 1];
            let output_elements = m * n;

            let activation_view = TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            );
            let packed_gate_view = TensorView::new(
                device_ptr(packed_gate_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_gate_view = TensorView::new(
                device_ptr(scales_gate_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );
            let packed_up_view = TensorView::new(
                device_ptr(packed_up_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            );
            let scales_up_view = TensorView::new(
                device_ptr(scales_up_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            );

            // Every (rmsnorm, decomposed, gamma dtype) symmetric gate/up variant
            // that has a `_vec` sibling, so the bit-identity gate covers all four
            // fused-symmetric entries and both gamma widths.
            for rmsnorm in [false, true] {
                for decomposed in [false, true] {
                    for gamma_dtype in [DataType::Float16, DataType::Float32] {
                        if !rmsnorm && gamma_dtype == DataType::Float32 {
                            // Gamma is only consumed by the RMS-norm prologue.
                            continue;
                        }
                        let gamma_is_f32 = gamma_dtype == DataType::Float32;
                        let gamma_bytes: Vec<u8> = if gamma_is_f32 {
                            gamma_f32.iter().flat_map(|v| v.to_le_bytes()).collect()
                        } else {
                            gamma_f32
                                .iter()
                                .flat_map(|v| f16::from_f32(*v).to_le_bytes())
                                .collect()
                        };
                        let gamma_dev = runtime.alloc_raw(gamma_bytes.len()).unwrap();
                        // SAFETY: buffer sized to the gamma byte slice.
                        unsafe {
                            runtime.htod(&gamma_bytes, gamma_dev).unwrap();
                        }
                        let gamma_view = TensorView::new(
                            device_ptr(gamma_dev),
                            gamma_dtype,
                            &gamma_shape,
                            &gamma_strides,
                            device,
                        );

                        let kernel = MatMulNBitsKernel {
                            runtime: runtime.clone(),
                            k,
                            n,
                            bits: 4,
                            block_size,
                            accuracy_level: 4,
                            accuracy4_workspace: None,
                            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                            constant_inputs: [true; 8],
                            fold_bias_post_round: false,
                            gate_up_swiglu: true,
                            decomposed_silu: decomposed,
                            rmsnorm_prologue: rmsnorm,
                            rmsnorm_epsilon: epsilon,
                            last_call_capture_safe: AtomicBool::new(false),
                            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
                        };

                        let run_once = |vec_on: bool, occ_on: bool| -> Vec<u16> {
                            let out_dev = runtime.alloc_raw(output_elements * 2).unwrap();
                            // Exclusive: this env write is process-wide, and the
                            // guard clears it on drop so an unwinding `unwrap`
                            // below cannot leak the lever to other tests.
                            let _guard = LeverEnvGuard::acquire();
                            // SAFETY: confined to the exclusive section.
                            unsafe {
                                std::env::set_var(
                                    "ONNX_GENAI_GATEUP_VEC",
                                    if vec_on { "1" } else { "0" },
                                );
                                std::env::set_var(
                                    "ONNX_GENAI_GATEUP_OCC",
                                    if occ_on { "1" } else { "0" },
                                );
                            }
                            let out = TensorMut::new(
                                device_ptr_mut(out_dev),
                                DataType::Float16,
                                &y_shape,
                                &y_strides,
                                device,
                            );
                            let mut outputs = [out];
                            if rmsnorm {
                                let inputs = [
                                    activation_view,
                                    packed_gate_view,
                                    scales_gate_view,
                                    packed_up_view,
                                    scales_up_view,
                                    gamma_view,
                                ];
                                kernel
                                    .run_f16_gate_up_swiglu(&inputs, &mut outputs, None)
                                    .unwrap();
                            } else {
                                let inputs = [
                                    activation_view,
                                    packed_gate_view,
                                    scales_gate_view,
                                    packed_up_view,
                                    scales_up_view,
                                ];
                                kernel
                                    .run_f16_gate_up_swiglu(&inputs, &mut outputs, None)
                                    .unwrap();
                            }
                            runtime.synchronize().unwrap();
                            unsafe {
                                std::env::remove_var("ONNX_GENAI_GATEUP_VEC");
                                std::env::remove_var("ONNX_GENAI_GATEUP_OCC");
                            }
                            drop(_guard);

                            let mut host = vec![f16::ZERO; output_elements];
                            // SAFETY: buffer holds `output_elements` fp16 values.
                            unsafe {
                                runtime.dtoh(as_bytes_mut(&mut host), out_dev).unwrap();
                                runtime.free_raw(out_dev).unwrap();
                            }
                            host.iter().map(|v| v.to_bits()).collect()
                        };

                        let reference = run_once(false, false);
                        let fused = run_once(true, false);
                        // Occupancy-raised `_vec_occ` path. The `_vec_occ` entries
                        // exist ONLY for the two symmetric RMS-norm-fused kernels,
                        // so this actually exercises `_vec_occ` when rmsnorm==true;
                        // for the non-rmsnorm launch `ONNX_GENAI_GATEUP_OCC` is a
                        // no-op and this simply re-checks the `_vec` path. Either
                        // way the result must stay bit-identical to the reference.
                        let occ = run_once(true, true);

                        // SAFETY: gamma buffer no longer referenced.
                        unsafe {
                            runtime.free_raw(gamma_dev).unwrap();
                        }

                        for index in 0..output_elements {
                            assert_eq!(
                                fused[index],
                                reference[index],
                                "fused-symmetric gate/up _vec diverged at M={m}, K={k}, N={n}, \
                                 rmsnorm={rmsnorm}, decomposed={decomposed}, \
                                 gamma_f32={gamma_is_f32}, row={}, column={}: vec=0x{:04x} \
                                 scalar=0x{:04x}",
                                index / n,
                                index % n,
                                fused[index],
                                reference[index]
                            );
                            assert_eq!(
                                occ[index],
                                reference[index],
                                "occupancy-raised gate/up _vec_occ diverged at M={m}, K={k}, \
                                 N={n}, rmsnorm={rmsnorm}, decomposed={decomposed}, \
                                 gamma_f32={gamma_is_f32}, row={}, column={}: occ=0x{:04x} \
                                 scalar=0x{:04x}",
                                index / n,
                                index % n,
                                occ[index],
                                reference[index]
                            );
                        }
                    }
                }
            }

            // SAFETY: shared input buffers are done after all variants ran.
            unsafe {
                runtime.free_raw(activation_dev).unwrap();
                runtime.free_raw(packed_gate_dev).unwrap();
                runtime.free_raw(scales_gate_dev).unwrap();
                runtime.free_raw(packed_up_dev).unwrap();
                runtime.free_raw(scales_up_dev).unwrap();
            }
        }
    }

    /// Byte-for-byte parity of the fused SkipSimplifiedLayerNormalization
    /// epilogue/prologue against the standalone three-op sequence
    /// (`preceding MatMulNBits` → `SkipSimplifiedLayerNormalization` →
    /// `following MatMulNBits`) on GPU.
    ///
    /// The reference path runs the exact production kernels: a plain preceding
    /// GEMV, the standalone `skip_rmsnorm_f16_warp_half4` kernel (producing the
    /// normalized output and the residual sum), then a plain following GEMV. The
    /// fused path folds the residual add into the preceding GEMV's bias-slot
    /// epilogue and the RMS normalization into the following GEMV's prologue. The
    /// residual sum (`preceding fused output`) must equal the standalone norm's
    /// `input_skip_bias_sum`, and the final projection must be bit-identical —
    /// for decode (M==1) and prefill (M>1), with and without a following bias.
    #[test]
    fn fused_skip_rmsnorm_is_bit_exact_to_three_op_path() {
        run_fused_skip_rmsnorm_parity(DataType::Float16, 4, false);
    }

    /// Phi-4-mini exports its `SkipSimplifiedLayerNormalization` gamma in fp32.
    /// The fused RMS-norm-prologue GEMV must accept that fp32 gamma and stay
    /// bit-identical to the standalone (fp32-gamma) norm + GEMV pair, so the
    /// fusion fires on Phi as well as on Qwen (fp16 gamma).
    #[test]
    fn fused_skip_rmsnorm_fp32_gamma_is_bit_exact_to_three_op_path() {
        run_fused_skip_rmsnorm_parity(DataType::Float32, 4, false);
    }

    /// Phi-4-mini's qkv/down projections are int8 with non-trivial asymmetric
    /// zero points. The fused int8 RMS-norm-prologue GEMV (following) and the
    /// int8 residual-fold epilogue (preceding) must stay bit-identical to the
    /// standalone int8 GEMV + skip_rmsnorm + int8 GEMV sequence at Phi's dims
    /// (down K=8192>hidden=3072, qkv hidden=3072<=N=5120), fp32 gamma. The
    /// asymmetric zero points make this a mutation guard: ignoring the zero
    /// point (or dropping to fp16 accumulation) diverges from the reference.
    #[test]
    fn fused_skip_rmsnorm_int8_asymmetric_zp_is_bit_exact_to_three_op_path() {
        run_fused_skip_rmsnorm_parity(DataType::Float32, 8, true);
    }

    fn run_fused_skip_rmsnorm_parity(gamma_dtype: DataType, bits: usize, explicit_zp: bool) {
        let Some(runtime) = runtime() else {
            eprintln!("skipping fused skip-rmsnorm parity test: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("matmul_nbits_gemv_f16")
            .is_err()
        {
            eprintln!("skipping fused skip-rmsnorm parity test: fp16 NVRTC headers unavailable");
            return;
        }

        // hidden % 128 == 0 (warp_half4 gate); preceding is a down projection
        // (pre_k > hidden), the following is a general projection (hidden <= n).
        // int8 exercises Phi's actual qkv/down dims; int4 keeps the Qwen shapes.
        let (hidden, pre_k, post_n) = if bits == 8 {
            (3072usize, 8192usize, 5120usize)
        } else {
            (896usize, QWEN_DOWN_K, 1152usize)
        };
        let epsilon = 1e-5f32;
        let block_size = 32usize;
        let blob_size = block_size * bits / 8;
        let device = DeviceId::cuda(0);

        for (m, following_bias) in [(1usize, false), (1, true), (5, true)] {
            let mut state = 0x51ce_d00d_f00d_1234u64;
            let mut next = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
            };

            // Pack random int4/int8 codes into the block-32 layout the kernels
            // unpack (nibble pairs for int4, one byte per weight for int8).
            let pack = |next: &mut dyn FnMut() -> f32, n: usize, k: usize| -> Vec<u8> {
                let k_blocks = k / block_size;
                let mut packed = vec![0u8; n * k_blocks * blob_size];
                if bits == 8 {
                    for byte in packed.iter_mut() {
                        *byte = ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                    return packed;
                }
                let mut quant = vec![0u8; n * k];
                for value in quant.iter_mut() {
                    *value = ((next() * 0.5 + 0.5) * 15.0).round().clamp(0.0, 15.0) as u8;
                }
                for col in 0..n {
                    for block in 0..k_blocks {
                        for pair in 0..blob_size {
                            let low = quant[col * k + block * block_size + pair * 2] & 15;
                            let high = quant[col * k + block * block_size + pair * 2 + 1] & 15;
                            packed[(col * k_blocks + block) * blob_size + pair] = low | (high << 4);
                        }
                    }
                }
                packed
            };

            // Non-uniform asymmetric zero points, one byte per block (int8) so the
            // dequant is `(code - zp) * scale`. `None` keeps the symmetric default
            // (zp == 128 for int8), preserving the byte-identical int4 path.
            let zp_bytes = |next: &mut dyn FnMut() -> f32, n: usize, k: usize| -> Vec<u8> {
                let k_blocks = k / block_size;
                (0..n * k_blocks)
                    .map(|_| (128.0 + (next() * 16.0)).round().clamp(96.0, 160.0) as u8)
                    .collect()
            };

            let pre_k_blocks = pre_k / block_size;
            let post_k_blocks = hidden / block_size;

            let activation: Vec<f16> = (0..m * pre_k).map(|_| f16::from_f32(next())).collect();
            let packed_pre = pack(&mut next, hidden, pre_k);
            let scales_pre: Vec<f16> = (0..hidden * pre_k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();
            let packed_post = pack(&mut next, post_n, hidden);
            let scales_post: Vec<f16> = (0..post_n * post_k_blocks)
                .map(|_| f16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
                .collect();
            // The residual is a plain fp16 activation, one hidden vector per token.
            let residual: Vec<f16> = (0..m * hidden).map(|_| f16::from_f32(next())).collect();
            // Gamma values are produced identically regardless of storage dtype;
            // fp16 keeps the byte-identical Qwen path, fp32 exercises Phi's export.
            let gamma_is_f32 = gamma_dtype == DataType::Float32;
            let gamma_f32: Vec<f32> = (0..hidden)
                .map(|_| 0.5 + 0.5 * (next() * 0.5 + 0.5))
                .collect();
            let gamma_bytes: Vec<u8> = if gamma_is_f32 {
                gamma_f32.iter().flat_map(|v| v.to_le_bytes()).collect()
            } else {
                gamma_f32
                    .iter()
                    .flat_map(|v| f16::from_f32(*v).to_le_bytes())
                    .collect()
            };
            let bias_post: Vec<f16> = (0..post_n).map(|_| f16::from_f32(next())).collect();
            // Per-block asymmetric zero points (int8 only); `explicit_zp == false`
            // uses the symmetric default and omits the input entirely.
            let zp_pre: Vec<u8> = if explicit_zp {
                zp_bytes(&mut next, hidden, pre_k)
            } else {
                Vec::new()
            };
            let zp_post: Vec<u8> = if explicit_zp {
                zp_bytes(&mut next, post_n, hidden)
            } else {
                Vec::new()
            };

            // Device buffers.
            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let packed_pre_dev = runtime.alloc_raw(packed_pre.len()).unwrap();
            let scales_pre_dev = runtime.alloc_raw(scales_pre.len() * 2).unwrap();
            let packed_post_dev = runtime.alloc_raw(packed_post.len()).unwrap();
            let scales_post_dev = runtime.alloc_raw(scales_post.len() * 2).unwrap();
            let residual_dev = runtime.alloc_raw(residual.len() * 2).unwrap();
            let gamma_dev = runtime.alloc_raw(gamma_bytes.len()).unwrap();
            let bias_post_dev = runtime.alloc_raw(bias_post.len() * 2).unwrap();
            let matmul_out_dev = runtime.alloc_raw(m * hidden * 2).unwrap();
            let normalized_dev = runtime.alloc_raw(m * hidden * 2).unwrap();
            let sum_dev = runtime.alloc_raw(m * hidden * 2).unwrap();
            let mean_dev = runtime.alloc_raw(m * 2).unwrap();
            let invstd_dev = runtime.alloc_raw(m * 2).unwrap();
            let y_ref_dev = runtime.alloc_raw(m * post_n * 2).unwrap();
            let pre_fused_dev = runtime.alloc_raw(m * hidden * 2).unwrap();
            let y_fused_dev = runtime.alloc_raw(m * post_n * 2).unwrap();
            let zp_pre_dev = explicit_zp.then(|| runtime.alloc_raw(zp_pre.len()).unwrap());
            let zp_post_dev = explicit_zp.then(|| runtime.alloc_raw(zp_post.len()).unwrap());

            // SAFETY: device buffers exactly cover their source slices.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(&packed_pre, packed_pre_dev).unwrap();
                runtime.htod(as_bytes(&scales_pre), scales_pre_dev).unwrap();
                runtime.htod(&packed_post, packed_post_dev).unwrap();
                runtime
                    .htod(as_bytes(&scales_post), scales_post_dev)
                    .unwrap();
                runtime.htod(as_bytes(&residual), residual_dev).unwrap();
                runtime.htod(&gamma_bytes, gamma_dev).unwrap();
                runtime.htod(as_bytes(&bias_post), bias_post_dev).unwrap();
                if let Some(dev) = zp_pre_dev {
                    runtime.htod(&zp_pre, dev).unwrap();
                }
                if let Some(dev) = zp_post_dev {
                    runtime.htod(&zp_post, dev).unwrap();
                }
            }

            // Tensor descriptors.
            let pre_a_shape = [m, pre_k];
            let pre_a_strides = [pre_k as i64, 1];
            let pre_b_shape = [hidden, pre_k_blocks, blob_size];
            let pre_b_strides = [(pre_k_blocks * blob_size) as i64, blob_size as i64, 1];
            let pre_scales_shape = [hidden, pre_k_blocks];
            let pre_scales_strides = [pre_k_blocks as i64, 1];
            let hidden_shape = [m, hidden];
            let hidden_strides = [hidden as i64, 1];
            let gamma_shape = [hidden];
            let gamma_strides = [1i64];
            let post_b_shape = [post_n, post_k_blocks, blob_size];
            let post_b_strides = [(post_k_blocks * blob_size) as i64, blob_size as i64, 1];
            let post_scales_shape = [post_n, post_k_blocks];
            let post_scales_strides = [post_k_blocks as i64, 1];
            let post_bias_shape = [post_n];
            let post_bias_strides = [1i64];
            let y_shape = [m, post_n];
            let y_strides = [post_n as i64, 1];
            let stat_shape = [m];
            let stat_strides = [1i64];

            let activation_view = TensorView::new(
                device_ptr(activation_dev),
                DataType::Float16,
                &pre_a_shape,
                &pre_a_strides,
                device,
            );
            let packed_pre_view = TensorView::new(
                device_ptr(packed_pre_dev),
                DataType::Uint8,
                &pre_b_shape,
                &pre_b_strides,
                device,
            );
            let scales_pre_view = TensorView::new(
                device_ptr(scales_pre_dev),
                DataType::Float16,
                &pre_scales_shape,
                &pre_scales_strides,
                device,
            );
            let packed_post_view = TensorView::new(
                device_ptr(packed_post_dev),
                DataType::Uint8,
                &post_b_shape,
                &post_b_strides,
                device,
            );
            let scales_post_view = TensorView::new(
                device_ptr(scales_post_dev),
                DataType::Float16,
                &post_scales_shape,
                &post_scales_strides,
                device,
            );
            let residual_view = TensorView::new(
                device_ptr(residual_dev),
                DataType::Float16,
                &hidden_shape,
                &hidden_strides,
                device,
            );
            let gamma_view = TensorView::new(
                device_ptr(gamma_dev),
                gamma_dtype,
                &gamma_shape,
                &gamma_strides,
                device,
            );
            let bias_post_view = TensorView::new(
                device_ptr(bias_post_dev),
                DataType::Float16,
                &post_bias_shape,
                &post_bias_strides,
                device,
            );
            let matmul_out_view = TensorView::new(
                device_ptr(matmul_out_dev),
                DataType::Float16,
                &hidden_shape,
                &hidden_strides,
                device,
            );
            let normalized_input_view = TensorView::new(
                device_ptr(normalized_dev),
                DataType::Float16,
                &hidden_shape,
                &hidden_strides,
                device,
            );
            let pre_fused_input_view = TensorView::new(
                device_ptr(pre_fused_dev),
                DataType::Float16,
                &hidden_shape,
                &hidden_strides,
                device,
            );
            // Asymmetric zero-point views (int8 only), one byte per block.
            let pre_zp_shape = [hidden, pre_k_blocks];
            let pre_zp_strides = [pre_k_blocks as i64, 1];
            let post_zp_shape = [post_n, post_k_blocks];
            let post_zp_strides = [post_k_blocks as i64, 1];
            let zp_pre_view = zp_pre_dev.map(|dev| {
                TensorView::new(
                    device_ptr(dev),
                    DataType::Uint8,
                    &pre_zp_shape,
                    &pre_zp_strides,
                    device,
                )
            });
            let zp_post_view = zp_post_dev.map(|dev| {
                TensorView::new(
                    device_ptr(dev),
                    DataType::Uint8,
                    &post_zp_shape,
                    &post_zp_strides,
                    device,
                )
            });

            let make_kernel = |k: usize, n: usize, fold: bool, rmsnorm: bool| MatMulNBitsKernel {
                runtime: runtime.clone(),
                k,
                n,
                bits,
                block_size,
                accuracy_level: 4,
                accuracy4_workspace: None,
                marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                constant_inputs: [true; 8],
                fold_bias_post_round: fold,
                gate_up_swiglu: false,
                decomposed_silu: false,
                rmsnorm_prologue: rmsnorm,
                rmsnorm_epsilon: epsilon,
                last_call_capture_safe: AtomicBool::new(false),
                bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
            };

            // ── Reference: preceding GEMV → skip_rmsnorm → following GEMV ──
            let preceding_ref = make_kernel(pre_k, hidden, false, false);
            {
                let mut matmul_out = TensorMut::new(
                    device_ptr_mut(matmul_out_dev),
                    DataType::Float16,
                    &hidden_shape,
                    &hidden_strides,
                    device,
                );
                preceding_ref
                    .run(
                        &{
                            let mut inputs =
                                vec![activation_view, packed_pre_view, scales_pre_view];
                            if let Some(zp) = zp_pre_view {
                                inputs.push(zp);
                            }
                            inputs
                        },
                        std::slice::from_mut(&mut matmul_out),
                        None,
                    )
                    .unwrap();
            }

            let mut skip_node = Node::new(
                onnx_runtime_ir::NodeId(0),
                "SkipSimplifiedLayerNormalization",
                Vec::new(),
                Vec::new(),
            );
            skip_node
                .attributes
                .insert("epsilon".into(), onnx_runtime_ir::Attribute::Float(epsilon));
            let skip_kernel = crate::kernels::normalization::SkipSimplifiedLayerNormFactory {
                runtime: runtime.clone(),
            }
            .create(&skip_node, &[])
            .unwrap();
            {
                let normalized = TensorMut::new(
                    device_ptr_mut(normalized_dev),
                    DataType::Float16,
                    &hidden_shape,
                    &hidden_strides,
                    device,
                );
                let mean = TensorMut::new(
                    device_ptr_mut(mean_dev),
                    DataType::Float16,
                    &stat_shape,
                    &stat_strides,
                    device,
                );
                let invstd = TensorMut::new(
                    device_ptr_mut(invstd_dev),
                    DataType::Float16,
                    &stat_shape,
                    &stat_strides,
                    device,
                );
                let sum = TensorMut::new(
                    device_ptr_mut(sum_dev),
                    DataType::Float16,
                    &hidden_shape,
                    &hidden_strides,
                    device,
                );
                skip_kernel
                    .execute(
                        &[matmul_out_view, residual_view, gamma_view],
                        &mut [normalized, mean, invstd, sum],
                    )
                    .unwrap();
            }

            let following_ref = make_kernel(hidden, post_n, false, false);
            {
                let mut y_ref = TensorMut::new(
                    device_ptr_mut(y_ref_dev),
                    DataType::Float16,
                    &y_shape,
                    &y_strides,
                    device,
                );
                let mut inputs = vec![normalized_input_view, packed_post_view, scales_post_view];
                if zp_post_view.is_some() || following_bias {
                    inputs.push(zp_post_view.unwrap_or(TensorView::absent(DataType::Uint8)));
                }
                if following_bias {
                    inputs.push(TensorView::absent(DataType::Int32));
                    inputs.push(bias_post_view);
                }
                following_ref
                    .run(&inputs, std::slice::from_mut(&mut y_ref), None)
                    .unwrap();
            }

            // ── Fused: residual epilogue in preceding, norm prologue in following ──
            let preceding_fused = make_kernel(pre_k, hidden, true, false);
            {
                let mut pre_fused = TensorMut::new(
                    device_ptr_mut(pre_fused_dev),
                    DataType::Float16,
                    &hidden_shape,
                    &hidden_strides,
                    device,
                );
                preceding_fused
                    .run(
                        &[
                            activation_view,
                            packed_pre_view,
                            scales_pre_view,
                            zp_pre_view.unwrap_or(TensorView::absent(DataType::Uint8)),
                            TensorView::absent(DataType::Int32),
                            residual_view,
                        ],
                        std::slice::from_mut(&mut pre_fused),
                        None,
                    )
                    .unwrap();
            }

            let following_fused = make_kernel(hidden, post_n, false, true);
            {
                let mut y_fused = TensorMut::new(
                    device_ptr_mut(y_fused_dev),
                    DataType::Float16,
                    &y_shape,
                    &y_strides,
                    device,
                );
                let mut inputs = vec![
                    pre_fused_input_view,
                    packed_post_view,
                    scales_post_view,
                    zp_post_view.unwrap_or(TensorView::absent(DataType::Uint8)),
                    TensorView::absent(DataType::Int32),
                ];
                if following_bias {
                    inputs.push(bias_post_view);
                } else {
                    inputs.push(TensorView::absent(DataType::Float16));
                }
                inputs.push(gamma_view);
                following_fused
                    .run(&inputs, std::slice::from_mut(&mut y_fused), None)
                    .unwrap();
            }

            runtime.synchronize().unwrap();

            let mut sum_host = vec![f16::ZERO; m * hidden];
            let mut pre_fused_host = vec![f16::ZERO; m * hidden];
            let mut y_ref_host = vec![f16::ZERO; m * post_n];
            let mut y_fused_host = vec![f16::ZERO; m * post_n];
            // SAFETY: host buffers match their device sources.
            unsafe {
                runtime.dtoh(as_bytes_mut(&mut sum_host), sum_dev).unwrap();
                runtime
                    .dtoh(as_bytes_mut(&mut pre_fused_host), pre_fused_dev)
                    .unwrap();
                runtime
                    .dtoh(as_bytes_mut(&mut y_ref_host), y_ref_dev)
                    .unwrap();
                runtime
                    .dtoh(as_bytes_mut(&mut y_fused_host), y_fused_dev)
                    .unwrap();
                for buffer in [
                    activation_dev,
                    packed_pre_dev,
                    scales_pre_dev,
                    packed_post_dev,
                    scales_post_dev,
                    residual_dev,
                    gamma_dev,
                    bias_post_dev,
                    matmul_out_dev,
                    normalized_dev,
                    sum_dev,
                    mean_dev,
                    invstd_dev,
                    y_ref_dev,
                    pre_fused_dev,
                    y_fused_dev,
                ] {
                    runtime.free_raw(buffer).unwrap();
                }
                for buffer in [zp_pre_dev, zp_post_dev].into_iter().flatten() {
                    runtime.free_raw(buffer).unwrap();
                }
            }

            // The preceding fused output is the residual sum (input + skip).
            for index in 0..m * hidden {
                assert_eq!(
                    pre_fused_host[index].to_bits(),
                    sum_host[index].to_bits(),
                    "residual epilogue diverged from skip_rmsnorm sum at M={m}, \
                     following_bias={following_bias}, token={}, column={}",
                    index / hidden,
                    index % hidden
                );
            }
            // The fused projection matches the three-op sequence. It is normally
            // bit-identical, EXCEPT two fp-reassociation sources make it merely
            // near-equal:
            //   (1) the asymmetric int8-zp M=1 case, where the three-op
            //       reference's standalone int8 GEMV routes to the split-K entry
            //       (K % 256 == 0, grid-starved), reordering the fp32 block-sum
            //       across K_SPLIT cooperating warps; and
            //   (2) any decode-shaped norm (num_groups <=
            //       SKIP_RMSNORM_BLOCK_MAX_GROUPS), where the reference's
            //       standalone SkipSimplifiedLayerNorm routes to the multi-warp
            //       `skip_rmsnorm_f16_block_half4` variant, which reduces the
            //       fp32 sum-of-squares in block-tree order while the fused norm
            //       prologue keeps the single-warp order.
            // Both are near-equal valid computations, so those paths are
            // validated to a tight magnitude-relative tolerance (which still
            // catches a dropped zero point or fp16 accumulation, both of which
            // diverge grossly) instead of byte-identity.
            let splitk_path = bits == 8 && explicit_zp && m == 1;
            let norm_block_reference =
                m as u32 <= crate::kernels::normalization::SKIP_RMSNORM_BLOCK_MAX_GROUPS;
            let near_equal = splitk_path || norm_block_reference;
            if near_equal {
                let mut max_abs = 0.0f32;
                let mut worst = 0.0f32;
                for index in 0..m * post_n {
                    let fused = y_fused_host[index].to_f32();
                    let reference = y_ref_host[index].to_f32();
                    assert!(
                        fused.is_finite(),
                        "near-equal fused int8-zp GEMV produced a non-finite output at M={m}, \
                         following_bias={following_bias}, column={}",
                        index % post_n
                    );
                    max_abs = max_abs.max(reference.abs());
                    worst = worst.max((fused - reference).abs());
                }
                let bound = (max_abs * 2e-3).max(1e-3);
                assert!(
                    worst < bound,
                    "fused norm prologue diverged (beyond fp reassociation) from \
                     skip_rmsnorm + GEMV at \
                     M={m}, following_bias={following_bias}: \
                     max_abs_diff={worst:.3e} bound={bound:.3e}"
                );
            } else {
                for index in 0..m * post_n {
                    assert_eq!(
                        y_fused_host[index].to_bits(),
                        y_ref_host[index].to_bits(),
                        "fused norm prologue diverged from skip_rmsnorm + GEMV at M={m}, \
                         following_bias={following_bias}, token={}, column={}",
                        index / post_n,
                        index % post_n
                    );
                }
            }
        }
    }

    /// The block-32 split-K decode GEMV narrows its fp16 epilogue straight into
    /// the caller's bf16 tensor instead of writing an fp16 staging buffer that
    /// `run_bf16` would then cast. That must be bit-identical to the staged
    /// route, because greedy decoding is only stable if every token is.
    ///
    /// The reference here is deliberately the staged route itself: run the fp16
    /// GEMV into an fp16 buffer, then `cast_half` it to bf16. That is exactly
    /// what the direct store replaces, and it is why the kernel rounds
    /// fp32 -> fp16 -> bf16 rather than fp32 -> bf16.
    ///
    /// The counter assertion is load-bearing. Without it a routing change that
    /// silently fell back to staging would still compare equal, and this test
    /// would pass while covering nothing.
    #[test]
    fn bf16_direct_store_matches_staged_cast_bit_for_bit() {
        use half::bf16;

        let Some(runtime) = runtime() else {
            eprintln!("skipping MatMulNBits bf16 direct-store test: CUDA runtime unavailable");
            return;
        };

        // Shaped to select `matmul_nbits_gemv_f16_scales_f16_zp_splitk`: block
        // 32, fp16-family scales, per-block zero points, K a multiple of 256,
        // and both dimensions past the small-shape (64-thread) path. K is at
        // the gate's measured split-K depth (see `ZP_SPLITK_BANDWIDTH_MIN_K`)
        // so the routing this test exists to cover is actually taken; the
        // counter assertion below fails loudly if that ever stops being true.
        let k = ZP_SPLITK_BANDWIDTH_MIN_K;
        let n = 2048usize;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;

        let mut state = 0x51ed_2701_c0ff_ee11u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let activation_bf16: Vec<bf16> = (0..k).map(|_| bf16::from_f32(next())).collect();
        let packed: Vec<u8> = (0..n * k_blocks * blob_size)
            .map(|_| next().to_bits() as u8)
            .collect();
        let scales_bf16: Vec<bf16> = (0..n * k_blocks)
            .map(|_| bf16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        let zero_points: Vec<u8> = (0..n * k_blocks.div_ceil(2))
            .map(|_| ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8)
            .collect();

        let device = DeviceId::cuda(0);
        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, k_blocks.div_ceil(2)];
        let zp_strides = [k_blocks.div_ceil(2) as i64, 1];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];

        let act_dev = runtime.alloc_raw(activation_bf16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scales_bf16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zero_points.len()).unwrap();
        let out_dev = runtime.alloc_raw(n * 2).unwrap();
        let act_f16_dev = runtime.alloc_raw(k * 2).unwrap();
        let scales_f16_dev = runtime.alloc_raw(scales_bf16.len() * 2).unwrap();
        let ref_f16_dev = runtime.alloc_raw(n * 2).unwrap();
        let ref_bf16_dev = runtime.alloc_raw(n * 2).unwrap();
        // SAFETY: device buffers exactly cover their source slices.
        unsafe {
            runtime.htod(as_bytes(&activation_bf16), act_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scales_bf16), scales_dev).unwrap();
            runtime.htod(&zero_points, zp_dev).unwrap();
        }

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 0,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        let bf16_inputs = vec![
            TensorView::new(
                device_ptr(act_dev),
                DataType::BFloat16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::BFloat16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];

        let before = BF16_DIRECT_OUT_STORES.with(|count| count.get());
        let mut got_out = [TensorMut::new(
            device_ptr_mut(out_dev),
            DataType::BFloat16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&bf16_inputs, &mut got_out, None).unwrap();
        runtime.synchronize().unwrap();
        let direct_stores = BF16_DIRECT_OUT_STORES.with(|count| count.get()) - before;

        // Reference: the staged route this replaces.
        super::super::cast::launch_cast_raw(
            &runtime,
            cuptr(act_dev as *const c_void),
            DataType::BFloat16,
            act_f16_dev,
            DataType::Float16,
            k,
        )
        .unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            cuptr(scales_dev as *const c_void),
            DataType::BFloat16,
            scales_f16_dev,
            DataType::Float16,
            scales_bf16.len(),
        )
        .unwrap();
        let ref_inputs = vec![
            TensorView::new(
                device_ptr(act_f16_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_f16_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];
        let mut ref_f16 = [TensorMut::new(
            device_ptr_mut(ref_f16_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&ref_inputs, &mut ref_f16, None).unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            ref_f16_dev,
            DataType::Float16,
            ref_bf16_dev,
            DataType::BFloat16,
            n,
        )
        .unwrap();
        runtime.synchronize().unwrap();

        let mut got = vec![bf16::ZERO; n];
        let mut want = vec![bf16::ZERO; n];
        // SAFETY: each host buffer matches its device source.
        unsafe {
            runtime.dtoh(as_bytes_mut(&mut got), out_dev).unwrap();
            runtime.dtoh(as_bytes_mut(&mut want), ref_bf16_dev).unwrap();
            for buffer in [
                act_dev,
                packed_dev,
                scales_dev,
                zp_dev,
                out_dev,
                act_f16_dev,
                scales_f16_dev,
                ref_f16_dev,
                ref_bf16_dev,
            ] {
                runtime.free_raw(buffer).unwrap();
            }
        }

        assert_eq!(
            direct_stores, 1,
            "the bf16 run did not take the direct-store path, so this test would \
             compare the staged route against itself"
        );
        for index in 0..n {
            assert_eq!(
                got[index].to_bits(),
                want[index].to_bits(),
                "direct bf16 store diverged from the staged cast at column {index}"
            );
        }
    }

    /// Regression guard for the small-batch loop. For
    /// `1 < m <= decode_gemv_loop_max_m()`, `run_f16` launches one single-row
    /// GEMV per row, and row 0 starts exactly at the staging pointer. An offer
    /// keyed on the pointer alone therefore let row 0 claim the whole bf16
    /// output, wrote only row 0's columns, and skipped the narrowing cast --
    /// leaving rows 1.. stale. The single-row parity test could not see this,
    /// and it was visible end to end as a diverging first sampled token.
    ///
    /// The offer now also carries the element count it covers, so a launch that
    /// writes one row of a multi-row output cannot accept it.
    #[test]
    fn bf16_direct_store_declines_the_small_batch_row_loop() {
        use half::bf16;

        let Some(runtime) = runtime() else {
            eprintln!(
                "skipping MatMulNBits bf16 small-batch direct-store test: CUDA runtime unavailable"
            );
            return;
        };
        // The loop this guards only exists when more than one row routes to the
        // per-row GEMV; with the loop disabled there is nothing to decline.
        if decode_gemv_loop_max_m() < 2 {
            eprintln!("skipping MatMulNBits bf16 small-batch direct-store test: row loop disabled");
            return;
        }

        let m = 2usize;
        let k = 2048usize;
        let n = 2048usize;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2;

        let mut state = 0x7c0f_fee5_1234_9876u64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let activation_bf16: Vec<bf16> = (0..m * k).map(|_| bf16::from_f32(next())).collect();
        let packed: Vec<u8> = (0..n * k_blocks * blob_size)
            .map(|_| next().to_bits() as u8)
            .collect();
        let scales_bf16: Vec<bf16> = (0..n * k_blocks)
            .map(|_| bf16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        let zero_points: Vec<u8> = (0..n * k_blocks.div_ceil(2))
            .map(|_| ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8)
            .collect();

        let device = DeviceId::cuda(0);
        let a_shape = [m, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, k_blocks.div_ceil(2)];
        let zp_strides = [k_blocks.div_ceil(2) as i64, 1];
        let y_shape = [m, n];
        let y_strides = [n as i64, 1];

        let act_dev = runtime.alloc_raw(activation_bf16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scales_bf16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zero_points.len()).unwrap();
        let out_dev = runtime.alloc_raw(m * n * 2).unwrap();
        let act_f16_dev = runtime.alloc_raw(m * k * 2).unwrap();
        let scales_f16_dev = runtime.alloc_raw(scales_bf16.len() * 2).unwrap();
        let ref_f16_dev = runtime.alloc_raw(m * n * 2).unwrap();
        let ref_bf16_dev = runtime.alloc_raw(m * n * 2).unwrap();
        // SAFETY: device buffers exactly cover their source slices.
        unsafe {
            runtime.htod(as_bytes(&activation_bf16), act_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scales_bf16), scales_dev).unwrap();
            runtime.htod(&zero_points, zp_dev).unwrap();
        }

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 0,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        let bf16_inputs = vec![
            TensorView::new(
                device_ptr(act_dev),
                DataType::BFloat16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::BFloat16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];

        let before = BF16_DIRECT_OUT_STORES.with(|count| count.get());
        let mut got_out = [TensorMut::new(
            device_ptr_mut(out_dev),
            DataType::BFloat16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&bf16_inputs, &mut got_out, None).unwrap();
        runtime.synchronize().unwrap();
        let direct_stores = BF16_DIRECT_OUT_STORES.with(|count| count.get()) - before;

        super::super::cast::launch_cast_raw(
            &runtime,
            cuptr(act_dev as *const c_void),
            DataType::BFloat16,
            act_f16_dev,
            DataType::Float16,
            m * k,
        )
        .unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            cuptr(scales_dev as *const c_void),
            DataType::BFloat16,
            scales_f16_dev,
            DataType::Float16,
            scales_bf16.len(),
        )
        .unwrap();
        let ref_inputs = vec![
            TensorView::new(
                device_ptr(act_f16_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_f16_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];
        let mut ref_f16 = [TensorMut::new(
            device_ptr_mut(ref_f16_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&ref_inputs, &mut ref_f16, None).unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            ref_f16_dev,
            DataType::Float16,
            ref_bf16_dev,
            DataType::BFloat16,
            m * n,
        )
        .unwrap();
        runtime.synchronize().unwrap();

        let mut got = vec![bf16::ZERO; m * n];
        let mut want = vec![bf16::ZERO; m * n];
        // SAFETY: each host buffer matches its device source.
        unsafe {
            runtime.dtoh(as_bytes_mut(&mut got), out_dev).unwrap();
            runtime.dtoh(as_bytes_mut(&mut want), ref_bf16_dev).unwrap();
            for buffer in [
                act_dev,
                packed_dev,
                scales_dev,
                zp_dev,
                out_dev,
                act_f16_dev,
                scales_f16_dev,
                ref_f16_dev,
                ref_bf16_dev,
            ] {
                runtime.free_raw(buffer).unwrap();
            }
        }

        assert_eq!(
            direct_stores, 0,
            "a per-row launch accepted the whole-output direct-store offer; rows \
             past the first would be left stale"
        );
        for index in 0..m * n {
            assert_eq!(
                got[index].to_bits(),
                want[index].to_bits(),
                "small-batch bf16 output diverged at row {}, column {}",
                index / n,
                index % n
            );
        }
    }

    /// The BFloat16 activation path caches its Float16-staged **constant** scales
    /// across calls (see [`Bf16ConstCache`]) instead of re-casting them every
    /// step. This must stay bit-identical to inline per-call staging: converting
    /// BFloat16 -> Float16 yields the same bits whether done once or repeatedly,
    /// and the tuned fp16 GEMV then reads identical scales. This test runs the
    /// bf16 path twice (cache miss, then cache hit) and compares it, bit for bit,
    /// to a reference that stages every bf16 input to Float16 inline.
    #[test]
    fn bf16_scale_cache_is_bit_exact_to_inline_staging() {
        use half::bf16;

        let Some(runtime) = runtime() else {
            eprintln!("skipping MatMulNBits bf16 scale-cache test: CUDA runtime unavailable");
            return;
        };

        let k = 256usize;
        let n = 64usize;
        let block_size = 32usize;
        let k_blocks = k / block_size;
        let blob_size = block_size / 2; // int4: two weights per byte

        let mut state = 0x0bad_c0de_dead_beefu64;
        let mut next = || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((state >> 33) as f32 / u32::MAX as f32) * 2.0 - 1.0
        };

        let activation_bf16: Vec<bf16> = (0..k).map(|_| bf16::from_f32(next())).collect();
        let packed: Vec<u8> = (0..n * k_blocks * blob_size)
            .map(|_| next().to_bits() as u8)
            .collect();
        let scales_bf16: Vec<bf16> = (0..n * k_blocks)
            .map(|_| bf16::from_f32(0.015 + 0.01 * (next() * 0.5 + 0.5)))
            .collect();
        let zero_points: Vec<u8> = (0..n * k_blocks.div_ceil(2))
            .map(|_| ((next() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8)
            .collect();

        let device = DeviceId::cuda(0);
        let a_shape = [1usize, k];
        let a_strides = [k as i64, 1];
        let b_shape = [n, k_blocks, blob_size];
        let b_strides = [(k_blocks * blob_size) as i64, blob_size as i64, 1];
        let scales_shape = [n, k_blocks];
        let scales_strides = [k_blocks as i64, 1];
        let zp_shape = [n, k_blocks.div_ceil(2)];
        let zp_strides = [k_blocks.div_ceil(2) as i64, 1];
        let y_shape = [1usize, n];
        let y_strides = [n as i64, 1];

        let act_dev = runtime.alloc_raw(activation_bf16.len() * 2).unwrap();
        let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
        let scales_dev = runtime.alloc_raw(scales_bf16.len() * 2).unwrap();
        let zp_dev = runtime.alloc_raw(zero_points.len()).unwrap();
        let out1_dev = runtime.alloc_raw(n * 2).unwrap();
        let out2_dev = runtime.alloc_raw(n * 2).unwrap();
        // SAFETY: device buffers exactly cover their source slices.
        unsafe {
            runtime.htod(as_bytes(&activation_bf16), act_dev).unwrap();
            runtime.htod(&packed, packed_dev).unwrap();
            runtime.htod(as_bytes(&scales_bf16), scales_dev).unwrap();
            runtime.htod(&zero_points, zp_dev).unwrap();
        }

        let inputs = vec![
            TensorView::new(
                device_ptr(act_dev),
                DataType::BFloat16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_dev),
                DataType::BFloat16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];

        let kernel = MatMulNBitsKernel {
            runtime: runtime.clone(),
            k,
            n,
            bits: 4,
            block_size,
            accuracy_level: 0,
            accuracy4_workspace: None,
            marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
            constant_inputs: [true; 8],
            fold_bias_post_round: false,
            gate_up_swiglu: false,
            decomposed_silu: false,
            rmsnorm_prologue: false,
            rmsnorm_epsilon: 1e-5,
            last_call_capture_safe: AtomicBool::new(false),
            bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
            bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
        };

        let mut out1 = [TensorMut::new(
            device_ptr_mut(out1_dev),
            DataType::BFloat16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&inputs, &mut out1, None).unwrap();
        let mut out2 = [TensorMut::new(
            device_ptr_mut(out2_dev),
            DataType::BFloat16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&inputs, &mut out2, None).unwrap();
        runtime.synchronize().unwrap();

        // Reference: stage every bf16 input to Float16 inline (no cache) and run
        // the fp16 GEMV directly, then narrow to BFloat16 exactly as run_bf16 does.
        let act_f16_dev = runtime.alloc_raw(k * 2).unwrap();
        let scales_f16_dev = runtime.alloc_raw(scales_bf16.len() * 2).unwrap();
        let ref_f16_dev = runtime.alloc_raw(n * 2).unwrap();
        let ref_bf16_dev = runtime.alloc_raw(n * 2).unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            cuptr(act_dev as *const c_void),
            DataType::BFloat16,
            act_f16_dev,
            DataType::Float16,
            k,
        )
        .unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            cuptr(scales_dev as *const c_void),
            DataType::BFloat16,
            scales_f16_dev,
            DataType::Float16,
            scales_bf16.len(),
        )
        .unwrap();
        let ref_inputs = vec![
            TensorView::new(
                device_ptr(act_f16_dev),
                DataType::Float16,
                &a_shape,
                &a_strides,
                device,
            ),
            TensorView::new(
                device_ptr(packed_dev),
                DataType::Uint8,
                &b_shape,
                &b_strides,
                device,
            ),
            TensorView::new(
                device_ptr(scales_f16_dev),
                DataType::Float16,
                &scales_shape,
                &scales_strides,
                device,
            ),
            TensorView::new(
                device_ptr(zp_dev),
                DataType::Uint8,
                &zp_shape,
                &zp_strides,
                device,
            ),
        ];
        let mut ref_f16 = [TensorMut::new(
            device_ptr_mut(ref_f16_dev),
            DataType::Float16,
            &y_shape,
            &y_strides,
            device,
        )];
        kernel.run(&ref_inputs, &mut ref_f16, None).unwrap();
        super::super::cast::launch_cast_raw(
            &runtime,
            ref_f16_dev,
            DataType::Float16,
            ref_bf16_dev,
            DataType::BFloat16,
            n,
        )
        .unwrap();
        runtime.synchronize().unwrap();

        let mut got1 = vec![bf16::ZERO; n];
        let mut got2 = vec![bf16::ZERO; n];
        let mut want = vec![bf16::ZERO; n];
        // SAFETY: each host buffer matches its device source.
        unsafe {
            runtime.dtoh(as_bytes_mut(&mut got1), out1_dev).unwrap();
            runtime.dtoh(as_bytes_mut(&mut got2), out2_dev).unwrap();
            runtime.dtoh(as_bytes_mut(&mut want), ref_bf16_dev).unwrap();
            for buffer in [
                act_dev,
                packed_dev,
                scales_dev,
                zp_dev,
                out1_dev,
                out2_dev,
                act_f16_dev,
                scales_f16_dev,
                ref_f16_dev,
                ref_bf16_dev,
            ] {
                runtime.free_raw(buffer).unwrap();
            }
        }

        for index in 0..n {
            assert_eq!(
                got1[index].to_bits(),
                got2[index].to_bits(),
                "cached bf16 scale path is non-deterministic across steps at column {index}"
            );
            assert_eq!(
                got1[index].to_bits(),
                want[index].to_bits(),
                "cached bf16 scale path diverged from inline staging at column {index}"
            );
        }
    }

    /// Achieved-bandwidth probe for the int4 decode GEMV, swept over the REAL
    /// projection shapes of the 30B model this repo is tuned against.
    ///
    /// # Why this exists
    ///
    /// Issue #1574 established that decode reaches only ~20% of the A100 weight
    /// -bandwidth roofline and that the INT4 GEMVs run at 18-26% of HBM peak.
    /// Confirming that took a four-step nsys ritual per data point — profile at
    /// 32 tokens, profile at 96, export both to sqlite, subtract to strip the
    /// load/prefill fixed costs — and every step had a way to silently produce a
    /// wrong answer (see the nsys notes in `measurement-discipline`). That is far
    /// too slow and too failure-prone a loop to iterate a kernel against.
    ///
    /// This probe collapses it: it drives the SAME dispatch the model decodes
    /// with (`MatMulNBitsKernel::run`), at the same shapes, and reports the
    /// number the kernel work is actually bounded by — achieved read bandwidth.
    /// There is no graph capture, no prefill, and no load phase to subtract, so
    /// the reading needs no differencing to be meaningful.
    ///
    /// # The shapes are not invented
    ///
    /// They are every distinct `MatMulNBits` shape in the model's decoder graph,
    /// with the exact per-token call counts, so the weighted total is the whole
    /// token's GEMV cost rather than a microbenchmark of one favourable case.
    /// The counts sum to 416 nodes/token, which is exactly the per-token
    /// `matmul_nbits` launch count observed under nsys — that agreement is what
    /// makes the extrapolated tok/s below a fair prediction rather than a guess.
    ///
    /// # Reading the output
    ///
    /// The headline is the last line: decode tok/s implied by GEMV time ALONE.
    /// It is an UPPER BOUND on end-to-end decode — attention, norms, sampling and
    /// launch gaps are all excluded — so the gap between it and a real
    /// `profile_native` run is the non-GEMV budget, and the gap between it and
    /// the bandwidth roofline is what a better GEMV can still recover.
    ///
    /// Percent-of-peak is quoted against `A100_SXM4_80GB_PEAK_GBPS`. On any other
    /// device the GB/s column is still correct and the percentage is not; adjust
    /// the constant rather than trusting the ratio.
    ///
    /// # Two things this probe got wrong, and now controls for
    ///
    /// The first version of it reported the k/v projection at 28 GB/s and led to
    /// a filed issue about a starved GQA grid. Both the number and the issue were
    /// artifacts:
    ///
    /// 1. **Host dispatch inside the timing window.** Bracketing a single
    ///    `run()` between two events measures the host as well as the kernel,
    ///    and `run()` costs ~24 us. That is larger than several of these kernels.
    ///    The timed region is now a captured CUDA graph, which is also what
    ///    production decode replays. k/v went from 23.9 us to 4.6 us -- the
    ///    "pathology" was five sixths measurement overhead. The host cost is
    ///    still reported, in its own column, because it is the real ceiling for
    ///    any path that is not captured.
    /// 2. **An unramped clock.** An idle A100 in this box sits at 210 MHz
    ///    against a 1410 MHz maximum with persistence mode off, and a short probe
    ///    reports whatever partial ramp it caught. This cost 17% on the widest
    ///    shape, and which way it biased an A/B depended on whether a neighbour
    ///    happened to be using an adjacent GPU. The sweep is now preceded by a
    ///    ramp that runs until the timing stops improving AND at least 8 s of
    ///    continuous work has elapsed, and it re-measures the first shape at the
    ///    end to prove the device did not drift underneath the comparison.
    ///
    /// The general lesson, which applies to the next probe as much as this one:
    /// an absolute number from a microbenchmark is worth nothing until something
    /// independent agrees with it. Here the check is that per-shape times must be
    /// ordered by bytes moved. When k/v (1 MB) appeared SLOWER than q (16 MB),
    /// that was the signal -- and it pointed at the probe, not the kernel.
    #[test]
    #[ignore = "perf microbench; requires a dedicated idle SM80+ CUDA device"]
    fn decode_gemv_achieved_bandwidth_by_projection_shape() {
        use cudarc::driver::result::event;
        use cudarc::driver::sys;
        use cudarc::driver::sys::CUdeviceptr;

        /// Datasheet HBM2e peak of the box this was written against. Only the
        /// percent-of-peak column depends on it.
        const A100_SXM4_80GB_PEAK_GBPS: f64 = 2039.0;
        /// `(K, N, calls_per_token, label)` — every distinct decoder GEMV shape.
        const SHAPES: [(usize, usize, usize, &str); 6] = [
            (6656, 19968, 104, "gate/up"),
            (19968, 6656, 52, "down"),
            (6656, 4096, 104, "q"),
            (4096, 6656, 52, "o"),
            (6656, 202048, 1, "lm_head"),
            (6656, 256, 104, "k/v (GQA)"),
        ];
        const BLOCK: usize = 32;

        let Some(runtime) = runtime() else {
            eprintln!("skipping GEMV bandwidth probe: CUDA runtime unavailable");
            return;
        };
        if runtime
            .require_nvrtc_half_headers("gemv bandwidth probe")
            .is_err()
        {
            eprintln!("skipping GEMV bandwidth probe: fp16 NVRTC headers unavailable");
            return;
        }
        runtime.bind().unwrap();
        let reps = zc_env_usize("GEMV_PROBE_REPS", 15).max(5);

        /// Everything one shape needs to be launched repeatedly. Device buffers
        /// are allocated once and reused so the ramp below is not paying for
        /// allocation, and so all shapes are resident while any is measured.
        struct ShapeBench {
            kernel: MatMulNBitsKernel,
            label: &'static str,
            k: usize,
            n: usize,
            calls: usize,
            k_blocks: usize,
            blob_size: usize,
            zp_row_bytes: usize,
            activation_dev: CUdeviceptr,
            packed_dev: CUdeviceptr,
            scales_dev: CUdeviceptr,
            zp_dev: CUdeviceptr,
            output_dev: CUdeviceptr,
            /// Weights + scales + zero points. The fp16 activation (2*K bytes)
            /// and the fp16 output (2*N) are three orders of magnitude smaller at
            /// these shapes and are left out so the number is unambiguously
            /// weight traffic.
            bytes: f64,
        }

        impl ShapeBench {
            fn launch(&self) {
                let a_shape = [1usize, self.k];
                let a_strides = [self.k as i64, 1];
                let b_shape = [self.n, self.k_blocks, self.blob_size];
                let b_strides = [
                    (self.k_blocks * self.blob_size) as i64,
                    self.blob_size as i64,
                    1,
                ];
                let scales_shape = [self.n, self.k_blocks];
                let scales_strides = [self.k_blocks as i64, 1];
                let zp_shape = [self.n, self.zp_row_bytes];
                let zp_strides = [self.zp_row_bytes as i64, 1];
                let y_shape = [1usize, self.n];
                let y_strides = [self.n as i64, 1];
                let device = DeviceId::cuda(0);
                let inputs = vec![
                    TensorView::new(
                        device_ptr(self.activation_dev),
                        DataType::Float16,
                        &a_shape,
                        &a_strides,
                        device,
                    ),
                    TensorView::new(
                        device_ptr(self.packed_dev),
                        DataType::Uint8,
                        &b_shape,
                        &b_strides,
                        device,
                    ),
                    TensorView::new(
                        device_ptr(self.scales_dev),
                        DataType::Float16,
                        &scales_shape,
                        &scales_strides,
                        device,
                    ),
                    TensorView::new(
                        device_ptr(self.zp_dev),
                        DataType::Uint8,
                        &zp_shape,
                        &zp_strides,
                        device,
                    ),
                ];
                let mut outputs = [TensorMut::new(
                    device_ptr_mut(self.output_dev),
                    DataType::Float16,
                    &y_shape,
                    &y_strides,
                    device,
                )];
                self.kernel.run(&inputs, &mut outputs, None).unwrap();
            }

            /// Median GPU milliseconds per launch, plus the host milliseconds
            /// spent enqueueing one.
            ///
            /// The two are separated on purpose, and the separation is the whole
            /// reason this helper is not three lines long. Bracketing ONE launch
            /// between two events measures neither: `cuEventRecord` timestamps
            /// the stream, so a start event, a host-side `run()` and an end event
            /// enclose the host dispatch as well as the kernel, and `run()` is
            /// not cheap -- it re-reads tuning env vars, re-derives the launch
            /// geometry and re-looks-up the NVRTC entry on every call. Measured
            /// that way the k/v projection appeared to spend 35 us moving 1 MB,
            /// which is 30 GB/s and absurd; almost all of it was the host.
            ///
            /// So enqueue `BATCH` launches between the events. The host runs
            /// ahead of the stream, consecutive kernels execute back to back, and
            /// the elapsed time divided by `BATCH` is the kernel. This is also
            /// what production decode sees, because CUDA graph replay removes the
            /// per-launch host work entirely.
            ///
            /// The host cost is still worth knowing -- it is the ceiling a
            /// non-captured path would hit -- so it is timed separately, by
            /// wall-clocking the enqueue loop before any synchronisation.
            fn median_ms(&self, reps: usize) -> (f64, f64) {
                const BATCH: usize = 32;
                let runtime = &self.kernel.runtime;

                // Host cost first, on the uncaptured path, because that is the
                // path whose host cost is interesting.
                let mut host = Vec::with_capacity(reps);
                for _ in 0..reps {
                    let enqueue_begin = std::time::Instant::now();
                    for _ in 0..BATCH {
                        self.launch();
                    }
                    host.push(enqueue_begin.elapsed().as_secs_f64() * 1e3 / BATCH as f64);
                    runtime.synchronize().unwrap();
                }
                host.sort_by(|a, b| a.partial_cmp(b).unwrap());
                let host_ms = host[host.len() / 2];

                // Capture the batch into a graph so the timed loop contains no
                // host work at all. Without this the cheapest shapes cannot be
                // measured: the k/v projection's kernel and its `run()` dispatch
                // are both about 24 us, so the stream starves and the events
                // report the host, not the GPU.
                let captured = runtime.reset_graph().is_ok()
                    && runtime.begin_graph_capture(&[&self.kernel]).is_ok()
                    && {
                        for _ in 0..BATCH {
                            self.launch();
                        }
                        runtime.end_graph_capture().is_ok()
                    };
                if !captured {
                    runtime.abort_graph_capture().ok();
                }

                let mut gpu = Vec::with_capacity(reps);
                for _ in 0..reps {
                    let start = event::create(sys::CUevent_flags::CU_EVENT_DEFAULT).unwrap();
                    let end = event::create(sys::CUevent_flags::CU_EVENT_DEFAULT).unwrap();
                    // SAFETY: both events belong to this context and bracket the
                    // batch on the same stream the kernel enqueues to.
                    unsafe {
                        event::record(start, runtime.stream_ptr()).unwrap();
                        if captured {
                            runtime.replay_graph().unwrap();
                        } else {
                            for _ in 0..BATCH {
                                self.launch();
                            }
                        }
                        event::record(end, runtime.stream_ptr()).unwrap();
                        event::synchronize(end).unwrap();
                        gpu.push(event::elapsed(start, end).unwrap() as f64 / BATCH as f64);
                        event::destroy(start).ok();
                        event::destroy(end).ok();
                    }
                }
                runtime.reset_graph().ok();
                gpu.sort_by(|a, b| a.partial_cmp(b).unwrap());
                (gpu[gpu.len() / 2], host_ms)
            }
        }

        let mut benches = Vec::new();
        for (k, n, calls, label) in SHAPES {
            let k_blocks = k / BLOCK;
            let blob_size = BLOCK / 2;
            let zp_row_bytes = k_blocks.div_ceil(2);

            // Bandwidth does not depend on the VALUES, only on the traffic, so
            // fill with a cheap deterministic pattern instead of paying for a
            // realistic quantization (this keeps lm_head, at 672 MB of packed
            // weights, from dominating the probe's own runtime).
            let mut state = 0x9e37_79b9_7f4a_7c15u64;
            let mut next_byte = || {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                (state >> 56) as u8
            };
            let packed: Vec<u8> = (0..n * k_blocks * blob_size).map(|_| next_byte()).collect();
            let zp: Vec<u8> = (0..n * zp_row_bytes).map(|_| next_byte()).collect();
            let scales: Vec<f16> = (0..n * k_blocks).map(|_| f16::from_f32(0.02)).collect();
            let activation: Vec<f16> = (0..k).map(|_| f16::from_f32(0.01)).collect();

            let activation_dev = runtime.alloc_raw(activation.len() * 2).unwrap();
            let packed_dev = runtime.alloc_raw(packed.len()).unwrap();
            let scales_dev = runtime.alloc_raw(scales.len() * 2).unwrap();
            let zp_dev = runtime.alloc_raw(zp.len()).unwrap();
            let output_dev = runtime.alloc_raw(n * 2).unwrap();
            // SAFETY: every device buffer was sized from the slice it receives.
            unsafe {
                runtime.htod(as_bytes(&activation), activation_dev).unwrap();
                runtime.htod(&packed, packed_dev).unwrap();
                runtime.htod(as_bytes(&scales), scales_dev).unwrap();
                runtime.htod(&zp, zp_dev).unwrap();
            }

            let bench = ShapeBench {
                kernel: MatMulNBitsKernel {
                    runtime: runtime.clone(),
                    k,
                    n,
                    bits: 4,
                    block_size: BLOCK,
                    accuracy_level: 4,
                    accuracy4_workspace: None,
                    marlin_repack_cache: marlin_gemm::RepackCache::new(runtime.clone()),
                    constant_inputs: [true; 8],
                    fold_bias_post_round: false,
                    gate_up_swiglu: false,
                    decomposed_silu: false,
                    rmsnorm_prologue: false,
                    rmsnorm_epsilon: 1e-5,
                    last_call_capture_safe: AtomicBool::new(false),
                    bf16_scratch: Mutex::new(Bf16Scratch::new(runtime.clone())),
                    bf16_const_cache: Mutex::new(Bf16ConstCache::new(runtime.clone())),
                },
                label,
                k,
                n,
                calls,
                k_blocks,
                blob_size,
                zp_row_bytes,
                activation_dev,
                packed_dev,
                scales_dev,
                zp_dev,
                output_dev,
                bytes: (n * k_blocks * blob_size + n * k_blocks * 2 + n * zp_row_bytes) as f64,
            };
            // First call also compiles the NVRTC module; never time it.
            bench.launch();
            runtime.synchronize().unwrap();
            benches.push(bench);
        }

        // Bring the SM clock up BEFORE measuring anything. An idle A100 in this
        // box sits at 210 MHz against a 1410 MHz maximum and persistence mode is
        // off, so a probe that starts timing immediately reports whatever partial
        // ramp it happened to catch. That is not a small effect: the same code on
        // the same device measured 816 GB/s on a GPU another tenant had left warm
        // and 586 GB/s on an idle one -- a 1.4x swing with nothing changed. Any
        // A/B run across two such states is pure noise, and the direction of the
        // noise is set by which of the box's eight GPUs a neighbour is using.
        //
        // Rather than trust a fixed sleep, ramp until the timing itself stops
        // improving: that is the observable the clock actually controls, so it
        // needs no NVML and no privileges. `ramp` is deliberately the widest
        // shape so the device is loaded the way decode loads it.
        let ramp = &benches[0];
        let ramp_start = std::time::Instant::now();
        let ramp_deadline = ramp_start + std::time::Duration::from_secs(30);
        let mut previous = f64::INFINITY;
        let mut ramp_trace = Vec::new();
        loop {
            let (now, _) = ramp.median_ms(5);
            ramp_trace.push(now * 1000.0);
            let settled = now > previous * 0.985;
            previous = now;
            // Convergence alone is not enough: two short readings agree long
            // before the clock is done climbing. A first attempt at this loop
            // stopped at "107 -> 107 us" and the very same shape then measured
            // 90 us at the end of the sweep -- a 16% drift the ramp had declared
            // settled. So also demand a floor on how long the device has been
            // kept busy, which is what the clock actually responds to.
            if settled && ramp_start.elapsed() >= std::time::Duration::from_secs(8) {
                break;
            }
            if std::time::Instant::now() >= ramp_deadline {
                eprintln!(
                    "WARNING: clock had not settled after 30 s of ramping; \
                     absolute numbers below are not comparable across runs"
                );
                break;
            }
        }
        let ramp_best = ramp_trace.iter().cloned().fold(f64::INFINITY, f64::min);
        println!(
            "clock ramp on {}: {:.0} -> {:.0} us over {} readings in {:.1} s \
             (best {:.0} us, {:.0}% off the first)",
            ramp.label,
            ramp_trace[0],
            ramp_trace[ramp_trace.len() - 1],
            ramp_trace.len(),
            ramp_start.elapsed().as_secs_f64(),
            ramp_best,
            100.0 * (ramp_trace[0] - ramp_best) / ramp_trace[0]
        );

        let mut total_ms_per_token = 0.0f64;
        let mut total_bytes_per_token = 0.0f64;
        println!(
            "{:<10} {:>7} {:>7} {:>6} {:>10} {:>9} {:>7} {:>9} {:>7} {:>9}",
            "shape",
            "K",
            "N",
            "calls",
            "median_us",
            "MB/call",
            "GB/s",
            "%peak",
            "ms/tok",
            "host_us"
        );

        let (first_before, _) = benches[0].median_ms(reps);
        let mut total_host_ms_per_token = 0.0f64;
        for bench in &benches {
            let (median_ms, host_ms) = bench.median_ms(reps);
            total_host_ms_per_token += host_ms * bench.calls as f64;
            let gbps = bench.bytes / (median_ms * 1e-3) / 1e9;
            let ms_tok = median_ms * bench.calls as f64;
            total_ms_per_token += ms_tok;
            total_bytes_per_token += bench.bytes * bench.calls as f64;
            println!(
                "{:<10} {:>7} {:>7} {:>6} {:>10.1} {:>9.2} {:>7.0} {:>8.1}% {:>7.2} {:>9.1}",
                bench.label,
                bench.k,
                bench.n,
                bench.calls,
                median_ms * 1000.0,
                bench.bytes / 1e6,
                gbps,
                100.0 * gbps / A100_SXM4_80GB_PEAK_GBPS,
                ms_tok,
                host_ms * 1000.0
            );
        }

        // Re-read the first shape last. If the device drifted (clock throttle, a
        // neighbour starting work) the sweep above compared shapes measured under
        // different conditions, and the per-shape ranking is not trustworthy.
        let (first_after, _) = benches[0].median_ms(reps);
        let drift = (first_after - first_before).abs() / first_before;
        if drift > 0.03 {
            eprintln!(
                "WARNING: {} drifted {:.1}% across the sweep ({:.1} -> {:.1} us); \
                 the device was not stable and these rows are not comparable",
                benches[0].label,
                100.0 * drift,
                first_before * 1000.0,
                first_after * 1000.0
            );
        } else {
            println!("\ndevice stable across sweep: {:.1}% drift", 100.0 * drift);
        }

        for bench in &benches {
            // SAFETY: every pointer came from `alloc_raw` above and is freed once.
            unsafe {
                runtime.free_raw(bench.activation_dev).ok();
                runtime.free_raw(bench.packed_dev).ok();
                runtime.free_raw(bench.scales_dev).ok();
                runtime.free_raw(bench.zp_dev).ok();
                runtime.free_raw(bench.output_dev).ok();
            }
        }

        let aggregate_gbps = total_bytes_per_token / (total_ms_per_token * 1e-3) / 1e9;
        let implied_tps = 1000.0 / total_ms_per_token;
        let roofline_tps = A100_SXM4_80GB_PEAK_GBPS * 1e9 / total_bytes_per_token;
        println!(
            "\nweight traffic {:.2} GB/token, GEMV time {:.2} ms/token\n\
             aggregate achieved bandwidth {:.0} GB/s ({:.1}% of peak)\n\
             decode ceiling from GEMV alone: {:.1} tok/s (bandwidth roofline {:.1} tok/s)\n\
             host dispatch for the same launches: {:.2} ms/token \
             (uncaptured ceiling {:.1} tok/s)",
            total_bytes_per_token / 1e9,
            total_ms_per_token,
            aggregate_gbps,
            100.0 * aggregate_gbps / A100_SXM4_80GB_PEAK_GBPS,
            implied_tps,
            roofline_tps,
            total_host_ms_per_token,
            1000.0 / total_host_ms_per_token
        );
        assert!(
            implied_tps.is_finite() && implied_tps > 0.0,
            "GEMV bandwidth probe produced no usable timing"
        );
    }
}