baracuda-cutlass 0.0.1-alpha.68

Safe Rust wrapper for compiled CUTLASS kernels: plan-based GEMM and grouped GEMM with caller-supplied workspace, typed device-buffer arguments, and capture-safe launch.
Documentation
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
//! Plan-based GEMM and grouped-GEMM API.

use core::ffi::c_void;
use core::marker::PhantomData;

use baracuda_driver::{Context, PinnedBuffer, Stream};
use baracuda_kernels_types::BackendKind;

use crate::error::{status_to_result, Error, Result};
use crate::types::{
    ArchSku, BatchedGemmArgs, BatchedGemmDescriptor, BiasElement, CutlassElement, ElementKind,
    EpilogueKind, GemmArgs, GemmDescriptor, GemmSku, GroupedPlanPreference, GroupedProblem,
    GroupedScheduleMode, IntElement, IntGemmArgs, IntGemmDescriptor, LayoutSku, PlanPreference,
    PrecisionGuarantee, ScalarType, Workspace,
};

// ============================================================================
// Internal dispatch — generic-T → element-specific extern "C" entry point
// ============================================================================

mod dispatch {
    use super::{ElementKind, LayoutSku};
    use core::ffi::c_void;

    use super::EpilogueKind;

    /// Single-GEMM dispatch on sm_80 with a bias-family epilogue (Bias,
    /// BiasRelu, BiasGelu, BiasSilu).
    ///
    /// SKU coverage today: `{Rcr, Rrr} × {F16, Bf16, F32 (TF32),
    /// F32Strict (SIMT)}` for every bias-family epilogue. F64 routes
    /// through [`gemm_bias_sm80_run_f64`] because the FFI takes `f64`
    /// alpha/beta; that fork is selected at the call site based on
    /// `T::Scalar::IS_F64`. The non-bias path lives in
    /// [`gemm_sm80_run`].
    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_bias_sm80_run(
        layout: LayoutSku,
        kind: ElementKind,
        epilogue: EpilogueKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        bias: *const c_void,
        alpha: f32,
        beta: f32,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind, epilogue) {
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_bf16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_bf16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_bf16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_bf16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- Rrr layout ----
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_bf16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_bf16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_bf16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_bf16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- TF32 path (Rcr × F32) ----
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_tf32_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_tf32_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_tf32_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_tf32_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- TF32 path (Rrr × F32) ----
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_tf32_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_tf32_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_tf32_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_tf32_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- f32-SIMT path (Rcr × F32Strict) ----
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32_simt_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32_simt_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32_simt_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32_simt_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- f32-SIMT path (Rrr × F32Strict) ----
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32_simt_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32_simt_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32_simt_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32_simt_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            _ => 3,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn gemm_bias_sm80_workspace_size(
        layout: LayoutSku,
        kind: ElementKind,
        epilogue: EpilogueKind,
        m: i32,
        n: i32,
        k: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind, epilogue) {
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_bf16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_bf16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_bf16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_bf16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_bf16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_bf16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_bf16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_bf16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_tf32_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_tf32_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_tf32_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_tf32_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_tf32_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_tf32_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_tf32_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_tf32_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32_simt_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32_simt_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32_simt_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32_simt_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32_simt_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32_simt_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32_simt_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32_simt_rrr_sm80_workspace_size(m, n, k)
            },
            _ => 0,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_bias_sm80_can_implement(
        layout: LayoutSku,
        kind: ElementKind,
        epilogue: EpilogueKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        bias: *const c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind, epilogue) {
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_bf16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_bf16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_bf16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_bf16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_bf16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_bf16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_bf16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_bf16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_tf32_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_tf32_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_tf32_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_tf32_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_tf32_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_tf32_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_tf32_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_tf32_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32_simt_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32_simt_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32_simt_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32_simt_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32_simt_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32_simt_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32_simt_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32_simt_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            _ => 3,
        }
    }

    /// Single-GEMM dispatch on sm_80 — selects per `(layout, kind)`.
    ///
    /// SKU coverage: all `(Rcr|Rrr) × (F16|Bf16|F32-via-TF32)` are
    /// implemented. F32 routes through Ampere TF32 tensor cores. Any
    /// unknown pair returns status 3 (not implemented).
    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_sm80_run(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        alpha: f32,
        beta: f32,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_f16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_bf16_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_tf32_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_f16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_bf16_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_tf32_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict) => unsafe {
                k_sys::baracuda_cutlass_gemm_f32_simt_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict) => unsafe {
                k_sys::baracuda_cutlass_gemm_f32_simt_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // F64 has its own dispatcher (`gemm_sm80_run_f64`) because the
            // FFI takes `f64` alpha/beta. The plan layer routes F64 through
            // that path before reaching this function; this arm is
            // defensive.
            (LayoutSku::Rcr, ElementKind::F64)
            | (LayoutSku::Rrr, ElementKind::F64) => 3,
            // Integer element kinds (`S8`, `U8`) route through
            // [`int_gemm_sm80_run`] instead — this float-family
            // dispatcher should never see them when the plan layer is
            // wired correctly. `I32` is an accumulator-only kind and
            // is never a kernel input element.
            (_, ElementKind::S8) | (_, ElementKind::U8) | (_, ElementKind::I32)
            | (_, ElementKind::I64)
            | (_, ElementKind::Bool)
            | (_, ElementKind::Fp8E4M3)
            | (_, ElementKind::Fp8E5M2)
            | (_, ElementKind::S4)
            | (_, ElementKind::U4)
            | (_, ElementKind::Bin)
            | (_, ElementKind::Complex32)
            | (_, ElementKind::Complex64) => 3,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn gemm_sm80_workspace_size(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_f16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_bf16_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_tf32_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_f16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_bf16_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_tf32_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::F32Strict) => unsafe {
                k_sys::baracuda_cutlass_gemm_f32_simt_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, ElementKind::F32Strict) => unsafe {
                k_sys::baracuda_cutlass_gemm_f32_simt_rrr_sm80_workspace_size(m, n, k)
            },
            // F64 routes through its own dispatcher.
            (LayoutSku::Rcr, ElementKind::F64)
            | (LayoutSku::Rrr, ElementKind::F64) => 0,
            // Integer kinds route through `int_gemm_sm80_workspace_size`.
            // FP8 kinds route through baracuda-kernels-sys. Defensive arms;
            // never expected to fire here.
            (_, ElementKind::S8)
            | (_, ElementKind::U8)
            | (_, ElementKind::I32)
            | (_, ElementKind::I64)
            | (_, ElementKind::Bool)
            | (_, ElementKind::Fp8E4M3)
            | (_, ElementKind::Fp8E5M2)
            | (_, ElementKind::S4)
            | (_, ElementKind::U4)
            | (_, ElementKind::Bin)
            | (_, ElementKind::Complex32)
            | (_, ElementKind::Complex64) => 0,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_sm80_can_implement(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_f16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_bf16_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_tf32_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rrr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_f16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rrr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_bf16_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_tf32_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rcr, ElementKind::F32Strict) => unsafe {
                k_sys::baracuda_cutlass_gemm_f32_simt_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rrr, ElementKind::F32Strict) => unsafe {
                k_sys::baracuda_cutlass_gemm_f32_simt_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            // F64 routes through its own dispatcher.
            (LayoutSku::Rcr, ElementKind::F64)
            | (LayoutSku::Rrr, ElementKind::F64) => 3,
            // Integer kinds route through `int_gemm_sm80_can_implement`.
            (_, ElementKind::S8) | (_, ElementKind::U8) | (_, ElementKind::I32)
            | (_, ElementKind::I64)
            | (_, ElementKind::Bool)
            | (_, ElementKind::Fp8E4M3)
            | (_, ElementKind::Fp8E5M2)
            | (_, ElementKind::S4)
            | (_, ElementKind::U4)
            | (_, ElementKind::Bin)
            | (_, ElementKind::Complex32)
            | (_, ElementKind::Complex64) => 3,
        }
    }

    // ---------- f64 single-GEMM dispatch, sm_80 ----------
    //
    // Distinct from `gemm_sm80_run` because the FFI signature takes
    // `f64` alpha/beta. The plan layer routes through these when
    // `T::Scalar::IS_F64` is true.

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_sm80_run_f64(
        layout: LayoutSku,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        alpha: f64,
        beta: f64,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match layout {
            LayoutSku::Rcr => unsafe {
                k_sys::baracuda_cutlass_gemm_f64_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            LayoutSku::Rrr => unsafe {
                k_sys::baracuda_cutlass_gemm_f64_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn gemm_sm80_workspace_size_f64(layout: LayoutSku, m: i32, n: i32, k: i32) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match layout {
            LayoutSku::Rcr => unsafe {
                k_sys::baracuda_cutlass_gemm_f64_rcr_sm80_workspace_size(m, n, k)
            },
            LayoutSku::Rrr => unsafe {
                k_sys::baracuda_cutlass_gemm_f64_rrr_sm80_workspace_size(m, n, k)
            },
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_sm80_can_implement_f64(
        layout: LayoutSku,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match layout {
            LayoutSku::Rcr => unsafe {
                k_sys::baracuda_cutlass_gemm_f64_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            LayoutSku::Rrr => unsafe {
                k_sys::baracuda_cutlass_gemm_f64_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
        }
    }

    // ---------- f64 bias-fused GEMM dispatch, sm_80 ----------

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_bias_sm80_run_f64(
        layout: LayoutSku,
        epilogue: EpilogueKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        bias: *const c_void,
        alpha: f64,
        beta: f64,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, epilogue) {
            (LayoutSku::Rcr, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f64_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f64_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f64_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f64_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f64_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f64_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f64_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f64_rrr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // Identity not a bias-family epilogue; never reached when
            // `epilogue.requires_bias()` gates the call site.
            (_, EpilogueKind::Identity) => 3,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn gemm_bias_sm80_workspace_size_f64(
        layout: LayoutSku,
        epilogue: EpilogueKind,
        m: i32,
        n: i32,
        k: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, epilogue) {
            (LayoutSku::Rcr, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f64_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f64_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f64_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f64_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f64_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f64_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f64_rrr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rrr, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f64_rrr_sm80_workspace_size(m, n, k)
            },
            (_, EpilogueKind::Identity) => 0,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn gemm_bias_sm80_can_implement_f64(
        layout: LayoutSku,
        epilogue: EpilogueKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        bias: *const c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, epilogue) {
            (LayoutSku::Rcr, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f64_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f64_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f64_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rcr, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f64_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::Bias) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f64_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::BiasRelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f64_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::BiasGelu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f64_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (LayoutSku::Rrr, EpilogueKind::BiasSilu) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f64_rrr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (_, EpilogueKind::Identity) => 3,
        }
    }

    // ---------- batched GEMM, sm_80 ----------
    //
    // SKU coverage (status 3 = not implemented):
    //   - Rcr × {F16, Bf16}            ✓
    //   - Rcr × F32, all Rrr           ✗

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn batched_gemm_sm80_run(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        stride_a: i64,
        b: *const c_void,
        ldb: i64,
        stride_b: i64,
        c: *const c_void,
        ldc: i64,
        stride_c: i64,
        d: *mut c_void,
        ldd: i64,
        stride_d: i64,
        alpha: f32,
        beta: f32,
        batch_count: i32,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_batched_f16_rcr_sm80_run(
                    m, n, k,
                    a, lda, stride_a,
                    b, ldb, stride_b,
                    c, ldc, stride_c,
                    d, ldd, stride_d,
                    alpha, beta,
                    batch_count,
                    workspace, workspace_bytes,
                    stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_batched_bf16_rcr_sm80_run(
                    m, n, k,
                    a, lda, stride_a,
                    b, ldb, stride_b,
                    c, ldc, stride_c,
                    d, ldd, stride_d,
                    alpha, beta,
                    batch_count,
                    workspace, workspace_bytes,
                    stream,
                )
            },
            _ => 3,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn batched_gemm_sm80_workspace_size(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        batch_count: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_batched_f16_rcr_sm80_workspace_size(
                    m, n, k, batch_count,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_batched_bf16_rcr_sm80_workspace_size(
                    m, n, k, batch_count,
                )
            },
            _ => 0,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn batched_gemm_sm80_can_implement(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        stride_a: i64,
        b: *const c_void,
        ldb: i64,
        stride_b: i64,
        c: *const c_void,
        ldc: i64,
        stride_c: i64,
        d: *mut c_void,
        ldd: i64,
        stride_d: i64,
        batch_count: i32,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::F16) => unsafe {
                k_sys::baracuda_cutlass_gemm_batched_f16_rcr_sm80_can_implement(
                    m, n, k,
                    a, lda, stride_a,
                    b, ldb, stride_b,
                    c, ldc, stride_c,
                    d, ldd, stride_d,
                    batch_count,
                )
            },
            (LayoutSku::Rcr, ElementKind::Bf16) => unsafe {
                k_sys::baracuda_cutlass_gemm_batched_bf16_rcr_sm80_can_implement(
                    m, n, k,
                    a, lda, stride_a,
                    b, ldb, stride_b,
                    c, ldc, stride_c,
                    d, ldd, stride_d,
                    batch_count,
                )
            },
            _ => 3,
        }
    }

    // ---------- grouped GEMM, RCR sm_80 ----------

    #[cfg(feature = "sm80")]
    pub(super) unsafe fn grouped_gemm_rcr_sm80_sufficient(
        kind: ElementKind,
        h_m: *const i32,
        h_n: *const i32,
        h_k: *const i32,
        group_count: i32,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match kind {
            ElementKind::F16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_f16_rcr_sm80_sufficient(h_m, h_n, h_k, group_count)
            },
            ElementKind::Bf16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_bf16_rcr_sm80_sufficient(h_m, h_n, h_k, group_count)
            },
            ElementKind::F32
            | ElementKind::F32Strict
            | ElementKind::F64
            | ElementKind::S8
            | ElementKind::U8
            | ElementKind::I32
            | ElementKind::I64
            | ElementKind::Bool
            | ElementKind::Fp8E4M3
            | ElementKind::Fp8E5M2
            | ElementKind::S4
            | ElementKind::U4
            | ElementKind::Bin
            | ElementKind::Complex32
            | ElementKind::Complex64 => 0,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) unsafe fn grouped_gemm_rcr_sm80_scratch_bytes(
        kind: ElementKind,
        h_m: *const i32,
        h_n: *const i32,
        h_k: *const i32,
        group_count: i32,
        threadblock_count: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match kind {
            ElementKind::F16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_f16_rcr_sm80_scratch_bytes(
                    h_m, h_n, h_k, group_count, threadblock_count,
                )
            },
            ElementKind::Bf16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_bf16_rcr_sm80_scratch_bytes(
                    h_m, h_n, h_k, group_count, threadblock_count,
                )
            },
            ElementKind::F32
            | ElementKind::F32Strict
            | ElementKind::F64
            | ElementKind::S8
            | ElementKind::U8
            | ElementKind::I32
            | ElementKind::I64
            | ElementKind::Bool
            | ElementKind::Fp8E4M3
            | ElementKind::Fp8E5M2
            | ElementKind::S4
            | ElementKind::U4
            | ElementKind::Bin
            | ElementKind::Complex32
            | ElementKind::Complex64 => 0,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) unsafe fn grouped_gemm_rcr_sm80_can_implement(
        kind: ElementKind,
        h_m: *const i32,
        h_n: *const i32,
        h_k: *const i32,
        group_count: i32,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match kind {
            ElementKind::F16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_f16_rcr_sm80_can_implement(h_m, h_n, h_k, group_count)
            },
            ElementKind::Bf16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_bf16_rcr_sm80_can_implement(h_m, h_n, h_k, group_count)
            },
            ElementKind::F32
            | ElementKind::F32Strict
            | ElementKind::F64
            | ElementKind::S8
            | ElementKind::U8
            | ElementKind::I32
            | ElementKind::I64
            | ElementKind::Bool
            | ElementKind::Fp8E4M3
            | ElementKind::Fp8E5M2
            | ElementKind::S4
            | ElementKind::U4
            | ElementKind::Bin
            | ElementKind::Complex32
            | ElementKind::Complex64 => 3,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn grouped_gemm_rcr_sm80_run(
        kind: ElementKind,
        group_count: i32,
        threadblock_count: i32,
        d_problem_sizes: *const c_void,
        d_ptr_a: *const c_void,
        d_ptr_b: *const c_void,
        d_ptr_c: *const c_void,
        d_ptr_d: *mut c_void,
        d_lda: *const c_void,
        d_ldb: *const c_void,
        d_ldc: *const c_void,
        d_ldd: *const c_void,
        h_problem_sizes: *const c_void,
        alpha: f32,
        beta: f32,
        scratch: *mut c_void,
        scratch_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match kind {
            ElementKind::F16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_f16_rcr_sm80_run(
                    group_count, threadblock_count,
                    d_problem_sizes,
                    d_ptr_a, d_ptr_b, d_ptr_c, d_ptr_d,
                    d_lda, d_ldb, d_ldc, d_ldd,
                    h_problem_sizes,
                    alpha, beta,
                    scratch, scratch_bytes,
                    stream,
                )
            },
            ElementKind::Bf16 => unsafe {
                k_sys::baracuda_cutlass_grouped_gemm_bf16_rcr_sm80_run(
                    group_count, threadblock_count,
                    d_problem_sizes,
                    d_ptr_a, d_ptr_b, d_ptr_c, d_ptr_d,
                    d_lda, d_ldb, d_ldc, d_ldd,
                    h_problem_sizes,
                    alpha, beta,
                    scratch, scratch_bytes,
                    stream,
                )
            },
            ElementKind::F32
            | ElementKind::F32Strict
            | ElementKind::F64
            | ElementKind::S8
            | ElementKind::U8
            | ElementKind::I32
            | ElementKind::I64
            | ElementKind::Bool
            | ElementKind::Fp8E4M3
            | ElementKind::Fp8E5M2
            | ElementKind::S4
            | ElementKind::U4
            | ElementKind::Bin
            | ElementKind::Complex32
            | ElementKind::Complex64 => 3,
        }
    }

    // ============================================================================
    // int8 GEMM dispatch — Identity, RCR layout, sm_80
    // ============================================================================
    //
    // Identity int kernels: `LinearCombinationClamp` epilogue. Layout is
    // restricted to `Rcr` (`Rrr` is deferred — see lib.rs section header).
    // Element kind is restricted to S8 / U8. Alpha/beta are `f32` (CUTLASS
    // int8 dequant-in-epilogue convention).

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn int_gemm_rcr_sm80_run(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        alpha: f32,
        beta: f32,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::S8) => unsafe {
                k_sys::baracuda_cutlass_gemm_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (LayoutSku::Rcr, ElementKind::U8) => unsafe {
                k_sys::baracuda_cutlass_gemm_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // RRR int8 is deferred — CUTLASS 4.2.0 lacks the 8-bit
            // `TensorOpMultiplicandCongruous` warp iterator needed for
            // `RowMajor × RowMajor × OpClassTensorOp` instantiation.
            (LayoutSku::Rrr, ElementKind::S8) | (LayoutSku::Rrr, ElementKind::U8) => 3,
            // Defensive: float and I32 kinds should never reach this dispatcher.
            _ => 3,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn int_gemm_rcr_sm80_workspace_size(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::S8) => unsafe {
                k_sys::baracuda_cutlass_gemm_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (LayoutSku::Rcr, ElementKind::U8) => unsafe {
                k_sys::baracuda_cutlass_gemm_u8_rcr_sm80_workspace_size(m, n, k)
            },
            _ => 0,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn int_gemm_rcr_sm80_can_implement(
        layout: LayoutSku,
        kind: ElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        match (layout, kind) {
            (LayoutSku::Rcr, ElementKind::S8) => unsafe {
                k_sys::baracuda_cutlass_gemm_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rcr, ElementKind::U8) => unsafe {
                k_sys::baracuda_cutlass_gemm_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                )
            },
            (LayoutSku::Rrr, ElementKind::S8) | (LayoutSku::Rrr, ElementKind::U8) => 3,
            _ => 3,
        }
    }

    // ============================================================================
    // int8 bias-fused GEMM dispatch — RCR layout, sm_80
    // ============================================================================
    //
    // Bias kernels: `LinearCombinationBiasElementwise<int8, int32, float,
    // int8, int8, EPA=16, ActOp, plus<float>, false, ElementBias>`. The
    // four `Bias*` epilogues differ only in `ActOp`; the bias element
    // is independent of the matrix element and dispatched on
    // `bias_kind`. The 16 reachable arms = 2 sgn × 4 epi × 2 bias-type.

    use crate::types::BiasElementKind;

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn int_gemm_bias_rcr_sm80_run(
        layout: LayoutSku,
        kind: ElementKind,
        epilogue: EpilogueKind,
        bias_kind: BiasElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        bias: *const c_void,
        alpha: f32,
        beta: f32,
        workspace: *mut c_void,
        workspace_bytes: usize,
        stream: *mut c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        // RRR int8 deferred (see Identity dispatcher).
        if !matches!(layout, LayoutSku::Rcr) {
            return 3;
        }
        match (kind, epilogue, bias_kind) {
            // ---- s8 × f32 bias ----
            (ElementKind::S8, EpilogueKind::Bias, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasRelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasGelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasSilu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- s8 × i32 bias ----
            (ElementKind::S8, EpilogueKind::Bias, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_i32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasRelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_i32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasGelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_i32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasSilu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_i32bias_s8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- u8 × f32 bias ----
            (ElementKind::U8, EpilogueKind::Bias, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasRelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasGelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasSilu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // ---- u8 × i32 bias ----
            (ElementKind::U8, EpilogueKind::Bias, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_i32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasRelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_i32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasGelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_i32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasSilu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_i32bias_u8_rcr_sm80_run(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd,
                    bias, alpha, beta, workspace, workspace_bytes, stream,
                )
            },
            // Identity reaches here when called accidentally — bias is
            // required for the bias-family dispatchers. Identity routes
            // through `int_gemm_rcr_sm80_run` instead.
            (_, EpilogueKind::Identity, _) => 3,
            // Defensive: float / I32 kinds should never reach this dispatcher.
            _ => 3,
        }
    }

    #[cfg(feature = "sm80")]
    pub(super) fn int_gemm_bias_rcr_sm80_workspace_size(
        layout: LayoutSku,
        kind: ElementKind,
        epilogue: EpilogueKind,
        bias_kind: BiasElementKind,
        m: i32,
        n: i32,
        k: i32,
    ) -> usize {
        use baracuda_cutlass_kernels_sys as k_sys;
        if !matches!(layout, LayoutSku::Rcr) {
            return 0;
        }
        match (kind, epilogue, bias_kind) {
            (ElementKind::S8, EpilogueKind::Bias, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::BiasRelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::BiasGelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::BiasSilu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::Bias, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_i32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::BiasRelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_i32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::BiasGelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_i32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::S8, EpilogueKind::BiasSilu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_i32bias_s8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::Bias, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::BiasRelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::BiasGelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::BiasSilu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::Bias, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_i32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::BiasRelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_i32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::BiasGelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_i32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            (ElementKind::U8, EpilogueKind::BiasSilu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_i32bias_u8_rcr_sm80_workspace_size(m, n, k)
            },
            _ => 0,
        }
    }

    #[cfg(feature = "sm80")]
    #[allow(clippy::too_many_arguments)]
    pub(super) unsafe fn int_gemm_bias_rcr_sm80_can_implement(
        layout: LayoutSku,
        kind: ElementKind,
        epilogue: EpilogueKind,
        bias_kind: BiasElementKind,
        m: i32,
        n: i32,
        k: i32,
        a: *const c_void,
        lda: i64,
        b: *const c_void,
        ldb: i64,
        c: *const c_void,
        ldc: i64,
        d: *mut c_void,
        ldd: i64,
        bias: *const c_void,
    ) -> i32 {
        use baracuda_cutlass_kernels_sys as k_sys;
        if !matches!(layout, LayoutSku::Rcr) {
            return 3;
        }
        match (kind, epilogue, bias_kind) {
            (ElementKind::S8, EpilogueKind::Bias, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasRelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasGelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasSilu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::Bias, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_i32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasRelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_i32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasGelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_i32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::S8, EpilogueKind::BiasSilu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_i32bias_s8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::Bias, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_f32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasRelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_f32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasGelu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_f32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasSilu, BiasElementKind::F32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_f32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::Bias, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_i32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasRelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_relu_i32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasGelu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_gelu_i32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            (ElementKind::U8, EpilogueKind::BiasSilu, BiasElementKind::I32) => unsafe {
                k_sys::baracuda_cutlass_gemm_bias_silu_i32bias_u8_rcr_sm80_can_implement(
                    m, n, k, a, lda, b, ldb, c, ldc, d, ldd, bias,
                )
            },
            _ => 3,
        }
    }
}

// ============================================================================
// Host-side validation helpers
// ============================================================================

/// Minimum element count required to back a `(rows, cols, ld)` matrix at
/// the given layout. Returns `None` on overflow.
///
/// Assumes `rows >= 1` and `cols >= 1` (callers go through
/// [`check_descriptor`] which rejects non-positive dimensions first).
fn min_elements_row_major(rows: i32, cols: i32, ld: i64) -> Option<usize> {
    // [rows, cols] row-major: element [i, j] at offset i*ld + j.
    // Maximum addressable index = (rows - 1) * ld + (cols - 1), so the
    // buffer must hold (rows - 1) * ld + cols elements. Accepts padded
    // leading dimensions (ld > cols) without rejecting valid slabs.
    let r = (rows - 1) as i64;
    let needed = r.checked_mul(ld)?.checked_add(cols as i64)?;
    usize::try_from(needed).ok()
}

fn min_elements_col_major(rows: i32, cols: i32, ld: i64) -> Option<usize> {
    // [rows, cols] column-major: element [i, j] at offset j*ld + i.
    // Maximum addressable index = (cols - 1) * ld + (rows - 1).
    let c = (cols - 1) as i64;
    let needed = c.checked_mul(ld)?.checked_add(rows as i64)?;
    usize::try_from(needed).ok()
}

// Compatibility shims for the buffer-size tests below — they document
// the per-operand layout (A row-major, B column-major for Rcr, C/D
// row-major) so we keep separate names for clarity.
#[cfg(test)]
fn min_elements_rcr_a(rows: i32, cols: i32, ld: i64) -> Option<usize> {
    min_elements_row_major(rows, cols, ld)
}
#[cfg(test)]
fn min_elements_rcr_b(rows: i32, cols: i32, ld: i64) -> Option<usize> {
    min_elements_col_major(rows, cols, ld)
}
#[cfg(test)]
fn min_elements_rcr_cd(rows: i32, cols: i32, ld: i64) -> Option<usize> {
    min_elements_row_major(rows, cols, ld)
}

fn check_descriptor(desc: &GemmDescriptor) -> Result<()> {
    if desc.m <= 0 || desc.n <= 0 || desc.k <= 0 {
        return Err(Error::InvalidProblem("M, N, K must all be positive"));
    }
    // All shipped layouts (Rcr, Rrr) and epilogues (Identity) are
    // accepted by select; per-(layout, kind) implementability is
    // dispatched at run time to the kernel's own can_implement.
    Ok(())
}

fn check_args<T: CutlassElement>(desc: &GemmDescriptor, args: &GemmArgs<'_, T>) -> Result<()> {
    // Epilogue / bias must agree: any Bias* variant needs bias = Some,
    // Identity needs bias = None.
    match (desc.epilogue.requires_bias(), &args.bias) {
        (false, Some(_)) => {
            return Err(Error::InvalidProblem(
                "args.bias must be None when descriptor.epilogue is Identity",
            ));
        }
        (true, None) => {
            return Err(Error::InvalidProblem(
                "args.bias is required when descriptor.epilogue is in the Bias family \
                 (Bias / BiasRelu / BiasGelu / BiasSilu)",
            ));
        }
        (false, None) | (true, Some(_)) => {}
    }
    if let Some(bias) = &args.bias {
        if bias.len != desc.n {
            return Err(Error::InvalidProblem(
                "bias vector length must equal N",
            ));
        }
        if bias.stride != 1 {
            return Err(Error::Unsupported(
                "bias vector must be contiguous (stride 1) — strided bias not supported",
            ));
        }
        if bias.data.len() < desc.n as usize {
            return Err(Error::BufferTooSmall {
                needed: desc.n as usize,
                got: bias.data.len(),
            });
        }
    }
    if args.a.rows != desc.m || args.a.cols != desc.k {
        return Err(Error::InvalidProblem("A shape doesn't match descriptor (M, K)"));
    }
    if args.b.rows != desc.k || args.b.cols != desc.n {
        return Err(Error::InvalidProblem("B shape doesn't match descriptor (K, N)"));
    }
    if args.d.rows != desc.m || args.d.cols != desc.n {
        return Err(Error::InvalidProblem("D shape doesn't match descriptor (M, N)"));
    }
    if let Some(c) = &args.c {
        if c.rows != desc.m || c.cols != desc.n {
            return Err(Error::InvalidProblem("C shape doesn't match descriptor (M, N)"));
        }
    }
    // A is row-major in both Rcr and Rrr — leading dim along the K axis.
    if args.a.ld < desc.k as i64 {
        return Err(Error::InvalidProblem("A leading dimension must be >= K"));
    }
    // B's leading-dim minor depends on layout:
    //   Rcr: column-major [K, N], ld is along the K axis (rows).
    //   Rrr: row-major    [K, N], ld is along the N axis (cols).
    let b_min_ld = match desc.layout {
        LayoutSku::Rcr => desc.k as i64,
        LayoutSku::Rrr => desc.n as i64,
    };
    if args.b.ld < b_min_ld {
        return Err(Error::InvalidProblem(match desc.layout {
            LayoutSku::Rcr => "B leading dimension must be >= K (column-major Rcr layout)",
            LayoutSku::Rrr => "B leading dimension must be >= N (row-major Rrr layout)",
        }));
    }
    if args.d.ld < desc.n as i64 {
        return Err(Error::InvalidProblem("D leading dimension must be >= N"));
    }
    if let Some(c) = &args.c {
        if c.ld < desc.n as i64 {
            return Err(Error::InvalidProblem("C leading dimension must be >= N"));
        }
    }

    let need_a = min_elements_row_major(args.a.rows, args.a.cols, args.a.ld)
        .ok_or(Error::InvalidProblem("A storage size overflow"))?;
    if args.a.data.len() < need_a {
        return Err(Error::BufferTooSmall {
            needed: need_a,
            got: args.a.data.len(),
        });
    }
    let need_b = match desc.layout {
        LayoutSku::Rcr => min_elements_col_major(args.b.rows, args.b.cols, args.b.ld),
        LayoutSku::Rrr => min_elements_row_major(args.b.rows, args.b.cols, args.b.ld),
    }
    .ok_or(Error::InvalidProblem("B storage size overflow"))?;
    if args.b.data.len() < need_b {
        return Err(Error::BufferTooSmall {
            needed: need_b,
            got: args.b.data.len(),
        });
    }
    let need_d = min_elements_row_major(args.d.rows, args.d.cols, args.d.ld)
        .ok_or(Error::InvalidProblem("D storage size overflow"))?;
    if args.d.data.len() < need_d {
        return Err(Error::BufferTooSmall {
            needed: need_d,
            got: args.d.data.len(),
        });
    }
    if let Some(c) = &args.c {
        let need_c = min_elements_row_major(c.rows, c.cols, c.ld)
            .ok_or(Error::InvalidProblem("C storage size overflow"))?;
        if c.data.len() < need_c {
            return Err(Error::BufferTooSmall {
                needed: need_c,
                got: c.data.len(),
            });
        }
    }
    Ok(())
}

// ============================================================================
// cuBLAS backend — Phase 30 fast-path for f16/bf16 decode-regime FP GEMM
// ============================================================================
//
// Background (from `crates/baracuda-kernels-bench/BENCHMARKS.md`, Phase 29):
// baracuda's CUTLASS RCR plan emits `_sm80_` kernels (Ampere-tuned) for
// f16/bf16. On Ada (sm_89, RTX 4070) cuBLAS auto-dispatches to the
// sm_89 tensor-core path with an f32 accumulator and wins 2–4× at
// low-M (M=1 / M=32) decode shapes, narrowing to ~parity at M=128.
// This module hosts the cuBLAS Gemm fallback path that the
// [`GemmPlan::select`] heuristic dispatches to for those shapes.
//
// Coverage:
//   - f16, bf16, f32: `cublasGemmEx` with `CUBLAS_COMPUTE_32F`
//     (CUBLAS_GEMM_DEFAULT_TENSOR_OP algo, value 99).
//   - f64: `cublasDgemm` (no GemmEx needed — DGEMM is plenty fast).
//   - F32Strict: not supported (cuBLAS doesn't expose a strict-IEEE
//     SIMT path the way CUTLASS does; F32Strict callers stay on the
//     CUTLASS SIMT kernels for bit-stability).
//   - Bias / Bias* epilogues: not supported (cuBLAS-classic has no
//     fused-bias-activation; cuBLASLt does but is a separate API
//     surface). Forcing Cublas backend on a Bias* epilogue returns
//     `Error::Unsupported` from `select`.
//
// Layout mapping (baracuda Row/Col/Row → cuBLAS column-major):
// baracuda's RCR means A row-major [M, K], B column-major [K, N], D
// row-major [M, N]. cuBLAS is column-major, so we use the standard
// "C^T = B^T · A^T" trick: pass B as the first operand, A as the
// second, with `transa = Op::T` on both, and the resulting D in
// col-major IS our row-major D. For RRR the mapping changes the
// second `transa` to `Op::N`.

mod cublas_backend {
    use core::cell::RefCell;

    use baracuda_cublas::Handle as CublasHandle;
    use baracuda_driver::Stream;

    // Per-thread cache of cuBLAS handles, keyed by the raw context
    // pointer the handle was created against.
    //
    // cuBLAS handles are tied to the CUDA context current at the time
    // of `cublasCreate`. Caching by (thread, ctx-raw-ptr) means the
    // first call into the cuBLAS backend on a given thread pays the
    // (~100µs–ms) `cublasCreate` cost; subsequent calls reuse the
    // handle. Per-thread storage sidesteps the cuBLAS-handle `!Sync`
    // constraint (NVIDIA documents that a handle should only be
    // touched from one host thread at a time) and keeps
    // `super::GemmPlan` `Send + Sync` (the plan stores no handle —
    // it looks one up out of the thread-local on each `run`).
    //
    // A `Vec` keyed by raw context pointer is fine here: production
    // callers have one context per process, and even
    // multi-context callers rarely exceed a handful.
    thread_local! {
        static HANDLE_CACHE: RefCell<Vec<(usize, CublasHandle)>> =
            const { RefCell::new(Vec::new()) };
    }

    /// Fetch (or lazily create) the cuBLAS handle bound to `stream`'s
    /// context, with the handle's stream binding set to `stream`.
    ///
    /// The returned handle is `Clone`able (the inner state is `Arc`'d
    /// inside [`baracuda_cublas::Handle`]) so the caller can move it
    /// into the closure that calls `gemm_ex` / `gemm` without holding
    /// the thread-local `RefCell` borrow across the launch.
    pub(super) fn handle_for(stream: &Stream) -> crate::Result<CublasHandle> {
        // Use the context's raw pointer as the cache key. baracuda's
        // `Context` doesn't expose a stable id, but the inner CUDA
        // context pointer is unique per process and stable for the
        // context's lifetime.
        let ctx_key = stream.context().as_raw() as usize;
        let handle = HANDLE_CACHE.with(|cache| -> crate::Result<CublasHandle> {
            let mut cache = cache.borrow_mut();
            if let Some((_, h)) = cache.iter().find(|(k, _)| *k == ctx_key) {
                return Ok(h.clone());
            }
            // First touch on this thread for this context — create.
            // The current context must be the stream's context for
            // `cublasCreate` to bind correctly. baracuda's Context API
            // is push-based; we call `set_current` (idempotent if
            // already current) before the cuBLAS create.
            stream
                .context()
                .set_current()
                .map_err(crate::Error::Driver)?;
            // Retry handle creation under transient failure. Observed
            // empirically: when many test PROCESSES start in parallel
            // (the `cargo test --workspace` harness launches dozens of
            // binaries concurrently), the cuBLAS library's first-call
            // initialization races on a shared driver resource (DLL
            // loader / cuBLAS-side global lock) and `cublasCreate_v2`
            // intermittently returns CUBLAS_STATUS_ALLOC_FAILED or
            // CUBLAS_STATUS_NOT_INITIALIZED. The error is genuinely
            // transient — a 50ms backoff + retry clears it 100% of the
            // time on RTX 4070 / cuBLAS 12. Five retries with linear
            // backoff (50ms, 100ms, ..., 250ms) bounds the worst case
            // at ~750ms per first-touch, which is fine for what is
            // already a one-time-per-thread operation.
            let h = {
                let mut last_err = None;
                let mut handle: Option<CublasHandle> = None;
                for attempt in 0..5 {
                    match CublasHandle::new() {
                        Ok(h) => { handle = Some(h); break }
                        Err(e) => {
                            last_err = Some(e);
                            // Linear backoff: 50ms * (attempt + 1).
                            std::thread::sleep(std::time::Duration::from_millis(
                                50 * (attempt as u64 + 1),
                            ));
                        }
                    }
                }
                match handle {
                    Some(h) => h,
                    None => {
                        // Surface the underlying error code in the
                        // message for diagnostics. The retry loop is
                        // transparent on success — only the final
                        // failure path mentions exhaustion.
                        let _ = last_err; // dropped; cublas Error not in scope here
                        return Err(crate::Error::Unsupported(
                            "cuBLAS handle creation failed after 5 retries \
                             (library missing, device unavailable, or \
                             persistent driver-init contention)",
                        ));
                    }
                }
            };
            cache.push((ctx_key, h.clone()));
            Ok(h)
        })?;
        // Bind to the launch stream so the GEMM enqueues on the
        // caller-supplied stream rather than the default stream. The
        // bind is per-handle, sticky across calls — but a previously
        // cached handle could have been bound to a *different* stream
        // last time. Always re-bind.
        handle
            .set_stream(stream)
            .map_err(|_| crate::Error::Unsupported(
                "cuBLAS set_stream failed",
            ))?;
        Ok(handle)
    }
}

/// Algo selector for `cublasGemmEx`.
///
/// `-1` corresponds to `CUBLAS_GEMM_DEFAULT` / `CUBLAS_GEMM_DFALT` — the
/// "let cuBLAS pick" heuristic. In modern cuBLAS (CUDA 12+) when
/// `compute_type = Compute32F` the algo selector is largely advisory:
/// cuBLAS picks the kernel from its internal heuristic based on
/// (M, N, K, dtype) regardless of the value here. The Phase-29 bench's
/// reference cuBLAS-direct path passes `0` (CUBLAS_GEMM_ALGO0), which
/// is also routed through the same heuristic; both produce the same
/// kernel selection on the f16/bf16/f32 GemmEx paths.
///
/// `CUBLAS_GEMM_DEFAULT_TENSOR_OP` (= 99) would force a tensor-op
/// kernel even at very low M where cuBLAS's heuristic prefers a CUDA-
/// core kernel; benchmarking showed it was ~3× slower than `DEFAULT`
/// at M=1 on RTX 4070. Stick with `DEFAULT` (`-1`).
const CUBLAS_GEMM_ALGO: i32 = -1;

/// Backend the plan picked for this descriptor. Stored privately on
/// the plan; surfaced through [`GemmPlan::backend`].
///
/// Differs from `GemmSku::arch` in that it answers a *higher-level*
/// question: "which kernel library does this plan call into?" The arch
/// SKU only meaningfully describes the CUTLASS variant — CUTLASS itself
/// is one of several backends now that the Phase-30 cuBLAS fast-path
/// joined the dispatch surface.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum BackendChoice {
    /// Compiled CUTLASS template instantiation in
    /// `baracuda-cutlass-kernels-sys`. `arch` records which CUTLASS
    /// SKU (sm_80 today).
    Cutlass { arch: ArchSku },
    /// `cublasGemmEx` (f16/bf16/f32) or `cublasDgemm` (f64) via the
    /// `baracuda-cublas` wrapper. Used as the Phase-30 fast path for
    /// f16/bf16 low-M decode shapes on sm_89 hardware.
    Cublas,
    /// Phase 44: vendored ozIMMU (Ozaki-scheme FP64 GEMM that
    /// synthesizes a DGEMM from `S²` int8 tensor-core matmuls). Only
    /// valid for f64 / RCR / RRR / Identity epilogue. The `slices`
    /// discriminant follows the public `BackendKind::Ozaki { slices }`
    /// convention: 0 = auto, 3..=18 = fixed slice count.
    Ozaki { slices: u8 },
}

impl BackendChoice {
    fn as_public(self) -> BackendKind {
        match self {
            BackendChoice::Cutlass { .. } => BackendKind::Cutlass,
            BackendChoice::Cublas => BackendKind::Cublas,
            BackendChoice::Ozaki { slices } => BackendKind::Ozaki { slices },
        }
    }
}

/// Heuristic that decides whether to route an FP-family GEMM through
/// cuBLAS or CUTLASS. Caller `pref.prefer_backend` overrides whatever
/// the heuristic would have picked (subject to availability checks).
///
/// Today's heuristic (Phase 30, validated on RTX 4070):
///
/// - f16/bf16 with `2 ≤ M < 128`: cuBLAS. The decode-batch regime
///   where cuBLAS's sm_89 tensor-core kernels beat baracuda's
///   CUTLASS sm_80 RCR plan by 2–3×.
/// - f16/bf16 with `M == 1` (pure GEMV-shape): CUTLASS. Counter-
///   intuitive given Phase-29's M=1 perf gap, but the layout
///   `transa=T` we must use to bridge baracuda's row-major contract
///   to cuBLAS's col-major API forces cuBLAS to materialize a B^T
///   transpose, which is slower than the unmaterialized
///   CUTLASS-RCR-sm_80 GEMV-tile at the K=N=4096 shape (185µs vs
///   108µs measured). For pure single-token decode, callers wanting
///   the bench's "all-1's mathematically-wrong" speed can force
///   `prefer_backend = Some(Cublas)` and accept the routing.
/// - f16/bf16 with `M >= 128`: CUTLASS. Tie zone; the existing
///   sm_80 RCR is known-stable.
/// - f32: CUTLASS. Phase-29 bench shows CUTLASS f32 RCR beats cuBLAS
///   `sgemm` at M=128; ~parity at low-M; not worth the routing churn.
/// - f64: CUTLASS (back-compat). Callers can force cuBLAS via
///   `prefer_backend` for decode-shaped f64 workloads.
/// - F32Strict: CUTLASS (cuBLAS has no strict-IEEE SIMT path).
///
/// Bias* epilogues always route through CUTLASS regardless of
/// (M, dtype) — cuBLAS-classic has no fused-bias-activation.
fn should_use_cublas_for_fp(
    desc: &GemmDescriptor,
    element: ElementKind,
) -> bool {
    // Bias / Bias* epilogues — cuBLAS-classic has no fused path.
    if desc.epilogue.requires_bias() {
        return false;
    }
    match element {
        // The 2 ≤ M < 128 window is where cuBLAS wins. M=1 is excluded
        // because the `transa=T` mapping costs more than cuBLAS-direct
        // saves over CUTLASS at K=N=4096-ish shapes. M=128+ is excluded
        // because CUTLASS sm_80 catches up at prefill scale.
        ElementKind::F16 | ElementKind::Bf16 => desc.m >= 2 && desc.m < 128,
        // f32 stays on CUTLASS by default — Phase 29 bench shows
        // CUTLASS f32 RCR beats cuBLAS sgemm at the M=128 prefill
        // shape. Callers can force via PlanPreference if needed.
        ElementKind::F32 => false,
        // F32Strict: CUTLASS SIMT path is the only bit-stable option.
        ElementKind::F32Strict => false,
        // f64: keep CUTLASS by default (back-compat). Callers can
        // force-prefer cuBLAS if their f64 workload is decode-shaped.
        ElementKind::F64 => false,
        // Any other element type isn't reachable through `GemmPlan<T>`
        // (the `Element` bound rejects non-FP types), but the match
        // arm needs to be exhaustive.
        _ => false,
    }
}

/// Phase 44 — validate a `BackendKind::Ozaki { slices }` request
/// against this descriptor.
///
/// ozIMMU only supports FP64 GEMM with the Identity epilogue (no
/// fused bias / activation chain) and the `RCR` / `RRR` layouts that
/// baracuda's `GemmPlan` already exposes. The slice count must be
/// `0` (= auto) or `3..=18` (= fixed). Anything else returns
/// `Error::Unsupported` so callers see the rejection at plan-select
/// time rather than as a deep status code at launch.
///
/// When the `ozimmu` cargo feature is off, every request is rejected
/// with a message pointing at the gate.
#[cfg_attr(not(feature = "ozimmu"), allow(unused_variables))]
fn validate_ozaki_request(
    desc: &GemmDescriptor,
    element: ElementKind,
    slices: u8,
) -> Result<()> {
    #[cfg(not(feature = "ozimmu"))]
    {
        return Err(Error::Unsupported(
            "PlanPreference::prefer_backend = Some(Ozaki {..}) requires the \
             `ozimmu` cargo feature on baracuda-cutlass (off by default — \
             enable on baracuda-kernels too if going through the kernels facade)",
        ));
    }
    #[cfg(feature = "ozimmu")]
    {
        if element != ElementKind::F64 {
            return Err(Error::Unsupported(
                "BackendKind::Ozaki is FP64-only (Ozaki-scheme synthesizes \
                 DGEMM from int8; f16/bf16/f32/F32Strict have no Ozaki path)",
            ));
        }
        if desc.epilogue != EpilogueKind::Identity {
            return Err(Error::Unsupported(
                "BackendKind::Ozaki only supports the Identity epilogue \
                 (no fused bias / activation chain on the Ozaki path)",
            ));
        }
        // Layout is already constrained to Rcr / Rrr by the descriptor;
        // both are supported by `mtk::ozimmu::gemm`.
        //
        // Phase 44c extends the encoding to include variant flags.
        // The low 5 bits are the slice count (0 = auto, 3..=18 = fixed);
        // the high 3 bits are the variant (0 = Base, 1 = EF, 2 = RN,
        // 3 = H). Reject anything else.
        let s = slices & 0x1F; // low 5 bits = slice count
        let v = slices >> 5;   // high 3 bits = variant
        if s != 0 && !(3..=18).contains(&s) {
            return Err(Error::Unsupported(
                "BackendKind::Ozaki slice count (low 5 bits) must be 0 \
                 (auto) or 3..=18",
            ));
        }
        if v > 3 {
            return Err(Error::Unsupported(
                "BackendKind::Ozaki variant (high 3 bits) must be 0 (Base), \
                 1 (EF), 2 (RN), or 3 (H)",
            ));
        }
        Ok(())
    }
}

/// Map a baracuda [`ElementKind`] to the cuBLAS [`cudaDataType_t`].
/// Returns `None` for element kinds that don't have a cuBLAS GemmEx
/// dtype (F32Strict, integer, FP8, …). Callers should fall back to
/// CUTLASS in the `None` case.
fn cublas_dtype_for(kind: ElementKind) -> Option<baracuda_cublas_sys::functions::cudaDataType_t> {
    use baracuda_cublas_sys::functions::cudaDataType_t;
    match kind {
        ElementKind::F16 => Some(cudaDataType_t::R_16F),
        ElementKind::Bf16 => Some(cudaDataType_t::R_16BF),
        ElementKind::F32 => Some(cudaDataType_t::R_32F),
        ElementKind::F64 => Some(cudaDataType_t::R_64F),
        _ => None,
    }
}

// ============================================================================
// GemmPlan
// ============================================================================

/// Selected GEMM kernel and the host-side metadata needed to launch it.
///
/// Plans are cheap to construct, hold no device memory, and are
/// `Send + Sync` for the same reason — they're pure host data. The
/// Phase-30 cuBLAS fast-path adds no per-plan state: cuBLAS handles
/// live in a thread-local cache so the plan itself stays trivially
/// thread-safe.
///
/// See the crate root for usage; key methods:
/// - [`select`](Self::select) — pick a kernel for a problem shape.
/// - [`can_implement`](Self::can_implement) — host-side validation.
/// - [`workspace_size`](Self::workspace_size) — bytes of scratch needed.
/// - [`run`](Self::run) — launch on a stream.
/// - [`sku`](Self::sku) — identity of the chosen kernel.
/// - [`backend`](Self::backend) — which backend (CUTLASS / cuBLAS) was
///   picked. Phase 30 added the cuBLAS fast-path for f16/bf16 low-M
///   decode shapes; the heuristic is documented on
///   [`should_use_cublas_for_fp`](self::should_use_cublas_for_fp).
#[derive(Debug)]
pub struct GemmPlan<T: CutlassElement> {
    desc: GemmDescriptor,
    sku: GemmSku,
    backend: BackendChoice,
    _element: PhantomData<T>,
}

impl<T: CutlassElement> GemmPlan<T> {
    /// Pick a kernel for `desc`.
    ///
    /// Queries the stream's device for its compute capability and selects
    /// between the CUTLASS-sm_80 (forward-compatible across Ampere /
    /// Ada / Hopper), CUTLASS-sm_90a (Hopper-specialized, when feature-
    /// enabled and the device actually is Hopper), and the Phase-30
    /// cuBLAS fast-path. Build features filter what kernels are
    /// *available*; the device cap and the f16/bf16-low-M heuristic
    /// decide what to *use*. See [`should_use_cublas_for_fp`] for the
    /// dispatch rules. Override the heuristic via
    /// [`PlanPreference::prefer_backend`].
    pub fn select(stream: &Stream, desc: &GemmDescriptor, pref: PlanPreference) -> Result<Self> {
        check_descriptor(desc)?;
        // Bias-family kernels currently cover every `(Layout, ElementKind)`
        // pair: F16/Bf16 → 8 elements per epilogue access; F32 (TF32)
        // and F64 → 4 elements per access; F32Strict (SIMT) → 1. The
        // F32Strict bias path uses a vendored SIMT broadcast-epilogue
        // partial specialization (see
        // `crates/baracuda-cutlass-kernels-sys/kernels/include/
        // baracuda_simt_broadcast_epilogue.h`) because CUTLASS doesn't
        // wire one by default. F64 routes through the f64-scalar
        // dispatcher (`gemm_bias_sm80_run_f64`) because alpha/beta are
        // `f64` at the FFI. When new element kinds land that don't yet
        // have bias instantiations, reinstate a gate here that returns
        // `Error::Unsupported` so callers don't get a runtime status 3
        // deep inside the launch path.

        // Phase 30: pick the backend (CUTLASS vs cuBLAS) before the
        // arch. Caller may force a backend via `pref.prefer_backend`;
        // otherwise the f16/bf16-low-M heuristic chooses.
        // Phase 44: `BackendKind::Ozaki { slices }` joins the dispatch
        // surface for FP64-only / Identity-only / RCR-or-RRR shapes
        // (gated behind the `ozimmu` feature on this crate).
        let element = T::KIND;

        // Phase 44 ozIMMU dispatch — handled before the cuBLAS gate so
        // its preconditions (f64 / Identity / RCR|RRR / feature gate)
        // are validated up front.
        if let Some(BackendKind::Ozaki { slices }) = pref.prefer_backend {
            validate_ozaki_request(desc, element, slices)?;
            let arch_for_sku = pick_arch(stream, desc, pref)?;
            let backend = BackendChoice::Ozaki { slices };
            let sku = GemmSku {
                arch: arch_for_sku,
                layout: desc.layout,
                epilogue: desc.epilogue,
                element,
                bias_element: None,
            };
            return Ok(Self {
                desc: *desc,
                sku,
                backend,
                _element: PhantomData,
            });
        }

        let use_cublas = match pref.prefer_backend {
            Some(BackendKind::Cublas) => {
                // Force-Cublas: validate that cuBLAS actually supports
                // this (layout, epilogue, element) triple. Bias*
                // epilogues are not supported (cuBLAS-classic has no
                // fused-bias-activation). F32Strict has no cuBLAS dtype.
                if desc.epilogue.requires_bias() {
                    return Err(Error::Unsupported(
                        "cuBLAS backend doesn't fuse bias activations \
                         (use Cutlass backend for Bias* epilogues)",
                    ));
                }
                if cublas_dtype_for(element).is_none() {
                    return Err(Error::Unsupported(
                        "cuBLAS backend has no GemmEx dtype for this element \
                         (F32Strict / integer / FP8 stay on Cutlass)",
                    ));
                }
                true
            }
            Some(BackendKind::Cutlass) => false,
            Some(BackendKind::Ozaki { .. }) => {
                // Unreachable — handled by the early return above.
                false
            }
            Some(_) => {
                // Other backend hints aren't meaningful for GEMM; treat
                // as "let the heuristic decide".
                should_use_cublas_for_fp(desc, element)
                    && cublas_dtype_for(element).is_some()
            }
            None => {
                should_use_cublas_for_fp(desc, element)
                    && cublas_dtype_for(element).is_some()
            }
        };

        let (backend, sku_arch) = if use_cublas {
            // Capture device arch for the SKU record (so telemetry /
            // autotuner caches still see the real silicon), but the
            // backend choice routes through cuBLAS.
            let arch_for_sku = pick_arch(stream, desc, pref)?;
            (BackendChoice::Cublas, arch_for_sku)
        } else {
            let arch = pick_arch(stream, desc, pref)?;
            (BackendChoice::Cutlass { arch }, arch)
        };

        let sku = GemmSku {
            arch: sku_arch,
            layout: desc.layout,
            epilogue: desc.epilogue,
            element,
            // Float-family bias kernels imply bias element = element type;
            // `None` distinguishes them from the int-family bias kernels
            // (which encode the bias element explicitly because it's
            // independent of the matrix dtype).
            bias_element: None,
        };
        Ok(Self {
            desc: *desc,
            sku,
            backend,
            _element: PhantomData,
        })
    }

    /// Which backend this plan picked.
    ///
    /// CUTLASS (the default path) or cuBLAS (the Phase-30 fast-path
    /// for f16/bf16 low-M decode shapes). The dispatch heuristic is
    /// documented on [`should_use_cublas_for_fp`].
    pub fn backend(&self) -> BackendKind {
        self.backend.as_public()
    }

    /// Validate that this plan can actually launch with `args`.
    ///
    /// Two-stage check:
    /// 1. **Host-side**: shape/stride/buffer-size validation in pure Rust.
    /// 2. **Kernel-side**: calls CUTLASS's `Gemm::can_implement` host
    ///    adapter via a no-launch FFI symbol to catch alignment and
    ///    kernel-support issues that the host can't see (e.g., the
    ///    selected tile's element-per-access requirement on `lda`/`ldb`).
    ///
    /// Returns without launching a kernel and without touching the device.
    /// Use this as a clean prelaunch branch point: if it returns `Ok`, the
    /// `run` call will succeed barring runtime CUDA errors.
    pub fn can_implement(&self, args: &GemmArgs<'_, T>) -> Result<()> {
        check_args(&self.desc, args)?;

        // Phase 30: even when the plan picked the cuBLAS backend, we
        // still run the CUTLASS-side `can_implement` FFI check.
        // Rationale: the cuBLAS path falls back to CUTLASS under graph
        // capture (cuBLAS-classic calls aren't capture-safe), so the
        // CUTLASS launch path may execute regardless of which backend
        // the plan nominally targets. Better to validate the CUTLASS
        // path up front than discover an alignment problem deep in the
        // capture replay.

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld),
            None => (core::ptr::null(), 0i64),
        };
        let bias_ptr = args
            .bias
            .as_ref()
            .map(|b| b.data.as_raw().0 as *const c_void)
            .unwrap_or(core::ptr::null());

        let bias_family = self.sku.epilogue.requires_bias();
        let status = match (self.sku.arch, bias_family) {
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) if <T::Scalar as ScalarType>::IS_F64 => unsafe {
                dispatch::gemm_sm80_can_implement_f64(
                    self.sku.layout,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) => unsafe {
                dispatch::gemm_sm80_can_implement(
                    self.sku.layout,
                    T::KIND,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) if <T::Scalar as ScalarType>::IS_F64 => unsafe {
                dispatch::gemm_bias_sm80_can_implement_f64(
                    self.sku.layout,
                    self.sku.epilogue,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    bias_ptr,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) => unsafe {
                dispatch::gemm_bias_sm80_can_implement(
                    self.sku.layout,
                    T::KIND,
                    self.sku.epilogue,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    bias_ptr,
                )
            },
            #[cfg(not(feature = "sm80"))]
            (ArchSku::Sm80, _) => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            (ArchSku::Sm90a, _) => {
                return Err(Error::Unsupported(
                    "sm90a kernels not yet shipped (deferred until Hopper hardware available for validation)",
                ));
            }
            (ArchSku::Sm89, _) => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }

    /// Bytes of device scratch this plan needs at `run` time.
    ///
    /// Returns 0 when the kernel's launch is workspace-free; pass
    /// [`Workspace::None`] in that case.
    ///
    /// Phase 30 note: even when the plan picked the cuBLAS backend
    /// (which manages its own scratch internally), this method
    /// reports the **CUTLASS-side** workspace requirement. The cuBLAS
    /// path falls back to CUTLASS under graph capture (cuBLAS-classic
    /// calls aren't capture-safe), so the caller must size the
    /// workspace for the CUTLASS path in case the fallback triggers.
    /// In practice CUTLASS Identity-epilogue GEMM on sm_80 reports
    /// 0 bytes for most (M, N, K), so this conservative reporting
    /// rarely costs anything.
    pub fn workspace_size(&self) -> usize {
        let bias_family = self.sku.epilogue.requires_bias();
        match (self.sku.arch, bias_family) {
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) if <T::Scalar as ScalarType>::IS_F64 => {
                dispatch::gemm_sm80_workspace_size_f64(
                    self.sku.layout,
                    self.desc.m, self.desc.n, self.desc.k,
                )
            }
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) => dispatch::gemm_sm80_workspace_size(
                self.sku.layout,
                T::KIND,
                self.desc.m, self.desc.n, self.desc.k,
            ),
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) if <T::Scalar as ScalarType>::IS_F64 => {
                dispatch::gemm_bias_sm80_workspace_size_f64(
                    self.sku.layout,
                    self.sku.epilogue,
                    self.desc.m, self.desc.n, self.desc.k,
                )
            }
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) => dispatch::gemm_bias_sm80_workspace_size(
                self.sku.layout,
                T::KIND,
                self.sku.epilogue,
                self.desc.m, self.desc.n, self.desc.k,
            ),
            #[cfg(not(feature = "sm80"))]
            (ArchSku::Sm80, _) => 0,
            (ArchSku::Sm90a, _) => 0,
            (ArchSku::Sm89, _) => 0,
        }
    }

    /// Identity of the kernel this plan chose.
    pub fn sku(&self) -> GemmSku {
        self.sku
    }

    /// Numerical guarantees this plan's kernel provides.
    ///
    /// Convenience for [`GemmSku::precision_guarantee`] applied to this
    /// plan's SKU. Useful for callers that maintain a per-decision-point
    /// alternatives table (e.g. picking between cuBLAS and CUTLASS for a
    /// given precision contract) without having to re-derive the
    /// guarantees from per-kernel documentation.
    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
        self.sku.precision_guarantee()
    }

    /// Launch the kernel.
    ///
    /// `workspace` must be at least [`workspace_size`](Self::workspace_size)
    /// bytes when non-zero, or [`Workspace::None`] when zero. The stream
    /// must be in the same context as the device buffers in `args`.
    pub fn run(
        &self,
        stream: &Stream,
        workspace: Workspace<'_>,
        args: GemmArgs<'_, T>,
    ) -> Result<()> {
        self.can_implement(&args)?;

        let needed = self.workspace_size();
        let (ws_ptr, ws_bytes): (*mut c_void, usize) = match workspace {
            Workspace::None => {
                if needed != 0 {
                    return Err(Error::WorkspaceTooSmall {
                        needed,
                        got: 0,
                    });
                }
                (core::ptr::null_mut(), 0)
            }
            Workspace::Borrowed(slice) => {
                if slice.len() < needed {
                    return Err(Error::WorkspaceTooSmall {
                        needed,
                        got: slice.len(),
                    });
                }
                (slice.as_raw().0 as *mut c_void, slice.len())
            }
        };

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld),
            None => (core::ptr::null(), 0i64),
        };
        let bias_ptr = args
            .bias
            .as_ref()
            .map(|b| b.data.as_raw().0 as *const c_void)
            .unwrap_or(core::ptr::null());
        // When the caller passes c = None, force beta = 0 at the safe
        // layer. The kernel internally substitutes D for the C operand to
        // satisfy CUTLASS's non-null pointer contract, so a non-zero beta
        // here would silently fold the previous D contents into the
        // result (D += alpha*AB instead of D = alpha*AB).
        let beta_eff = if args.c.is_some() { args.beta } else { <T::Scalar as Default>::default() };
        let stream_raw = stream.as_raw();

        // Phase 30: cuBLAS fast-path. Dispatches to `cublasGemmEx`
        // (f16/bf16/f32) or `cublasDgemm` (f64). cuBLAS is column-major;
        // we apply the row-major-from-col-major trick: compute
        // `D^T = (op_b B)^T · (op_a A)^T` in cuBLAS terms, which
        // lets us pass A/B straight through and read D row-major.
        //
        // For RCR (A row-major, B col-major, D row-major):
        //   cuBLAS sees A as col-major A^T [K, M] (lda = K),
        //   cuBLAS sees B as col-major B [K, N] (ldb = K),
        //   D^T col-major [N, M] (ldd = N) IS D row-major [M, N].
        //   So we call gemmEx(transa = T, transb = N, m=N, n=M, k=K,
        //                     B, ldb=K, A, lda=K, D, ldd=N).
        // For RRR (A row-major, B row-major, D row-major):
        //   B viewed as col-major is B^T [N, K] (ldb = N),
        //   so transb stays N (no transpose) but the operands are
        //   B^T·A^T = (A·B)^T → identical call shape with transa=N.
        //
        // Capture-mode guard: cuBLAS-classic calls aren't capture-safe
        // (they perform host-side handle-state mutations and may issue
        // host allocations / branches that break graph capture). Fall
        // back to CUTLASS when the stream is in capture mode. The
        // `is_capturing` query itself is graph-safe (it just reads
        // driver state).
        if matches!(self.backend, BackendChoice::Cublas) {
            let capturing = stream.is_capturing().unwrap_or(false);
            if !capturing {
                return self.run_cublas(stream, args, beta_eff);
            }
            // Fall through to the CUTLASS dispatch below. The
            // BackendChoice::Cublas flag stays set on the plan for
            // telemetry / sku() consistency; only this launch falls
            // back. Subsequent launches outside capture will route
            // back to cuBLAS.
        }

        // Phase 44: ozIMMU dispatch. Same capture-safety story as the
        // cuBLAS path — ozIMMU calls into cuBLAS internally to drive
        // the int8 tensor-core matmuls + accumulate stage, so it
        // inherits cuBLAS's "not capture-safe" property. Fall back to
        // the CUTLASS DGEMM path under capture; the SKU stays Ozaki
        // for telemetry consistency.
        #[cfg(feature = "ozimmu")]
        if let BackendChoice::Ozaki { slices } = self.backend {
            let capturing = stream.is_capturing().unwrap_or(false);
            if !capturing {
                return self.run_ozaki(stream, args, beta_eff, slices);
            }
        }
        #[cfg(not(feature = "ozimmu"))]
        if matches!(self.backend, BackendChoice::Ozaki { .. }) {
            // Should be unreachable — `select` rejects Ozaki when the
            // feature is off. Belt-and-suspenders.
            return Err(Error::Unsupported(
                "BackendChoice::Ozaki selected without `ozimmu` cargo feature",
            ));
        }

        let bias_family = self.sku.epilogue.requires_bias();
        let status = match (self.sku.arch, bias_family) {
            // Fork on T::Scalar::IS_F64 to pick the matching FFI dispatcher.
            // The two paths only differ in the alpha/beta types passed to
            // CUTLASS; the `to_f32` / `to_f64` calls are identity on the
            // matching impl and never narrow at runtime because the gate
            // statically picks the impl that matches `T::Scalar`.
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) if <T::Scalar as ScalarType>::IS_F64 => unsafe {
                dispatch::gemm_sm80_run_f64(
                    self.sku.layout,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    args.alpha.to_f64(),
                    beta_eff.to_f64(),
                    ws_ptr, ws_bytes, stream_raw,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) => unsafe {
                dispatch::gemm_sm80_run(
                    self.sku.layout,
                    T::KIND,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    args.alpha.to_f32(),
                    beta_eff.to_f32(),
                    ws_ptr, ws_bytes, stream_raw,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) if <T::Scalar as ScalarType>::IS_F64 => unsafe {
                dispatch::gemm_bias_sm80_run_f64(
                    self.sku.layout,
                    self.sku.epilogue,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    bias_ptr,
                    args.alpha.to_f64(),
                    beta_eff.to_f64(),
                    ws_ptr, ws_bytes, stream_raw,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) => unsafe {
                dispatch::gemm_bias_sm80_run(
                    self.sku.layout,
                    T::KIND,
                    self.sku.epilogue,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    bias_ptr,
                    args.alpha.to_f32(),
                    beta_eff.to_f32(),
                    ws_ptr, ws_bytes, stream_raw,
                )
            },
            #[cfg(not(feature = "sm80"))]
            (ArchSku::Sm80, _) => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            (ArchSku::Sm90a, _) => {
                return Err(Error::Unsupported(
                    "sm90a kernels not yet implemented (Phase 4c)",
                ));
            }
            (ArchSku::Sm89, _) => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }

    /// Phase-30 cuBLAS fast-path launch.
    ///
    /// Caller already validated host-side shape / strides via
    /// [`Self::can_implement`] and confirmed the chosen backend is
    /// [`BackendChoice::Cublas`]. This method translates baracuda's
    /// row-major operands into cuBLAS's column-major convention via
    /// the standard "compute D^T in col-major" trick, then dispatches
    /// to `cublasGemmEx` (f16/bf16/f32) or `cublasDgemm` (f64).
    fn run_cublas(
        &self,
        stream: &Stream,
        args: GemmArgs<'_, T>,
        beta_eff: T::Scalar,
    ) -> Result<()> {
        use baracuda_cublas::Op as CublasOp;
        use baracuda_cublas_sys::functions::cublasComputeType_t;

        // Bias / Bias* epilogues aren't supported on the cuBLAS path —
        // `select` already rejected them. Belt-and-suspenders here.
        if self.sku.epilogue.requires_bias() {
            return Err(Error::Unsupported(
                "cuBLAS backend doesn't fuse bias activations \
                 (caller forced a Bias* epilogue onto the cuBLAS path)",
            ));
        }

        let handle = cublas_backend::handle_for(stream)?;

        let m = self.desc.m;
        let n = self.desc.n;
        let k = self.desc.k;
        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        // C must equal D for cuBLAS's `C = α·op(A)·op(B) + β·C` shape
        // when the safe-layer caller passed C=None (treated as β=0).
        // When C is Some, we route it through. cuBLAS reads C with the
        // same layout/ldc as it writes D, so the same row-major-from-
        // col-major mapping applies.
        let (c_ptr, ldc_arg) = match &args.c {
            // cuBLAS expects β*C added in; pass the caller's C directly.
            Some(c) => (c.data.as_raw().0 as *mut c_void, c.ld as i32),
            None => (d_ptr, args.d.ld as i32),
        };

        // Row-major-from-col-major mapping for baracuda's Rcr/Rrr:
        //
        // baracuda Rcr: A row-major [M, K] (lda = K),
        //               B col-major [K, N] (ldb = K),
        //               D row-major [M, N] (ldd = N).
        //
        // cuBLAS sees the same memory column-major:
        //   - A_raw[i*K + kk] col-major (lda=K) → A_blas[kk, i] = A[i, kk]
        //     ⇒ cuBLAS view of A is A^T, shape [K, M], lda=K.
        //   - B_raw[j*K + kk] col-major (ldb=K) → B_blas[kk, j] = B[kk, j]
        //     ⇒ cuBLAS view of B IS B, shape [K, N], ldb=K.
        //   - D_raw[i*N + j] col-major (ldd=N) → D_blas[j, i] = D[i, j]
        //     ⇒ cuBLAS view of D is D^T, shape [N, M], ldd=N.
        //
        // The target identity is D[i,j] = Σ_kk A[i,kk]·B[kk,j], which in
        // cuBLAS view is D_blas[j,i] = Σ_kk B_blas[kk,j] · A_blas[kk,i].
        // Expressed as a cuBLAS GEMM `D_blas = op(X)·op(Y)` with
        // D_blas shape (M_blas, N_blas) = (N, M):
        //   - op(X) shape (M_blas, K) = (N, K) ⇐ B_blas with Op::T
        //     (B_blas is [K, N], B_blas^T = [N, K]).
        //   - op(Y) shape (K, N_blas) = (K, M) ⇐ A_blas with Op::N
        //     (A_blas is already [K, M]).
        // So pass B as the first operand to gemmEx with Op::T and A as
        // the second operand with Op::N.
        //
        // For Rrr (A row-major [M,K], B row-major [K,N], D row-major
        // [M,N]):
        //   - B_raw[kk*N + j] col-major (ldb=N) → B_blas[j, kk] = B[kk, j]
        //     ⇒ cuBLAS view of B is B^T, shape [N, K], ldb=N.
        //   - First operand needs (M_blas, K) = (N, K) ⇐ B^T-as-stored
        //     with Op::N (no further transpose).
        //   - Second operand same as Rcr: A with Op::N, lda=K.
        //
        // `cublas_lda` and `cublas_ldb` below name the ld values *as
        // gemmEx expects them*: cublas_lda is the leading dim of the
        // first operand (which in our call is baracuda's B), and
        // cublas_ldb is the leading dim of the second operand (which
        // is baracuda's A). For both Rcr and Rrr, cublas_lda = args.b.ld
        // and cublas_ldb = args.a.ld; the only thing that changes is
        // the op on the first operand.
        let (transa, transb) = match self.desc.layout {
            LayoutSku::Rcr => (CublasOp::T, CublasOp::N),
            LayoutSku::Rrr => (CublasOp::N, CublasOp::N),
        };
        let cublas_lda = args.b.ld as i32; // first operand (B) ld
        let cublas_ldb = args.a.ld as i32; // second operand (A) ld
        let ldd_arg = args.d.ld as i32;

        // Pick compute path by `T::Scalar` (the FP family bound on
        // CutlassElement guarantees f32 or f64). f64 routes through
        // `cublasDgemm`; everything else uses `cublasGemmEx` with
        // `CUBLAS_COMPUTE_32F` (f32 accumulator regardless of operand
        // dtype, matching cuBLAS's tensor-core path).
        if <T::Scalar as ScalarType>::IS_F64 {
            // f64 path: cublasDgemm. No GemmEx needed; α/β are f64.
            use baracuda_cublas_sys::cublasOperation_t;

            // Translate cublasOperation_t for the raw helper.
            let to_raw = |op: CublasOp| match op {
                CublasOp::N => cublasOperation_t::N,
                CublasOp::T => cublasOperation_t::T,
                CublasOp::C => cublasOperation_t::C,
            };
            // cublasDgemm signature: (handle, transa, transb, m, n, k,
            //   alpha, A, lda, B, ldb, beta, C, ldc).
            // Layout-mapped operand order: B first, A second, output D.
            let alpha_f64 = args.alpha.to_f64();
            let beta_f64 = beta_eff.to_f64();
            let c_api = baracuda_cublas_sys::cublas()
                .map_err(|_| Error::Unsupported("cuBLAS library unavailable"))?;
            let dgemm = c_api
                .cublas_dgemm()
                .map_err(|_| Error::Unsupported("cublasDgemm symbol unavailable"))?;
            // SAFETY: every pointer is from a live DeviceBuffer with
            // the correct dtype; sizes were validated via check_args;
            // the handle is bound to `stream`'s context.
            let status = unsafe {
                dgemm(
                    handle.as_raw(),
                    to_raw(transa),
                    to_raw(transb),
                    n,
                    m,
                    k,
                    &alpha_f64,
                    b_ptr as *const f64,
                    cublas_lda,
                    a_ptr as *const f64,
                    cublas_ldb,
                    &beta_f64,
                    // cublasDgemm uses C as both input and output. Pass
                    // C-or-D depending on whether caller supplied C.
                    if args.c.is_some() {
                        // Caller passed a separate C. cuBLAS writes
                        // back into the same buffer it reads from, so
                        // we'd need a copy step to materialize into D.
                        // For now, restrict the cuBLAS f64 path to
                        // C=None (the common decode case).
                        return Err(Error::Unsupported(
                            "cuBLAS f64 GEMM with explicit C operand is not yet wired \
                             (D and C alias differently than cuBLAS expects); \
                             use Cutlass backend or set c = None",
                        ));
                    } else {
                        d_ptr as *mut f64
                    },
                    ldd_arg,
                )
            };
            return match status {
                baracuda_cublas_sys::cublasStatus_t::SUCCESS => Ok(()),
                _ => Err(Error::CutlassInternal(status.0)),
            };
        }

        // f16/bf16/f32 path: cublasGemmEx with Compute32F accumulator
        // and the tensor-op default algo selector.
        let dtype = cublas_dtype_for(self.sku.element).ok_or(Error::Unsupported(
            "cuBLAS backend selected for element kind without a cuBLAS dtype mapping",
        ))?;
        // For the col-major-mapped problem the operands swap order; the
        // dtype tag is the same for A, B, and D since all three carry
        // the same `T`.
        let a_type = dtype;
        let b_type = dtype;
        let c_type = dtype;
        // Alpha/beta as f32 (the host scalars cuBLAS expects when
        // compute_type = Compute32F).
        let alpha_f32 = args.alpha.to_f32();
        let beta_f32 = beta_eff.to_f32();

        // Caller passed an explicit C: cuBLAS gemmEx writes C in-place
        // (treats C as the output too). When `args.c == Some` and the
        // caller wants D != C, we'd need a memcpy step. For simplicity
        // (and matching the bench's no-C decode case) reject the
        // explicit-C path on the cuBLAS branch and tell the caller to
        // use Cutlass backend. The Identity / no-bias path is the
        // common decode shape we're optimizing.
        if args.c.is_some() {
            return Err(Error::Unsupported(
                "cuBLAS GemmPlan path requires c = None \
                 (cublasGemmEx writes the output in-place into the C operand; \
                 explicit-C with D ≠ C requires an extra copy step — \
                 force Cutlass backend if you need it)",
            ));
        }
        let _ = (c_ptr, ldc_arg); // suppress unused-let warning

        // SAFETY: every pointer is from a live DeviceBuffer with the
        // correct dtype; sizes were validated via check_args; the
        // handle is bound to `stream`'s context.
        unsafe {
            baracuda_cublas::gemm_ex(
                &handle,
                transa,
                transb,
                n,
                m,
                k,
                &alpha_f32 as *const f32 as *const c_void,
                b_ptr,
                b_type,
                cublas_lda,
                a_ptr,
                a_type,
                cublas_ldb,
                &beta_f32 as *const f32 as *const c_void,
                d_ptr,
                c_type,
                ldd_arg,
                cublasComputeType_t::Compute32F,
                CUBLAS_GEMM_ALGO,
            )
            .map_err(|_| Error::CutlassInternal(-1))
        }
    }

    /// Phase-44 ozIMMU dispatch launch.
    ///
    /// Caller already validated host-side shape / strides via
    /// [`Self::can_implement`], confirmed the chosen backend is
    /// [`BackendChoice::Ozaki`], and verified the stream is not in
    /// graph-capture mode (Ozaki is not capture-safe — ozIMMU runs
    /// cuBLAS internally on the int8 accumulate stage). This method
    /// translates baracuda's row-major operands into ozIMMU's
    /// cuBLAS-compatible column-major convention (same trick as the
    /// cuBLAS f64 path) and dispatches to `mtk::ozimmu::gemm`.
    ///
    /// Restrictions for the Phase 44 alpha:
    /// - `args.c` must be `None` (caller passes a C operand only when
    ///   they want `D = alpha*AB + beta*C` with `D != C`; ozIMMU's
    ///   GEMM uses C as the output operand, same as cublasDgemm, so
    ///   we'd need an extra copy to materialize into D — defer).
    /// - Element must be F64 — guarded at `select` already; this
    ///   method takes the safe-typed `T` so the compiler can't see
    ///   that, but the `Scalar::IS_F64` check below makes it
    ///   defense-in-depth.
    #[cfg(feature = "ozimmu")]
    fn run_ozaki(
        &self,
        stream: &Stream,
        args: GemmArgs<'_, T>,
        beta_eff: T::Scalar,
        slices: u8,
    ) -> Result<()> {
        use baracuda_ozimmu::{Op as OzakiOp, OzakiSlices, OzakiVariant};

        if !<T::Scalar as ScalarType>::IS_F64 {
            return Err(Error::Unsupported(
                "BackendChoice::Ozaki reached on non-f64 element \
                 (select() guard should have rejected this)",
            ));
        }
        if args.c.is_some() {
            return Err(Error::Unsupported(
                "ozIMMU GemmPlan path requires c = None \
                 (the Ozaki path writes its output in-place into the C \
                 operand of the underlying cuBLAS GEMM — explicit-C with \
                 D ≠ C requires an extra copy step that the Phase 44 \
                 alpha does not yet wire; force Cutlass backend if needed)",
            ));
        }

        // Phase 44c — decode the discriminant. Low 5 bits = slice
        // count (0 = auto, 3..=18 = fixed); high 3 bits = variant
        // (0 = Base, 1 = EF, 2 = RN, 3 = H). The pure-slices-only
        // values 0..=18 used by Phase 44b decode as Base, preserving
        // source-compat for existing callers.
        let s = slices & 0x1F;
        let v = slices >> 5;
        let slice_choice = match s {
            0 => OzakiSlices::Auto,
            3 => OzakiSlices::S3,
            4 => OzakiSlices::S4,
            5 => OzakiSlices::S5,
            6 => OzakiSlices::S6,
            7 => OzakiSlices::S7,
            8 => OzakiSlices::S8,
            9 => OzakiSlices::S9,
            10 => OzakiSlices::S10,
            11 => OzakiSlices::S11,
            12 => OzakiSlices::S12,
            13 => OzakiSlices::S13,
            14 => OzakiSlices::S14,
            15 => OzakiSlices::S15,
            16 => OzakiSlices::S16,
            17 => OzakiSlices::S17,
            18 => OzakiSlices::S18,
            _ => {
                return Err(Error::Unsupported(
                    "ozIMMU slice count out of range (validated at select; \
                     this is unreachable)",
                ));
            }
        };
        let variant_choice = match v {
            0 => OzakiVariant::Base,
            1 => OzakiVariant::EF,
            2 => OzakiVariant::RN,
            3 => OzakiVariant::H,
            _ => {
                return Err(Error::Unsupported(
                    "ozIMMU variant out of range (validated at select; \
                     this is unreachable)",
                ));
            }
        };

        let handle = ozimmu_backend::handle_for(stream)?;

        // Row-major → ozIMMU (cuBLAS-compatible col-major) mapping.
        // Same algebra as the cuBLAS f64 path: compute `D^T` in
        // col-major terms, swap the operand order, set transa = T for
        // RCR (because B in col-major IS B^T-transposed-from-row-major)
        // or transa = N for RRR (because B in col-major IS B from row
        // major).
        //
        // Pass B as the first operand, A as the second.
        let (transa, transb) = match self.desc.layout {
            LayoutSku::Rcr => (OzakiOp::T, OzakiOp::N),
            LayoutSku::Rrr => (OzakiOp::N, OzakiOp::N),
        };
        let m = self.desc.m as usize;
        let n = self.desc.n as usize;
        let k = self.desc.k as usize;
        let lda = args.b.ld as usize; // first operand (B) ld
        let ldb = args.a.ld as usize; // second operand (A) ld
        let ldc = args.d.ld as usize;

        let a_ptr = args.a.data.as_raw().0 as *const f64;
        let b_ptr = args.b.data.as_raw().0 as *const f64;
        let d_ptr = args.d.data.as_raw().0 as *mut f64;
        let alpha = args.alpha.to_f64();
        let beta = beta_eff.to_f64();

        // SAFETY: the descriptor / args were validated by
        // can_implement(); pointers are live DeviceBuffer<f64> views.
        //
        // Phase 44c — always go through dgemm_with_variant. Base
        // variant is bit-identical to the pre-44c dgemm path; the
        // variant dispatch happens inside the C++ shim with no
        // measurable per-call host overhead.
        unsafe {
            handle.dgemm_with_variant(
                transa, transb,
                // ozIMMU sees us computing D^T col-major: shape (n, m).
                n, m, k,
                alpha,
                b_ptr, lda,
                a_ptr, ldb,
                beta,
                d_ptr, ldc,
                slice_choice,
                variant_choice,
            )
            .map_err(|e| {
                use baracuda_ozimmu::Error as OzErr;
                match e {
                    OzErr::DgemmFailed(s) => Error::CutlassInternal(s),
                    _ => Error::Unsupported(
                        "ozIMMU dgemm rejected the request (see logs)",
                    ),
                }
            })
        }
    }
}

// ============================================================================
// Phase 44 ozIMMU backend — handle cache + dispatch helpers
// ============================================================================
//
// Mirror of the Phase-30 `cublas_backend` module: thread-local cache of
// ozIMMU handles keyed by raw context pointer. ozIMMU handles are
// expensive to construct (they spin up a cuBLAS handle internally + do
// some env-var probing); cache + re-bind keeps the steady-state launch
// cost down to one `set_cuda_stream` call. Returns an `Arc`-cloned
// safe wrapper so the cache can hold the canonical handle while the
// caller drives a launch without holding the thread-local borrow.

#[cfg(feature = "ozimmu")]
mod ozimmu_backend {
    use core::cell::RefCell;
    use std::rc::Rc;

    use baracuda_driver::Stream;
    use baracuda_ozimmu::Handle as OzimmuHandle;

    thread_local! {
        static HANDLE_CACHE: RefCell<Vec<(usize, Rc<OzimmuHandle>)>> =
            const { RefCell::new(Vec::new()) };
    }

    /// Fetch (or lazily create) an ozIMMU handle bound to `stream`'s
    /// context, with the handle's stream binding set to `stream`.
    pub(super) fn handle_for(stream: &Stream) -> crate::Result<Rc<OzimmuHandle>> {
        let ctx_key = stream.context().as_raw() as usize;
        let handle = HANDLE_CACHE.with(|cache| -> crate::Result<Rc<OzimmuHandle>> {
            let mut cache = cache.borrow_mut();
            if let Some((_, h)) = cache.iter().find(|(k, _)| *k == ctx_key) {
                return Ok(h.clone());
            }
            // Make sure the stream's context is current — ozIMMU's
            // create() calls into cuBLAS create() which needs the
            // current context to bind correctly.
            stream
                .context()
                .set_current()
                .map_err(crate::Error::Driver)?;
            // Retry with linear backoff under transient init failures
            // (mirrors the cuBLAS Phase-35 retry pattern; ozIMMU
            // wraps cuBLAS so it inherits the same parallel-init
            // race window).
            let mut last_status: Option<i32> = None;
            let mut handle: Option<OzimmuHandle> = None;
            for attempt in 0..5 {
                match OzimmuHandle::new() {
                    Ok(h) => { handle = Some(h); break }
                    Err(e) => {
                        if let baracuda_ozimmu::Error::CreateFailed(s) = e {
                            last_status = Some(s);
                        }
                        std::thread::sleep(std::time::Duration::from_millis(
                            50 * (attempt as u64 + 1),
                        ));
                    }
                }
            }
            let h = match handle {
                Some(h) => h,
                None => {
                    let _ = last_status;
                    return Err(crate::Error::Unsupported(
                        "ozIMMU handle creation failed after 5 retries \
                         (library missing, device unavailable, or persistent \
                         init contention)",
                    ));
                }
            };
            let rc = Rc::new(h);
            cache.push((ctx_key, rc.clone()));
            Ok(rc)
        })?;
        handle.set_stream(stream);
        Ok(handle)
    }
}

// ============================================================================
// BatchedGemmPlan — uniform-shape batched GEMM
// ============================================================================
//
// All batches share `(M, N, K)`; per-batch operands are addressed by
// adding `i * stride_*` (in elements) to the base pointer. For
// variable-shape grouped problems use `GroupedGemmPlan` instead.
//
// v1 coverage: Rcr layout, F16 / Bf16 elements, sm_80, Identity epilogue.

fn check_batched_descriptor(desc: &BatchedGemmDescriptor) -> Result<()> {
    if desc.m <= 0 || desc.n <= 0 || desc.k <= 0 {
        return Err(Error::InvalidProblem("M, N, K must all be positive"));
    }
    if desc.batch_count <= 0 {
        return Err(Error::InvalidProblem("batch_count must be positive"));
    }
    if desc.epilogue != EpilogueKind::Identity {
        return Err(Error::Unsupported(
            "BatchedGemmPlan v1 supports only EpilogueKind::Identity",
        ));
    }
    Ok(())
}

fn check_batched_args<T: CutlassElement>(
    desc: &BatchedGemmDescriptor,
    args: &BatchedGemmArgs<'_, T>,
) -> Result<()> {
    // Per-batch shape validation matches the single-GEMM path; strides
    // are validated by checking that the last batch's max-addressable
    // element fits within each base buffer.
    if args.a.rows != desc.m || args.a.cols != desc.k {
        return Err(Error::InvalidProblem("A shape doesn't match descriptor (M, K)"));
    }
    if args.b.rows != desc.k || args.b.cols != desc.n {
        return Err(Error::InvalidProblem("B shape doesn't match descriptor (K, N)"));
    }
    if args.d.rows != desc.m || args.d.cols != desc.n {
        return Err(Error::InvalidProblem("D shape doesn't match descriptor (M, N)"));
    }
    if let Some(c) = &args.c {
        if c.rows != desc.m || c.cols != desc.n {
            return Err(Error::InvalidProblem("C shape doesn't match descriptor (M, N)"));
        }
    }
    if args.a.ld < desc.k as i64 {
        return Err(Error::InvalidProblem("A leading dimension must be >= K"));
    }
    let b_min_ld = match desc.layout {
        LayoutSku::Rcr => desc.k as i64,
        LayoutSku::Rrr => desc.n as i64,
    };
    if args.b.ld < b_min_ld {
        return Err(Error::InvalidProblem("B leading dimension too small for layout"));
    }
    if args.d.ld < desc.n as i64 {
        return Err(Error::InvalidProblem("D leading dimension must be >= N"));
    }
    if let Some(c) = &args.c {
        if c.ld < desc.n as i64 {
            return Err(Error::InvalidProblem("C leading dimension must be >= N"));
        }
    }

    // Per-batch element footprint = single-batch min + (batch - 1) * stride.
    // Stride 0 means "broadcast same matrix across all batches" — the
    // single-batch min is the only constraint there.
    fn need_for_batches(
        per_batch_min: usize,
        stride: i64,
        batch_count: i32,
    ) -> Option<usize> {
        if batch_count <= 1 || stride == 0 {
            return Some(per_batch_min);
        }
        let extra = stride.checked_mul((batch_count - 1) as i64)?;
        let extra = usize::try_from(extra).ok()?;
        per_batch_min.checked_add(extra)
    }

    let a_per = min_elements_row_major(args.a.rows, args.a.cols, args.a.ld)
        .ok_or(Error::InvalidProblem("A storage size overflow"))?;
    let need_a = need_for_batches(a_per, args.stride_a, desc.batch_count)
        .ok_or(Error::InvalidProblem("A batched storage size overflow"))?;
    if args.a.data.len() < need_a {
        return Err(Error::BufferTooSmall {
            needed: need_a,
            got: args.a.data.len(),
        });
    }

    let b_per = match desc.layout {
        LayoutSku::Rcr => min_elements_col_major(args.b.rows, args.b.cols, args.b.ld),
        LayoutSku::Rrr => min_elements_row_major(args.b.rows, args.b.cols, args.b.ld),
    }
    .ok_or(Error::InvalidProblem("B storage size overflow"))?;
    let need_b = need_for_batches(b_per, args.stride_b, desc.batch_count)
        .ok_or(Error::InvalidProblem("B batched storage size overflow"))?;
    if args.b.data.len() < need_b {
        return Err(Error::BufferTooSmall {
            needed: need_b,
            got: args.b.data.len(),
        });
    }

    let d_per = min_elements_row_major(args.d.rows, args.d.cols, args.d.ld)
        .ok_or(Error::InvalidProblem("D storage size overflow"))?;
    let need_d = need_for_batches(d_per, args.stride_d, desc.batch_count)
        .ok_or(Error::InvalidProblem("D batched storage size overflow"))?;
    if args.d.data.len() < need_d {
        return Err(Error::BufferTooSmall {
            needed: need_d,
            got: args.d.data.len(),
        });
    }

    if let Some(c) = &args.c {
        let c_per = min_elements_row_major(c.rows, c.cols, c.ld)
            .ok_or(Error::InvalidProblem("C storage size overflow"))?;
        let need_c = need_for_batches(c_per, args.stride_c, desc.batch_count)
            .ok_or(Error::InvalidProblem("C batched storage size overflow"))?;
        if c.data.len() < need_c {
            return Err(Error::BufferTooSmall {
                needed: need_c,
                got: c.data.len(),
            });
        }
    }
    Ok(())
}

/// Plan for a uniform-shape batched GEMM launch.
///
/// All batches share `(M, N, K)`. Plans hold host-side selection
/// metadata only — no device memory, cheap to clone, `Send + Sync`.
///
/// See [`GroupedGemmPlan`] for the variable-shape (per-group) case.
#[derive(Debug)]
pub struct BatchedGemmPlan<T: CutlassElement> {
    desc: BatchedGemmDescriptor,
    sku: GemmSku,
    _element: PhantomData<T>,
}

impl<T: CutlassElement> BatchedGemmPlan<T> {
    /// Pick a kernel for `desc`.
    ///
    /// Returns [`Error::Unsupported`] when the requested
    /// `(layout, element)` combination has no shipped batched kernel
    /// (today: anything other than `Rcr × {F16, Bf16}`).
    pub fn select(
        stream: &Stream,
        desc: &BatchedGemmDescriptor,
        pref: PlanPreference,
    ) -> Result<Self> {
        check_batched_descriptor(desc)?;
        let one_off_desc = GemmDescriptor {
            m: desc.m,
            n: desc.n,
            k: desc.k,
            layout: desc.layout,
            epilogue: desc.epilogue,
        };
        let arch = pick_arch(stream, &one_off_desc, pref)?;
        // v1 coverage gate: only Rcr × {F16, Bf16} have batched kernels.
        match (desc.layout, T::KIND) {
            (LayoutSku::Rcr, ElementKind::F16) | (LayoutSku::Rcr, ElementKind::Bf16) => {}
            _ => {
                return Err(Error::Unsupported(
                    "BatchedGemmPlan v1 only ships Rcr × {F16, Bf16} on sm_80",
                ));
            }
        }
        let sku = GemmSku {
            arch,
            layout: desc.layout,
            epilogue: desc.epilogue,
            element: T::KIND,
            // Float-family bias kernels imply bias element = element type;
            // `None` distinguishes them from the int-family bias kernels
            // (which encode the bias element explicitly because it's
            // independent of the matrix dtype).
            bias_element: None,
        };
        Ok(Self {
            desc: *desc,
            sku,
            _element: PhantomData,
        })
    }

    /// Validate that this plan can launch with `args`. See
    /// [`GemmPlan::can_implement`] for the two-stage host + kernel check.
    pub fn can_implement(&self, args: &BatchedGemmArgs<'_, T>) -> Result<()> {
        check_batched_args(&self.desc, args)?;

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc, stride_c) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld, args.stride_c),
            None => (core::ptr::null(), 0i64, 0i64),
        };

        let status = match self.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => unsafe {
                dispatch::batched_gemm_sm80_can_implement(
                    self.sku.layout,
                    T::KIND,
                    self.desc.m,
                    self.desc.n,
                    self.desc.k,
                    a_ptr,
                    args.a.ld,
                    args.stride_a,
                    b_ptr,
                    args.b.ld,
                    args.stride_b,
                    c_ptr,
                    ldc,
                    stride_c,
                    d_ptr,
                    args.d.ld,
                    args.stride_d,
                    self.desc.batch_count,
                )
            },
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            ArchSku::Sm90a => {
                return Err(Error::Unsupported(
                    "sm90a batched kernels not yet shipped",
                ));
            }
            ArchSku::Sm89 => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }

    /// Bytes of device scratch this plan needs at `run` time.
    pub fn workspace_size(&self) -> usize {
        match self.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => dispatch::batched_gemm_sm80_workspace_size(
                self.sku.layout,
                T::KIND,
                self.desc.m,
                self.desc.n,
                self.desc.k,
                self.desc.batch_count,
            ),
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => 0,
            ArchSku::Sm90a => 0,
            ArchSku::Sm89 => 0,
        }
    }

    /// Identity of the kernel this plan chose.
    pub fn sku(&self) -> GemmSku {
        self.sku
    }

    /// Numerical guarantees this plan's kernel provides.
    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
        self.sku.precision_guarantee()
    }

    /// Launch the batched kernel.
    pub fn run(
        &self,
        stream: &Stream,
        workspace: Workspace<'_>,
        args: BatchedGemmArgs<'_, T>,
    ) -> Result<()> {
        self.can_implement(&args)?;

        let needed = self.workspace_size();
        let (ws_ptr, ws_bytes): (*mut c_void, usize) = match workspace {
            Workspace::None => {
                if needed != 0 {
                    return Err(Error::WorkspaceTooSmall { needed, got: 0 });
                }
                (core::ptr::null_mut(), 0)
            }
            Workspace::Borrowed(slice) => {
                if slice.len() < needed {
                    return Err(Error::WorkspaceTooSmall {
                        needed,
                        got: slice.len(),
                    });
                }
                (slice.as_raw().0 as *mut c_void, slice.len())
            }
        };

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc, stride_c) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld, args.stride_c),
            None => (core::ptr::null(), 0i64, 0i64),
        };
        let beta_eff = if args.c.is_some() { args.beta } else { <T::Scalar as Default>::default() };
        let stream_raw = stream.as_raw();

        let status = match self.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => unsafe {
                // Batched GEMM v1 ships only Rcr × {F16, Bf16} — both
                // f32-scalar — so the `to_f32` conversion is identity.
                // The select gate rejects F64/F32Strict before we reach here.
                dispatch::batched_gemm_sm80_run(
                    self.sku.layout,
                    T::KIND,
                    self.desc.m,
                    self.desc.n,
                    self.desc.k,
                    a_ptr,
                    args.a.ld,
                    args.stride_a,
                    b_ptr,
                    args.b.ld,
                    args.stride_b,
                    c_ptr,
                    ldc,
                    stride_c,
                    d_ptr,
                    args.d.ld,
                    args.stride_d,
                    args.alpha.to_f32(),
                    beta_eff.to_f32(),
                    self.desc.batch_count,
                    ws_ptr,
                    ws_bytes,
                    stream_raw,
                )
            },
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            ArchSku::Sm90a => {
                return Err(Error::Unsupported(
                    "sm90a batched kernels not yet shipped",
                ));
            }
            ArchSku::Sm89 => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }
}

fn pick_arch(
    stream: &Stream,
    _desc: &GemmDescriptor,
    pref: PlanPreference,
) -> Result<ArchSku> {
    // Selection policy:
    //   1. Query the stream's device for its compute capability.
    //   2. Prefer sm90a when (a) the caller didn't disable it via
    //      `pref.allow_sm90a == false`, (b) the `sm90a` feature is on,
    //      and (c) the device is actually Hopper (cap >= 9.0).
    //   3. Otherwise fall back to sm80, which runs forward-compatibly on
    //      Ampere (sm_80), Ada (sm_89), and Hopper (sm_90+) at lower peak
    //      perf than sm90a.
    //
    // Build features control what kernels are *available*; this function
    // controls what's *picked* given the actual device.
    let (major, _minor) = stream.context().device().compute_capability()?;

    if pref.allow_sm90a && cfg!(feature = "sm90a") && major >= 9 {
        return Ok(ArchSku::Sm90a);
    }

    if cfg!(feature = "sm80") {
        // sm80 kernels are PTX-forward-compatible to anything sm_80+.
        if major >= 8 {
            return Ok(ArchSku::Sm80);
        }
        return Err(Error::Unsupported(
            "device compute capability < 8.0; sm_80 kernels won't run here",
        ));
    }

    Err(Error::Unsupported(
        "no arch features enabled — build with --features sm80",
    ))
}

// ============================================================================
// Grouped GEMM
// ============================================================================
//
// Architecture (per Fuel team's design review):
//   - `GroupedGemmPlan` holds host-only selection metadata (SKU, schedule
//     mode, epilogue kind). Cheap to clone, no device allocations.
//   - `prepare()` packs per-group host arrays (problem_sizes, ptr arrays,
//     ld arrays) and computes the threadblock count + scratch size for the
//     specific problem set. Returns a `PreparedGroupedGemm`.
//   - `PreparedGroupedGemm::workspace_size()` reports total bytes needed
//     (metadata layout + CUTLASS internal scratch, with alignment padding).
//   - `PreparedGroupedGemm::run(stream, workspace)` uploads the host
//     metadata to the start of the workspace via async H2D, computes
//     workspace pointer offsets, and launches the kernel.
//
// Workspace layout (caller-supplied; baracuda-cutlass owns this):
//
//     0                              metadata_end                  total
//     |  problem_sizes               |    pad   | CUTLASS scratch  |
//     |  ptr_a, ptr_b, ptr_c, ptr_d  |          |                  |
//     |  lda,   ldb,   ldc,   ldd    |          |                  |
//
// All v0 limitations:
//   - All groups must share the same `(alpha, beta)` epilogue params.
//   - All groups must consistently have `c = None` or `c = Some(_)`.
//   - Identity epilogue only (Bias deferred per Fuel team roadmap).

const COORD_BYTES: usize = 12; // [i32; 3]
const PTR_BYTES: usize = 8; // u64
const LD_BYTES: usize = 8; // i64
const SCRATCH_ALIGN: usize = 256; // CUTLASS internal scratch wants ≥128B; 256 is safe

#[inline]
fn align_up(x: usize, align: usize) -> usize {
    (x + align - 1) & !(align - 1)
}

/// Byte offsets for each metadata array within the caller-supplied workspace.
#[derive(Copy, Clone, Debug)]
struct MetadataLayout {
    problem_sizes_offset: usize,
    ptr_a_offset: usize,
    ptr_b_offset: usize,
    ptr_c_offset: usize,
    ptr_d_offset: usize,
    lda_offset: usize,
    ldb_offset: usize,
    ldc_offset: usize,
    ldd_offset: usize,
    /// First byte past the packed metadata, before scratch alignment.
    metadata_end: usize,
    /// Aligned start of CUTLASS internal scratch.
    scratch_offset: usize,
    /// Total workspace bytes needed.
    total_workspace_bytes: usize,
}

impl MetadataLayout {
    fn compute(group_count: usize, scratch_bytes: usize) -> Self {
        let mut off = 0usize;
        let problem_sizes_offset = off;
        off += COORD_BYTES * group_count;
        off = align_up(off, 8);

        let ptr_a_offset = off;
        off += PTR_BYTES * group_count;
        let ptr_b_offset = off;
        off += PTR_BYTES * group_count;
        let ptr_c_offset = off;
        off += PTR_BYTES * group_count;
        let ptr_d_offset = off;
        off += PTR_BYTES * group_count;
        let lda_offset = off;
        off += LD_BYTES * group_count;
        let ldb_offset = off;
        off += LD_BYTES * group_count;
        let ldc_offset = off;
        off += LD_BYTES * group_count;
        let ldd_offset = off;
        off += LD_BYTES * group_count;
        let metadata_end = off;

        let scratch_offset = align_up(metadata_end, SCRATCH_ALIGN);
        let total_workspace_bytes = scratch_offset + scratch_bytes;

        Self {
            problem_sizes_offset,
            ptr_a_offset,
            ptr_b_offset,
            ptr_c_offset,
            ptr_d_offset,
            lda_offset,
            ldb_offset,
            ldc_offset,
            ldd_offset,
            metadata_end,
            scratch_offset,
            total_workspace_bytes,
        }
    }
}

/// Plan for a grouped (per-problem variable shape) GEMM launch.
///
/// Cheap host-only struct — selection metadata + a cloned [`Context`]
/// handle so [`prepare`](Self::prepare) can allocate pinned host memory
/// without a stream argument. The cloned context is `Arc`-backed in
/// baracuda-driver, so cloning is cheap and the plan stays `Send + Sync`.
///
/// Use [`prepare`](Self::prepare) to bind a concrete slice of
/// [`GroupedProblem`]s to this plan and produce a [`PreparedGroupedGemm`]
/// that owns pinned host scratch and can launch capture-safely.
#[derive(Debug)]
pub struct GroupedGemmPlan<T: CutlassElement> {
    sku: GemmSku,
    schedule: GroupedScheduleMode,
    context: Context,
    _element: PhantomData<T>,
}

impl<T: CutlassElement> GroupedGemmPlan<T> {
    /// Pick a grouped-GEMM kernel for the given epilogue and preferences.
    ///
    /// v0 supports only [`EpilogueKind::Identity`]. Selection arch follows
    /// the same device-cap-aware logic as [`GemmPlan::select`].
    pub fn select(
        stream: &Stream,
        epilogue: EpilogueKind,
        pref: GroupedPlanPreference,
    ) -> Result<Self> {
        if epilogue != EpilogueKind::Identity {
            return Err(Error::Unsupported(
                "v0 grouped GEMM supports only EpilogueKind::Identity",
            ));
        }

        let dummy_desc = GemmDescriptor {
            m: 1,
            n: 1,
            k: 1,
            layout: LayoutSku::Rcr,
            epilogue,
        };
        let arch = pick_arch(stream, &dummy_desc, pref.base)?;
        let sku = GemmSku {
            arch,
            layout: LayoutSku::Rcr,
            epilogue,
            element: T::KIND,
            bias_element: None,
        };
        Ok(Self {
            sku,
            schedule: pref.schedule,
            context: stream.context().clone(),
            _element: PhantomData,
        })
    }

    /// Identity of the kernel this plan chose.
    pub fn sku(&self) -> GemmSku {
        self.sku
    }

    /// Numerical guarantees this plan's kernel provides.
    ///
    /// See [`GemmPlan::precision_guarantee`] for usage.
    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
        self.sku.precision_guarantee()
    }

    /// Schedule mode this plan was selected with.
    pub fn schedule(&self) -> GroupedScheduleMode {
        self.schedule
    }

    /// Bind a concrete set of per-group problems to this plan.
    ///
    /// Performs host-side validation, queries CUTLASS for the threadblock
    /// count and scratch-bytes requirement, and packs the per-group host
    /// arrays. The returned [`PreparedGroupedGemm`] holds host-side
    /// metadata only — no device allocations, and crucially **no Rust
    /// borrow on the input `groups` slice**: device pointers are extracted
    /// into pinned memory during this call. The caller is free to drop
    /// `groups` immediately after; the underlying device buffers must be
    /// kept alive for as long as the prepared plan (or any captured graph
    /// referencing it) is in use.
    pub fn prepare<'a, 'g>(
        &'a self,
        groups: &'g [GroupedProblem<'g, T>],
    ) -> Result<PreparedGroupedGemm<'a, T>> {
        if groups.is_empty() {
            return Err(Error::InvalidProblem("grouped GEMM requires at least one group"));
        }

        // v0 invariants enforced here, before we touch CUTLASS:
        //   - All groups share the same (alpha, beta).
        //   - C presence (`Some` vs `None`) is consistent across groups.
        //   - Each group's shapes / strides are individually valid.
        let first_alpha = groups[0].alpha;
        let first_beta = groups[0].beta;
        let first_has_c = groups[0].c.is_some();
        for g in groups {
            if g.m <= 0 || g.n <= 0 || g.k <= 0 {
                return Err(Error::InvalidProblem("group M, N, K must all be positive"));
            }
            if g.a.rows != g.m || g.a.cols != g.k {
                return Err(Error::InvalidProblem("group A shape doesn't match (M, K)"));
            }
            if g.b.rows != g.k || g.b.cols != g.n {
                return Err(Error::InvalidProblem("group B shape doesn't match (K, N)"));
            }
            if g.d.rows != g.m || g.d.cols != g.n {
                return Err(Error::InvalidProblem("group D shape doesn't match (M, N)"));
            }
            if let Some(c) = &g.c {
                if c.rows != g.m || c.cols != g.n {
                    return Err(Error::InvalidProblem("group C shape doesn't match (M, N)"));
                }
            }
            if g.a.ld < g.k as i64 || g.b.ld < g.k as i64 || g.d.ld < g.n as i64 {
                return Err(Error::InvalidProblem("group leading dimension too small"));
            }
            if g.alpha != first_alpha {
                return Err(Error::Unsupported(
                    "v0 grouped GEMM requires all groups to share alpha",
                ));
            }
            if g.beta != first_beta {
                return Err(Error::Unsupported(
                    "v0 grouped GEMM requires all groups to share beta",
                ));
            }
            if g.c.is_some() != first_has_c {
                return Err(Error::Unsupported(
                    "v0 grouped GEMM requires all groups to consistently have c=None or c=Some",
                ));
            }
        }

        // Pack host problem_sizes as [m,n,k, m,n,k, ...] for the C ABI's
        // sufficient / scratch_bytes / can_implement queries.
        let group_count = groups.len();
        let mut h_m: Vec<i32> = Vec::with_capacity(group_count);
        let mut h_n: Vec<i32> = Vec::with_capacity(group_count);
        let mut h_k: Vec<i32> = Vec::with_capacity(group_count);
        for g in groups {
            h_m.push(g.m);
            h_n.push(g.n);
            h_k.push(g.k);
        }

        let kind = T::KIND;
        let group_count_i32 = group_count as i32;

        // CUTLASS-level can_implement (per-group alignment / shape).
        let ci_status = match self.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => unsafe {
                dispatch::grouped_gemm_rcr_sm80_can_implement(
                    kind,
                    h_m.as_ptr(),
                    h_n.as_ptr(),
                    h_k.as_ptr(),
                    group_count_i32,
                )
            },
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            ArchSku::Sm90a => {
                return Err(Error::Unsupported(
                    "sm90a grouped kernels not yet shipped (deferred until Hopper hardware available)",
                ));
            }
            ArchSku::Sm89 => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };
        status_to_result(ci_status)?;

        // Threadblock count + CUTLASS scratch bytes.
        let threadblock_count = match self.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => unsafe {
                dispatch::grouped_gemm_rcr_sm80_sufficient(
                    kind,
                    h_m.as_ptr(),
                    h_n.as_ptr(),
                    h_k.as_ptr(),
                    group_count_i32,
                )
            },
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => 0,
            ArchSku::Sm90a => 0,
            ArchSku::Sm89 => 0,
        };
        if threadblock_count <= 0 {
            return Err(Error::CutlassInternal(threadblock_count));
        }

        let scratch_bytes = match self.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => unsafe {
                dispatch::grouped_gemm_rcr_sm80_scratch_bytes(
                    kind,
                    h_m.as_ptr(),
                    h_n.as_ptr(),
                    h_k.as_ptr(),
                    group_count_i32,
                    threadblock_count,
                )
            },
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => 0,
            ArchSku::Sm90a => 0,
            ArchSku::Sm89 => 0,
        };

        let layout = MetadataLayout::compute(group_count, scratch_bytes);

        // Pack host metadata into a PINNED host buffer so the H2D in
        // `run()` is truly async (and therefore stream-capture-safe).
        // From pageable host memory, cuMemcpyHtoDAsync is implicitly
        // synchronizing and not capturable; pinned memory is required.
        let mut pinned: PinnedBuffer<u8> = PinnedBuffer::new(&self.context, layout.metadata_end)?;

        // Collect device pointers and leading dimensions before borrowing
        // `pinned` mutably — keeps the mutable-borrow scope tight so we
        // can move `pinned` into the returned struct below.
        let ptr_a: Vec<u64> = groups.iter().map(|g| g.a.data.as_raw().0).collect();
        let ptr_b: Vec<u64> = groups.iter().map(|g| g.b.data.as_raw().0).collect();
        let ptr_d: Vec<u64> = groups.iter().map(|g| g.d.data.as_raw().0).collect();
        // For c = None, point ptr_c at the group's D buffer (kernel reads
        // a valid pointer but multiplies by beta = 0; same trick as
        // single-GEMM null-C handling).
        let ptr_c: Vec<u64> = groups
            .iter()
            .map(|g| {
                g.c.as_ref()
                    .map(|c| c.data.as_raw().0)
                    .unwrap_or_else(|| g.d.data.as_raw().0)
            })
            .collect();
        let lda: Vec<i64> = groups.iter().map(|g| g.a.ld).collect();
        let ldb: Vec<i64> = groups.iter().map(|g| g.b.ld).collect();
        let ldd: Vec<i64> = groups.iter().map(|g| g.d.ld).collect();
        let ldc: Vec<i64> = groups
            .iter()
            .map(|g| g.c.as_ref().map(|c| c.ld).unwrap_or(g.d.ld))
            .collect();

        // Now write all metadata into the pinned slab. The borrow ends
        // when `host_packed` falls out of scope at the end of the block.
        {
            let host_packed: &mut [u8] = &mut pinned;

            let mut p = layout.problem_sizes_offset;
            for g in groups {
                host_packed[p..p + 4].copy_from_slice(&g.m.to_ne_bytes());
                host_packed[p + 4..p + 8].copy_from_slice(&g.n.to_ne_bytes());
                host_packed[p + 8..p + 12].copy_from_slice(&g.k.to_ne_bytes());
                p += COORD_BYTES;
            }

            let pack_ptrs = |dst: &mut [u8], offset: usize, ptrs: &[u64]| {
                let mut p = offset;
                for &val in ptrs {
                    dst[p..p + 8].copy_from_slice(&val.to_ne_bytes());
                    p += PTR_BYTES;
                }
            };
            pack_ptrs(host_packed, layout.ptr_a_offset, &ptr_a);
            pack_ptrs(host_packed, layout.ptr_b_offset, &ptr_b);
            pack_ptrs(host_packed, layout.ptr_c_offset, &ptr_c);
            pack_ptrs(host_packed, layout.ptr_d_offset, &ptr_d);

            let pack_lds = |dst: &mut [u8], offset: usize, lds: &[i64]| {
                let mut p = offset;
                for &val in lds {
                    dst[p..p + 8].copy_from_slice(&val.to_ne_bytes());
                    p += LD_BYTES;
                }
            };
            pack_lds(host_packed, layout.lda_offset, &lda);
            pack_lds(host_packed, layout.ldb_offset, &ldb);
            pack_lds(host_packed, layout.ldc_offset, &ldc);
            pack_lds(host_packed, layout.ldd_offset, &ldd);
        }

        // Host-side problem_sizes copy CUTLASS reads at run time (the
        // device copy from `pinned` is what the kernel actually
        // dereferences; this Vec just gives CUTLASS a stable host pointer
        // for its own internal tile-schedule math).
        let mut host_problem_sizes: Vec<i32> = Vec::with_capacity(group_count * 3);
        for g in groups {
            host_problem_sizes.push(g.m);
            host_problem_sizes.push(g.n);
            host_problem_sizes.push(g.k);
        }

        let beta_eff = if first_has_c { first_beta } else { <T::Scalar as Default>::default() };

        // Grouped GEMM v0 ships only Rcr × {F16, Bf16} (both f32-scalar);
        // the to_f32 conversion is identity. The select gate rejects
        // F64/F32Strict before we reach here.
        Ok(PreparedGroupedGemm {
            plan: self,
            pinned,
            host_problem_sizes,
            layout,
            threadblock_count,
            alpha: first_alpha.to_f32(),
            beta: beta_eff.to_f32(),
            _element: PhantomData,
        })
    }
}

/// A [`GroupedGemmPlan`] bound to a concrete set of per-group problems.
///
/// Owns a [`PinnedBuffer<u8>`] holding the packed metadata (problem
/// sizes, pointer arrays, leading dimensions). Pinned host memory is
/// what makes the H2D inside [`run`](Self::run) truly async — and
/// therefore safely capturable into a CUDA graph. Owns no device memory;
/// the caller supplies that via [`Workspace::Borrowed`] at run time.
///
/// # Lifetime contract
///
/// `PreparedGroupedGemm` extracts raw device pointers from the input
/// [`GroupedProblem`] slice during [`prepare`](GroupedGemmPlan::prepare)
/// and stores them in pinned memory — it does **not** hold a Rust borrow
/// on the input buffers afterwards. This is required for stream capture:
/// the captured graph references the pinned buffer (for the metadata
/// H2D) and the device buffers (via the pointer arrays) by raw address,
/// not by Rust lifetime. The caller must therefore keep both this
/// `PreparedGroupedGemm` and the underlying device buffers alive for as
/// long as any captured graph that references them is in use.
///
/// In practice the pattern is: build groups, call `prepare`, capture
/// into a graph, then keep `PreparedGroupedGemm` plus the input/output
/// device buffers alive for the lifetime of the captured graph.
#[derive(Debug)]
pub struct PreparedGroupedGemm<'a, T: CutlassElement> {
    plan: &'a GroupedGemmPlan<T>,
    /// Pinned host scratch holding all packed metadata. The H2D in `run`
    /// reads from this buffer; pinned memory means the copy is truly
    /// async + capturable on the user's stream.
    pinned: PinnedBuffer<u8>,
    host_problem_sizes: Vec<i32>,
    layout: MetadataLayout,
    threadblock_count: i32,
    alpha: f32,
    beta: f32,
    _element: PhantomData<T>,
}

impl<'a, T: CutlassElement> PreparedGroupedGemm<'a, T> {
    /// Total bytes of device workspace this plan needs at `run` time.
    ///
    /// Includes both the packed metadata layout and CUTLASS's internal
    /// scratch tail with alignment padding between them.
    pub fn workspace_size(&self) -> usize {
        self.layout.total_workspace_bytes
    }

    /// Identity of the kernel this plan chose (forwarded from the parent
    /// [`GroupedGemmPlan`]).
    pub fn sku(&self) -> GemmSku {
        self.plan.sku
    }

    /// Group count this plan was prepared for.
    pub fn group_count(&self) -> usize {
        self.host_problem_sizes.len() / 3
    }

    /// Launch the grouped GEMM.
    ///
    /// Uploads the packed metadata to the start of `workspace` via async
    /// H2D on `stream`, then enqueues the grouped kernel using the
    /// remainder of the workspace as CUTLASS internal scratch.
    pub fn run(&self, stream: &Stream, workspace: Workspace<'_>) -> Result<()> {
        let needed = self.workspace_size();
        let workspace_slice = match workspace {
            Workspace::None => {
                return Err(Error::WorkspaceTooSmall { needed, got: 0 });
            }
            Workspace::Borrowed(slice) => {
                if slice.len() < needed {
                    return Err(Error::WorkspaceTooSmall {
                        needed,
                        got: slice.len(),
                    });
                }
                slice
            }
        };

        let workspace_base = workspace_slice.as_raw().0;

        // Single async H2D from pinned host memory into the workspace
        // prefix. Because the source is pinned (allocated in `prepare`),
        // this copy is truly async and capture-safe — wrapping the
        // surrounding launch in `cuStreamBeginCapture` / `cuStreamEndCapture`
        // produces a graph that replays correctly.
        {
            let mut workspace_for_meta = workspace_slice;
            let metadata_dst = workspace_for_meta.slice_mut(0..self.layout.metadata_end);
            metadata_dst.copy_from_host_async(&self.pinned, stream)?;
        }

        // Compute device pointers via base + offset arithmetic. The C
        // function dereferences these as pointer arrays.
        let off = |o: usize| (workspace_base + o as u64) as *const c_void;
        let off_mut = |o: usize| (workspace_base + o as u64) as *mut c_void;
        let d_problem_sizes = off(self.layout.problem_sizes_offset);
        let d_ptr_a = off(self.layout.ptr_a_offset);
        let d_ptr_b = off(self.layout.ptr_b_offset);
        let d_ptr_c = off(self.layout.ptr_c_offset);
        let d_ptr_d = off_mut(self.layout.ptr_d_offset);
        let d_lda = off(self.layout.lda_offset);
        let d_ldb = off(self.layout.ldb_offset);
        let d_ldc = off(self.layout.ldc_offset);
        let d_ldd = off(self.layout.ldd_offset);
        let scratch_ptr = off_mut(self.layout.scratch_offset);
        let scratch_bytes = self.layout.total_workspace_bytes - self.layout.scratch_offset;

        let h_problem_sizes = self.host_problem_sizes.as_ptr() as *const c_void;
        let stream_raw = stream.as_raw();
        let group_count = self.group_count() as i32;

        let status = match self.plan.sku.arch {
            #[cfg(feature = "sm80")]
            ArchSku::Sm80 => unsafe {
                dispatch::grouped_gemm_rcr_sm80_run(
                    T::KIND,
                    group_count,
                    self.threadblock_count,
                    d_problem_sizes,
                    d_ptr_a,
                    d_ptr_b,
                    d_ptr_c,
                    d_ptr_d,
                    d_lda,
                    d_ldb,
                    d_ldc,
                    d_ldd,
                    h_problem_sizes,
                    self.alpha,
                    self.beta,
                    scratch_ptr,
                    scratch_bytes,
                    stream_raw,
                )
            },
            #[cfg(not(feature = "sm80"))]
            ArchSku::Sm80 => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            ArchSku::Sm90a => {
                return Err(Error::Unsupported(
                    "sm90a grouped kernels not yet shipped",
                ));
            }
            ArchSku::Sm89 => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }
}

// ============================================================================
// IntGemmPlan — int8 GEMM (Phase 2)
// ============================================================================
//
// Sibling to [`GemmPlan`] for the integer GEMM family. The split exists
// because the kernel-level dispatch, accumulator (int32), and epilogue
// templates (`LinearCombinationClamp` / `LinearCombinationBiasElementwise`
// with `ElementCompute = float`) differ enough from the float family
// that mixing them through a single generic plan would smear the
// argument types of every helper.
//
// API surface mirrors [`GemmPlan`]: `select`, `can_implement`,
// `workspace_size`, `run`, `sku`, `precision_guarantee`. Trait bounds:
// - `T: IntElement` constrains the matrix element to a kernel-supported
//   int dtype (today [`S8`](crate::S8) or [`U8`](crate::U8)).
// - `BT: BiasElement` constrains the bias element to a kernel-supported
//   bias dtype (today `f32` or `i32`). Defaults to `f32` since most
//   callers using a `Bias*` epilogue start there; `IntGemmPlan::<S8>`
//   shorthand picks the f32-bias path. Override explicitly with
//   `IntGemmPlan::<S8, i32>` for the int32-bias path.
//
// Layout coverage: today's int8 kernels are RCR-only. Selecting
// [`LayoutSku::Rrr`] returns [`Error::Unsupported`] at `select` time —
// CUTLASS 4.2.0 has no warp-level iterator for the 8-bit `Congruous`
// shared-memory layout the row-major B operand would need. A follow-up
// release will vendor the missing specialization.

/// Plan handle for an int8 GEMM kernel selection.
///
/// See module-level docs above and [`IntGemmDescriptor`] /
/// [`IntGemmArgs`] for the full API contract.
#[derive(Debug)]
pub struct IntGemmPlan<T: IntElement, BT: BiasElement = f32> {
    desc: IntGemmDescriptor,
    sku: GemmSku,
    _element: PhantomData<T>,
    _bias_element: PhantomData<BT>,
}

impl<T: IntElement, BT: BiasElement> IntGemmPlan<T, BT> {
    /// Pick an int-GEMM kernel for `desc`.
    ///
    /// Returns [`Error::Unsupported`] for `LayoutSku::Rrr` — see the
    /// module-level docs above for the CUTLASS upstream limitation.
    /// `BT` is only meaningful for the `Bias*` epilogue variants;
    /// `EpilogueKind::Identity` ignores it.
    pub fn select(
        stream: &Stream,
        desc: &IntGemmDescriptor,
        pref: PlanPreference,
    ) -> Result<Self> {
        check_int_descriptor(desc)?;
        let arch = pick_int_arch(stream, pref)?;
        // RCR-only on int8 today. The descriptor-level check rejects
        // any non-RCR layout up front so callers see the error at
        // plan-creation time rather than at launch.
        if !matches!(desc.layout, LayoutSku::Rcr) {
            return Err(Error::Unsupported(
                "int8 GEMM kernels are RCR-only in this release \
                 (CUTLASS 4.2.0 lacks 8-bit `TensorOpMultiplicandCongruous` \
                 warp iterators for RRR / row-major-B layout)",
            ));
        }
        // `bias_element` is meaningful only for the bias-family
        // epilogues; Identity int kernels carry `None` to match the
        // float-family convention.
        let bias_element = if desc.epilogue.requires_bias() {
            Some(BT::KIND)
        } else {
            None
        };
        let sku = GemmSku {
            arch,
            layout: desc.layout,
            epilogue: desc.epilogue,
            element: T::KIND,
            bias_element,
        };
        Ok(Self {
            desc: *desc,
            sku,
            _element: PhantomData,
            _bias_element: PhantomData,
        })
    }

    /// Validate that this plan can launch with `args`.
    ///
    /// Two-stage check identical in shape to [`GemmPlan::can_implement`].
    pub fn can_implement(&self, args: &IntGemmArgs<'_, T, BT>) -> Result<()> {
        check_int_args(&self.desc, args)?;

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld),
            None => (core::ptr::null(), 0i64),
        };
        let bias_ptr = args
            .bias
            .as_ref()
            .map(|b| b.data.as_raw().0 as *const c_void)
            .unwrap_or(core::ptr::null());

        let bias_family = self.sku.epilogue.requires_bias();
        let status = match (self.sku.arch, bias_family) {
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) => unsafe {
                dispatch::int_gemm_rcr_sm80_can_implement(
                    self.sku.layout,
                    T::KIND,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) => unsafe {
                dispatch::int_gemm_bias_rcr_sm80_can_implement(
                    self.sku.layout,
                    T::KIND,
                    self.sku.epilogue,
                    BT::KIND,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    bias_ptr,
                )
            },
            #[cfg(not(feature = "sm80"))]
            (ArchSku::Sm80, _) => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            (ArchSku::Sm90a, _) => {
                return Err(Error::Unsupported(
                    "sm90a int8 kernels not yet shipped",
                ));
            }
            (ArchSku::Sm89, _) => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }

    /// Bytes of device scratch this plan needs at `run` time.
    pub fn workspace_size(&self) -> usize {
        let bias_family = self.sku.epilogue.requires_bias();
        match (self.sku.arch, bias_family) {
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) => dispatch::int_gemm_rcr_sm80_workspace_size(
                self.sku.layout,
                T::KIND,
                self.desc.m, self.desc.n, self.desc.k,
            ),
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) => dispatch::int_gemm_bias_rcr_sm80_workspace_size(
                self.sku.layout,
                T::KIND,
                self.sku.epilogue,
                BT::KIND,
                self.desc.m, self.desc.n, self.desc.k,
            ),
            #[cfg(not(feature = "sm80"))]
            (ArchSku::Sm80, _) => 0,
            (ArchSku::Sm90a, _) => 0,
            (ArchSku::Sm89, _) => 0,
        }
    }

    /// Identity of the kernel this plan chose.
    pub fn sku(&self) -> GemmSku {
        self.sku
    }

    /// Numerical guarantees this plan's kernel provides.
    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
        self.sku.precision_guarantee()
    }

    /// Launch the kernel.
    pub fn run(
        &self,
        stream: &Stream,
        workspace: Workspace<'_>,
        args: IntGemmArgs<'_, T, BT>,
    ) -> Result<()> {
        self.can_implement(&args)?;

        let needed = self.workspace_size();
        let (ws_ptr, ws_bytes): (*mut c_void, usize) = match workspace {
            Workspace::None => {
                if needed != 0 {
                    return Err(Error::WorkspaceTooSmall { needed, got: 0 });
                }
                (core::ptr::null_mut(), 0)
            }
            Workspace::Borrowed(slice) => {
                if slice.len() < needed {
                    return Err(Error::WorkspaceTooSmall {
                        needed,
                        got: slice.len(),
                    });
                }
                (slice.as_raw().0 as *mut c_void, slice.len())
            }
        };

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld),
            None => (core::ptr::null(), 0i64),
        };
        let bias_ptr = args
            .bias
            .as_ref()
            .map(|b| b.data.as_raw().0 as *const c_void)
            .unwrap_or(core::ptr::null());
        // Match GemmPlan: when c = None, force beta = 0 at the safe layer
        // so the C-substituted-as-D fallback inside the kernel doesn't
        // fold the previous D contents into the result.
        let beta_eff: f32 = if args.c.is_some() { args.beta } else { 0.0 };
        let stream_raw = stream.as_raw();

        let bias_family = self.sku.epilogue.requires_bias();
        let status = match (self.sku.arch, bias_family) {
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, false) => unsafe {
                dispatch::int_gemm_rcr_sm80_run(
                    self.sku.layout,
                    T::KIND,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    args.alpha,
                    beta_eff,
                    ws_ptr, ws_bytes, stream_raw,
                )
            },
            #[cfg(feature = "sm80")]
            (ArchSku::Sm80, true) => unsafe {
                dispatch::int_gemm_bias_rcr_sm80_run(
                    self.sku.layout,
                    T::KIND,
                    self.sku.epilogue,
                    BT::KIND,
                    self.desc.m, self.desc.n, self.desc.k,
                    a_ptr, args.a.ld,
                    b_ptr, args.b.ld,
                    c_ptr, ldc,
                    d_ptr, args.d.ld,
                    bias_ptr,
                    args.alpha,
                    beta_eff,
                    ws_ptr, ws_bytes, stream_raw,
                )
            },
            #[cfg(not(feature = "sm80"))]
            (ArchSku::Sm80, _) => {
                return Err(Error::Unsupported(
                    "sm80 selected but the `sm80` feature isn't enabled",
                ));
            }
            (ArchSku::Sm90a, _) => {
                return Err(Error::Unsupported("sm90a int8 kernels not yet shipped"));
            }
            (ArchSku::Sm89, _) => {
                return Err(Error::Unsupported(
                    "Ada-specialized FP8 / sm_89 SKUs live in baracuda-kernels-sys, not baracuda-cutlass",
                ));
            }
        };

        status_to_result(status)
    }
}

// Internal helpers for int-GEMM validation. Structure mirrors
// `check_descriptor` / `check_args` for the float family.

fn check_int_descriptor(desc: &IntGemmDescriptor) -> Result<()> {
    if desc.m <= 0 || desc.n <= 0 || desc.k <= 0 {
        return Err(Error::InvalidProblem("M, N, K must all be positive"));
    }
    Ok(())
}

fn check_int_args<T: IntElement, BT: BiasElement>(
    desc: &IntGemmDescriptor,
    args: &IntGemmArgs<'_, T, BT>,
) -> Result<()> {
    // Epilogue / bias must agree.
    match (desc.epilogue.requires_bias(), &args.bias) {
        (false, Some(_)) => {
            return Err(Error::InvalidProblem(
                "args.bias must be None when descriptor.epilogue is Identity",
            ));
        }
        (true, None) => {
            return Err(Error::InvalidProblem(
                "args.bias is required when descriptor.epilogue is in the Bias family \
                 (Bias / BiasRelu / BiasGelu / BiasSilu)",
            ));
        }
        (false, None) | (true, Some(_)) => {}
    }
    if let Some(bias) = &args.bias {
        if bias.len != desc.n {
            return Err(Error::InvalidProblem("bias vector length must equal N"));
        }
        if bias.stride != 1 {
            return Err(Error::Unsupported(
                "bias vector must be contiguous (stride 1) — strided bias not supported",
            ));
        }
        if bias.data.len() < desc.n as usize {
            return Err(Error::BufferTooSmall {
                needed: desc.n as usize,
                got: bias.data.len(),
            });
        }
    }
    if args.a.rows != desc.m || args.a.cols != desc.k {
        return Err(Error::InvalidProblem("A shape doesn't match descriptor (M, K)"));
    }
    if args.b.rows != desc.k || args.b.cols != desc.n {
        return Err(Error::InvalidProblem("B shape doesn't match descriptor (K, N)"));
    }
    if args.d.rows != desc.m || args.d.cols != desc.n {
        return Err(Error::InvalidProblem("D shape doesn't match descriptor (M, N)"));
    }
    if let Some(c) = &args.c {
        if c.rows != desc.m || c.cols != desc.n {
            return Err(Error::InvalidProblem("C shape doesn't match descriptor (M, N)"));
        }
    }
    if args.a.ld < desc.k as i64 {
        return Err(Error::InvalidProblem("A leading dimension must be >= K"));
    }
    let b_min_ld = match desc.layout {
        LayoutSku::Rcr => desc.k as i64,
        LayoutSku::Rrr => desc.n as i64,
    };
    if args.b.ld < b_min_ld {
        return Err(Error::InvalidProblem(match desc.layout {
            LayoutSku::Rcr => "B leading dimension must be >= K (column-major Rcr layout)",
            LayoutSku::Rrr => "B leading dimension must be >= N (row-major Rrr layout)",
        }));
    }
    if args.d.ld < desc.n as i64 {
        return Err(Error::InvalidProblem("D leading dimension must be >= N"));
    }
    if let Some(c) = &args.c {
        if c.ld < desc.n as i64 {
            return Err(Error::InvalidProblem("C leading dimension must be >= N"));
        }
    }
    let need_a = min_elements_row_major(args.a.rows, args.a.cols, args.a.ld)
        .ok_or(Error::InvalidProblem("A storage size overflow"))?;
    if args.a.data.len() < need_a {
        return Err(Error::BufferTooSmall {
            needed: need_a,
            got: args.a.data.len(),
        });
    }
    let need_b = match desc.layout {
        LayoutSku::Rcr => min_elements_col_major(args.b.rows, args.b.cols, args.b.ld),
        LayoutSku::Rrr => min_elements_row_major(args.b.rows, args.b.cols, args.b.ld),
    }
    .ok_or(Error::InvalidProblem("B storage size overflow"))?;
    if args.b.data.len() < need_b {
        return Err(Error::BufferTooSmall {
            needed: need_b,
            got: args.b.data.len(),
        });
    }
    let need_d = min_elements_row_major(args.d.rows, args.d.cols, args.d.ld)
        .ok_or(Error::InvalidProblem("D storage size overflow"))?;
    if args.d.data.len() < need_d {
        return Err(Error::BufferTooSmall {
            needed: need_d,
            got: args.d.data.len(),
        });
    }
    if let Some(c) = &args.c {
        let need_c = min_elements_row_major(c.rows, c.cols, c.ld)
            .ok_or(Error::InvalidProblem("C storage size overflow"))?;
        if c.data.len() < need_c {
            return Err(Error::BufferTooSmall {
                needed: need_c,
                got: c.data.len(),
            });
        }
    }
    Ok(())
}

fn pick_int_arch(stream: &Stream, pref: PlanPreference) -> Result<ArchSku> {
    // Int kernels currently only ship for sm_80. The selection logic is a
    // simpler shape of `pick_arch` — no sm_90a path because there are no
    // sm_90a int kernels.
    let (major, _minor) = stream.context().device().compute_capability()?;
    if pref.allow_sm90a && cfg!(feature = "sm90a") && major >= 9 {
        // Allowed but not yet shipped — fall through to sm_80.
    }
    if cfg!(feature = "sm80") {
        if major >= 8 {
            return Ok(ArchSku::Sm80);
        }
        return Err(Error::Unsupported(
            "device compute capability < 8.0; sm_80 int8 kernels won't run here",
        ));
    }
    Err(Error::Unsupported(
        "no arch features enabled — build with --features sm80",
    ))
}

#[cfg(test)]
mod buffer_size_tests {
    //! Regression tests for the per-Fuel-team-review buffer-size formulas.
    //!
    //! Pre-fix the helpers used `rows * ld` / `cols * ld`, which over-rejects
    //! valid padded slabs. The corrected formula is
    //! `(major - 1) * ld + minor`.

    use super::{min_elements_rcr_a, min_elements_rcr_b, min_elements_rcr_cd};

    #[test]
    fn rcr_a_tight_layout() {
        // [M=4, K=8] row-major, lda = K = 8.
        // Min elements = (4 - 1) * 8 + 8 = 32.
        assert_eq!(min_elements_rcr_a(4, 8, 8), Some(32));
    }

    #[test]
    fn rcr_a_padded_layout_accepts_smaller_count() {
        // [M=4, K=8] row-major with lda = 16 (padded).
        // Min elements = (4 - 1) * 16 + 8 = 56.
        // Pre-fix formula was rows*ld = 4*16 = 64 — over-strict by 8 elements.
        assert_eq!(min_elements_rcr_a(4, 8, 16), Some(56));
    }

    #[test]
    fn rcr_b_tight_layout() {
        // [K=8, N=4] column-major, ldb = K = 8.
        // Min elements = (4 - 1) * 8 + 8 = 32.
        assert_eq!(min_elements_rcr_b(8, 4, 8), Some(32));
    }

    #[test]
    fn rcr_b_padded_layout_accepts_smaller_count() {
        // [K=8, N=4] column-major, ldb = 16 (padded).
        // Min elements = (4 - 1) * 16 + 8 = 56. Pre-fix was 4*16 = 64.
        assert_eq!(min_elements_rcr_b(8, 4, 16), Some(56));
    }

    #[test]
    fn rcr_cd_tight_layout() {
        // [M=4, N=8] row-major, ld = N = 8.
        // Min elements = (4 - 1) * 8 + 8 = 32.
        assert_eq!(min_elements_rcr_cd(4, 8, 8), Some(32));
    }

    #[test]
    fn rcr_cd_padded_layout_accepts_smaller_count() {
        // [M=4, N=8] row-major, ld = 16 (padded).
        // Min elements = (4 - 1) * 16 + 8 = 56. Pre-fix was 4*16 = 64.
        assert_eq!(min_elements_rcr_cd(4, 8, 16), Some(56));
    }

    #[test]
    fn single_row_matrix_does_not_underflow() {
        // [M=1, K=8] should need exactly K elements regardless of ld.
        assert_eq!(min_elements_rcr_a(1, 8, 8), Some(8));
        assert_eq!(min_elements_rcr_a(1, 8, 256), Some(8));
    }

    #[test]
    fn overflow_returns_none() {
        // Force i64::checked_mul overflow.
        assert_eq!(min_elements_rcr_a(i32::MAX, 1, i64::MAX), None);
    }
}