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

CUDA execution provider for the ORT 2.0 runtime (Phase 2a: cudarc + cuBLASLt MatMul; custom fused kernels deferred)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
//! CUDA implementation of ORT 1.27 `com.microsoft::QMoE`.
//!
//! Expert tensors remain resident on one GPU. Decode uses the Phase-1 per-route
//! GEMV path; prefill groups routes by expert, gathers contiguous activation
//! tiles, and uses a tiled affine block-dequant GEMM when an expert has multiple
//! assigned tokens. Weight paging, asynchronous prefetch, and expert-parallel
//! sharding are intentionally deferred.

use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use cudarc::driver::sys::CUdeviceptr;
use cudarc::driver::{LaunchConfig, PushKernelArg};
use onnx_runtime_ep_api::{EpError, Kernel, KernelFactory, Result, TensorMut, TensorView};
use onnx_runtime_ir::{DataType, Node};

use crate::error::driver_err;
use crate::kernels::{qmoe_gemm, qmoe_grouping};
use crate::runtime::{CudaRuntime, cuptr};

const MODULE: &str = "qmoe_affine_v1";
const ROUTE_ENTRY: &str = "qmoe_route";
const ACTIVATE_ENTRY: &str = "qmoe_activate";
const LINEAR_F32_ENTRY: &str = "qmoe_linear_f32";
const LINEAR_F16_ENTRY: &str = "qmoe_linear_f16";
const LINEAR_BF16_ENTRY: &str = "qmoe_linear_bf16";
const COMBINE_F32_ENTRY: &str = "qmoe_combine_f32";
const COMBINE_F16_ENTRY: &str = "qmoe_combine_f16";
const COMBINE_BF16_ENTRY: &str = "qmoe_combine_bf16";

const CUDA_SRC: &str = r#"
#ifndef QMOE_BITS
#define QMOE_BITS 4
#endif
#ifndef QMOE_BLOCK_SIZE
#define QMOE_BLOCK_SIZE 16
#endif
#ifndef QMOE_HAS_ZERO_POINTS
#define QMOE_HAS_ZERO_POINTS 0
#endif

#if __has_include(<cuda_fp16.h>) && __has_include(<cuda_bf16.h>)
#define QMOE_HAS_HALF 1
#include <cuda_fp16.h>
#include <cuda_bf16.h>
#endif

__device__ __forceinline__ int total_order_key(float value)
{
    int bits = __float_as_int(value);
    bits ^= (bits >> 31) & 0x7fffffff;
    return bits;
}

__device__ __forceinline__ bool route_value_is_better(
    float candidate, int candidate_index, float best, int best_index)
{
    const int candidate_key = total_order_key(candidate);
    const int best_key = total_order_key(best);
    return candidate_key > best_key
        || (candidate_key == best_key && candidate_index < best_index);
}

extern "C" __global__ void qmoe_route(
    const float* router_probs,
    const float* router_weights,
    int* selected_experts,
    float* selected_weights,
    const unsigned long long rows,
    const int experts,
    const int top_k,
    const int normalize)
{
    const unsigned long long first =
        (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
    const unsigned long long stride =
        (unsigned long long)gridDim.x * blockDim.x;
    for (unsigned long long row = first; row < rows; row += stride) {
        const float* logits = router_probs + row * (unsigned long long)experts;
        int* indices = selected_experts + row * (unsigned long long)top_k;
        float* weights = selected_weights + row * (unsigned long long)top_k;

        for (int slot = 0; slot < top_k; ++slot) {
            int best_index = -1;
            float best_value = 0.0f;
            for (int expert = 0; expert < experts; ++expert) {
                bool already_selected = false;
                for (int previous = 0; previous < slot; ++previous) {
                    already_selected |= indices[previous] == expert;
                }
                if (already_selected) {
                    continue;
                }
                const float candidate = logits[expert];
                if (best_index < 0
                    || route_value_is_better(
                        candidate, expert, best_value, best_index)) {
                    best_index = expert;
                    best_value = candidate;
                }
            }
            indices[slot] = best_index;
        }

        if (router_weights) {
            const float* aggregation =
                router_weights + row * (unsigned long long)experts;
            float denominator = 1.0f;
            if (normalize) {
                denominator = 0.0f;
                for (int slot = 0; slot < top_k; ++slot) {
                    denominator += aggregation[indices[slot]];
                }
            }
            for (int slot = 0; slot < top_k; ++slot) {
                weights[slot] = denominator == 0.0f
                    ? 0.0f
                    : aggregation[indices[slot]] / denominator;
            }
            continue;
        }

        float maximum = -__int_as_float(0x7f800000);
        for (int expert = 0; expert < experts; ++expert) {
            maximum = fmaxf(maximum, logits[expert]);
        }
        float all_sum = 0.0f;
        for (int expert = 0; expert < experts; ++expert) {
            all_sum += expf(logits[expert] - maximum);
        }
        float denominator = all_sum;
        if (normalize) {
            denominator = 0.0f;
            for (int slot = 0; slot < top_k; ++slot) {
                denominator += expf(logits[indices[slot]] - maximum);
            }
        }
        for (int slot = 0; slot < top_k; ++slot) {
            weights[slot] =
                expf(logits[indices[slot]] - maximum) / denominator;
        }
    }
}

__device__ __forceinline__ float block_sum(float value)
{
    extern __shared__ float warp_sums[];
    const int lane = threadIdx.x & 31;
    const int warp = threadIdx.x >> 5;
    for (int offset = 16; offset > 0; offset >>= 1) {
        value += __shfl_down_sync(0xffffffffu, value, offset);
    }
    if (lane == 0) {
        warp_sums[warp] = value;
    }
    __syncthreads();
    value = threadIdx.x < ((blockDim.x + 31) >> 5) ? warp_sums[lane] : 0.0f;
    if (warp == 0) {
        for (int offset = 16; offset > 0; offset >>= 1) {
            value += __shfl_down_sync(0xffffffffu, value, offset);
        }
    }
    return value;
}

template <int Bits, int BlockSize, bool HasZeroPoints>
__device__ __forceinline__ float decode_affine_weight(
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const int expert,
    const int output,
    const int depth,
    const int out_features,
    const int packed_in,
    const int blocks,
    const int zero_point_bytes)
{
    constexpr int PackSize = 8 / Bits;
    const unsigned long long expert_row =
        (unsigned long long)expert * out_features + output;
    const unsigned char byte =
        packed[expert_row * packed_in + depth / PackSize];
    constexpr int Mask = Bits == 8 ? 255 : ((1 << Bits) - 1);
    const int quantized = (byte >> ((depth % PackSize) * Bits)) & Mask;
    const int block = depth / BlockSize;
    int zero_point = 1 << (Bits - 1);
    if (HasZeroPoints) {
        const unsigned char packed_zero =
            zero_points[expert_row * zero_point_bytes + block / PackSize];
        zero_point =
            (packed_zero >> ((block % PackSize) * Bits)) & Mask;
    }
    return ((float)quantized - (float)zero_point)
        * scales[expert_row * blocks + block];
}

template <typename Input>
__device__ __forceinline__ float qmoe_load(
    const Input* input, unsigned long long index);

template <typename Input, int BlockSize, bool HasZeroPoints>
__device__ __forceinline__ float qmoe_int4_chunk(
    const Input* input,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const unsigned long long input_base,
    const unsigned long long expert_row,
    const int depth,
    const int packed_in,
    const int blocks,
    const int zero_point_bytes)
{
    // Int4 rows are multiples of eight packed bytes because block sizes are
    // powers of two >= 16, and chunk depths advance by eight values.
    const unsigned int packed_values =
        *reinterpret_cast<const unsigned int*>(
            packed + expert_row * packed_in + depth / 2);
    const int block = depth / BlockSize;
    int zero_point = 8;
    if (HasZeroPoints) {
        const unsigned char packed_zero =
            zero_points[expert_row * zero_point_bytes + block / 2];
        zero_point = (packed_zero >> ((block & 1) * 4)) & 15;
    }
    const float scale = scales[expert_row * blocks + block];
    float value = 0.0f;
#pragma unroll
    for (int offset = 0; offset < 8; ++offset) {
        const int quantized = (packed_values >> (offset * 4)) & 15;
        const float weight = ((float)quantized - (float)zero_point) * scale;
        value += qmoe_load(input, input_base + depth + offset) * weight;
    }
    return value;
}

template <>
__device__ __forceinline__ float qmoe_load<float>(
    const float* input, unsigned long long index)
{
    return input[index];
}

#ifdef QMOE_HAS_HALF
template <>
__device__ __forceinline__ float qmoe_load<__half>(
    const __half* input, unsigned long long index)
{
    return __half2float(input[index]);
}

template <>
__device__ __forceinline__ float qmoe_load<__nv_bfloat16>(
    const __nv_bfloat16* input, unsigned long long index)
{
    return __bfloat162float(input[index]);
}
#endif

template <typename Input, int Bits, int BlockSize, bool HasZeroPoints>
__device__ void qmoe_linear_impl(
    const Input* input,
    const int* selected_experts,
    const unsigned long long* expert_counts,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const unsigned long long routes,
    const unsigned long long gemm_min_tokens,
    const int input_rows_are_routes,
    const int top_k,
    const int out_features,
    const int in_features,
    const int packed_in,
    const int blocks,
    const int zero_point_bytes)
{
    const unsigned long long tasks =
        routes * (unsigned long long)out_features;
    for (unsigned long long task = blockIdx.x;
         task < tasks;
         task += gridDim.x) {
        const unsigned long long route = task / out_features;
        const int output_feature = (int)(task % out_features);
        const int expert = selected_experts[route];
        if (expert_counts
            && expert_counts[expert] >= gemm_min_tokens) {
            continue;
        }
        const unsigned long long input_row =
            input_rows_are_routes ? route : route / (unsigned long long)top_k;
        float value = 0.0f;
        const unsigned long long input_base =
            input_row * (unsigned long long)in_features;
        const unsigned long long expert_row =
            (unsigned long long)expert * out_features + output_feature;
        if (Bits == 4) {
            const int chunks = in_features / 8;
            for (int chunk = (int)threadIdx.x;
                 chunk < chunks;
                 chunk += (int)blockDim.x) {
                value += qmoe_int4_chunk<Input, BlockSize, HasZeroPoints>(
                    input, packed, scales, zero_points, input_base, expert_row,
                    chunk * 8, packed_in, blocks, zero_point_bytes);
            }
        } else {
            for (int depth = (int)threadIdx.x;
                 depth < in_features;
                 depth += (int)blockDim.x) {
                value += qmoe_load(input, input_base + depth)
                    * decode_affine_weight<Bits, BlockSize, HasZeroPoints>(
                        packed, scales, zero_points, expert, output_feature, depth,
                        out_features, packed_in, blocks, zero_point_bytes);
            }
        }
        value = block_sum(value);
        if (threadIdx.x == 0) {
            const unsigned long long bias_index =
                (unsigned long long)expert * out_features + output_feature;
            output[task] = value + (bias ? bias[bias_index] : 0.0f);
        }
        __syncthreads();
    }
}

extern "C" __global__ void qmoe_linear_f32(
    const float* input,
    const int* selected_experts,
    const unsigned long long* expert_counts,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const unsigned long long routes,
    const unsigned long long gemm_min_tokens,
    const int input_rows_are_routes,
    const int top_k,
    const int out_features,
    const int in_features,
    const int packed_in,
    const int blocks,
    const int zero_point_bytes)
{
    qmoe_linear_impl<float, QMOE_BITS, QMOE_BLOCK_SIZE, QMOE_HAS_ZERO_POINTS != 0>(
        input, selected_experts, expert_counts, packed, scales, zero_points, bias,
        output, routes, gemm_min_tokens, input_rows_are_routes, top_k, out_features, in_features,
        packed_in, blocks, zero_point_bytes);
}

#ifdef QMOE_HAS_HALF
extern "C" __global__ void qmoe_linear_f16(
    const __half* input,
    const int* selected_experts,
    const unsigned long long* expert_counts,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const unsigned long long routes,
    const unsigned long long gemm_min_tokens,
    const int input_rows_are_routes,
    const int top_k,
    const int out_features,
    const int in_features,
    const int packed_in,
    const int blocks,
    const int zero_point_bytes)
{
    qmoe_linear_impl<__half, QMOE_BITS, QMOE_BLOCK_SIZE, QMOE_HAS_ZERO_POINTS != 0>(
        input, selected_experts, expert_counts, packed, scales, zero_points, bias,
        output, routes, gemm_min_tokens, input_rows_are_routes, top_k, out_features, in_features,
        packed_in, blocks, zero_point_bytes);
}

extern "C" __global__ void qmoe_linear_bf16(
    const __nv_bfloat16* input,
    const int* selected_experts,
    const unsigned long long* expert_counts,
    const unsigned char* packed,
    const float* scales,
    const unsigned char* zero_points,
    const float* bias,
    float* output,
    const unsigned long long routes,
    const unsigned long long gemm_min_tokens,
    const int input_rows_are_routes,
    const int top_k,
    const int out_features,
    const int in_features,
    const int packed_in,
    const int blocks,
    const int zero_point_bytes)
{
    qmoe_linear_impl<__nv_bfloat16, QMOE_BITS, QMOE_BLOCK_SIZE, QMOE_HAS_ZERO_POINTS != 0>(
        input, selected_experts, expert_counts, packed, scales, zero_points, bias,
        output, routes, gemm_min_tokens, input_rows_are_routes, top_k, out_features, in_features,
        packed_in, blocks, zero_point_bytes);
}
#endif

__device__ __forceinline__ float stable_sigmoid(float value)
{
    if (value >= 0.0f) {
        return 1.0f / (1.0f + expf(-value));
    }
    const float exponential = expf(value);
    return exponential / (1.0f + exponential);
}

__device__ __forceinline__ float swiglu_value(
    float gate,
    float linear,
    float alpha,
    float beta,
    float limit)
{
    const float bounded_gate = fminf(gate, limit);
    const float bounded_linear =
        isnan(linear) ? linear : fminf(fmaxf(linear, -limit), limit);
    return bounded_gate * stable_sigmoid(alpha * bounded_gate)
        * (bounded_linear + beta);
}

extern "C" __global__ void qmoe_activate(
    const float* fc1,
    const float* fc3,
    float* activated,
    const unsigned long long routes,
    const int inter,
    const int activation,
    const int swiglu_fusion,
    const float alpha,
    const float beta,
    const float swiglu_limit)
{
    const unsigned long long total = routes * (unsigned long long)inter;
    const unsigned long long first =
        (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
    const unsigned long long stride =
        (unsigned long long)gridDim.x * blockDim.x;
    for (unsigned long long index = first; index < total; index += stride) {
        const unsigned long long route = index / inter;
        const int feature = (int)(index % inter);
        const unsigned long long base =
            route * (unsigned long long)(activation == 3 && swiglu_fusion != 0
                ? inter * 2
                : inter);
        const float value = fc1[base + feature];
        if (activation == 0) {
            activated[index] = fmaxf(value, 0.0f);
        } else if (activation == 1) {
            const double x = (double)value;
            const double inner =
                0.7978845608028654 * (x + 0.044715 * x * x * x);
            activated[index] =
                (float)(0.5 * x * (1.0 + tanh(inner)));
        } else if (activation == 2 && !fc3) {
            activated[index] = value * stable_sigmoid(value);
        } else if (activation == 4) {
            activated[index] = value;
        } else {
            float gate;
            float linear;
            if (fc3) {
                gate = value;
                linear = fc3[index];
            } else if (swiglu_fusion == 1) {
                gate = fc1[base + 2 * feature];
                linear = fc1[base + 2 * feature + 1];
            } else {
                gate = value;
                linear = fc1[base + inter + feature];
            }
            activated[index] =
                swiglu_value(gate, linear, alpha, beta, swiglu_limit);
        }
    }
}

template <typename Output>
__device__ __forceinline__ void qmoe_store(
    Output* output, unsigned long long index, float value);

template <>
__device__ __forceinline__ void qmoe_store<float>(
    float* output, unsigned long long index, float value)
{
    output[index] = value;
}

#ifdef QMOE_HAS_HALF
template <>
__device__ __forceinline__ void qmoe_store<__half>(
    __half* output, unsigned long long index, float value)
{
    output[index] = __float2half_rn(value);
}

template <>
__device__ __forceinline__ void qmoe_store<__nv_bfloat16>(
    __nv_bfloat16* output, unsigned long long index, float value)
{
    output[index] = __float2bfloat16_rn(value);
}
#endif

template <typename Output>
__device__ void qmoe_combine_impl(
    const float* route_output,
    const float* selected_weights,
    Output* output,
    const unsigned long long rows,
    const int hidden,
    const int top_k)
{
    const unsigned long long total = rows * (unsigned long long)hidden;
    const unsigned long long first =
        (unsigned long long)blockIdx.x * blockDim.x + threadIdx.x;
    const unsigned long long stride =
        (unsigned long long)gridDim.x * blockDim.x;
    for (unsigned long long index = first; index < total; index += stride) {
        const unsigned long long row = index / hidden;
        const int feature = (int)(index % hidden);
        float value = 0.0f;
        for (int slot = 0; slot < top_k; ++slot) {
            const unsigned long long route =
                row * (unsigned long long)top_k + slot;
            value += selected_weights[route]
                * route_output[route * (unsigned long long)hidden + feature];
        }
        qmoe_store(output, index, value);
    }
}

extern "C" __global__ void qmoe_combine_f32(
    const float* route_output,
    const float* selected_weights,
    float* output,
    const unsigned long long rows,
    const int hidden,
    const int top_k)
{
    qmoe_combine_impl(
        route_output, selected_weights, output, rows, hidden, top_k);
}

#ifdef QMOE_HAS_HALF
extern "C" __global__ void qmoe_combine_f16(
    const float* route_output,
    const float* selected_weights,
    __half* output,
    const unsigned long long rows,
    const int hidden,
    const int top_k)
{
    qmoe_combine_impl(
        route_output, selected_weights, output, rows, hidden, top_k);
}

extern "C" __global__ void qmoe_combine_bf16(
    const float* route_output,
    const float* selected_weights,
    __nv_bfloat16* output,
    const unsigned long long rows,
    const int hidden,
    const int top_k)
{
    qmoe_combine_impl(
        route_output, selected_weights, output, rows, hidden, top_k);
}
#endif
"#;

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
struct QuantLayout {
    bits: usize,
    block_size: usize,
    has_zero_points: bool,
}

fn linear_module_source(layout: QuantLayout) -> (&'static str, &'static str) {
    static SOURCES: OnceLock<Mutex<HashMap<QuantLayout, (&'static str, &'static str)>>> =
        OnceLock::new();
    let sources = SOURCES.get_or_init(|| Mutex::new(HashMap::new()));
    let mut sources = sources.lock().expect("QMoE source cache poisoned");
    if let Some(source) = sources.get(&layout) {
        return *source;
    }

    let zero_points = usize::from(layout.has_zero_points);
    let module = Box::leak(
        format!(
            "qmoe_affine_linear_v2_bits{}_block{}_zero_points{}",
            layout.bits, layout.block_size, zero_points
        )
        .into_boxed_str(),
    );
    let source = Box::leak(
        format!(
            "#define QMOE_BITS {}\n#define QMOE_BLOCK_SIZE {}\n\
             #define QMOE_HAS_ZERO_POINTS {}\n{}",
            layout.bits, layout.block_size, zero_points, CUDA_SRC
        )
        .into_boxed_str(),
    );
    sources.insert(layout, (module, source));
    (module, source)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Activation {
    Relu,
    Gelu,
    Silu,
    Swiglu,
    Identity,
}

impl Activation {
    fn parse(node: &Node) -> Result<Self> {
        let name = match node.attr("activation_type") {
            Some(value) => value
                .as_str()
                .ok_or_else(|| error("attribute activation_type must be a string"))?,
            None => "relu",
        };
        match name {
            "relu" => Ok(Self::Relu),
            "gelu" => Ok(Self::Gelu),
            "silu" => Ok(Self::Silu),
            "swiglu" => Ok(Self::Swiglu),
            "identity" => Ok(Self::Identity),
            other => Err(error(format!(
                "unsupported activation_type '{other}' (supported: relu, gelu, silu, swiglu, identity)"
            ))),
        }
    }

    fn kernel_id(self) -> i32 {
        match self {
            Self::Relu => 0,
            Self::Gelu => 1,
            Self::Silu => 2,
            Self::Swiglu => 3,
            Self::Identity => 4,
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct MoeAttributes {
    k: usize,
    prefill_min_tokens: usize,
    activation: Activation,
    normalize_routing_weights: bool,
    swiglu_fusion: usize,
    activation_alpha: f32,
    activation_beta: f32,
    swiglu_limit: f32,
}

impl MoeAttributes {
    fn from_node(node: &Node) -> Result<Self> {
        let k = int_attr(node, "k", 1)?;
        if k <= 0 {
            return Err(error(format!("k must be > 0, got {k}")));
        }
        let activation = Activation::parse(node)?;
        let prefill_min_tokens = int_attr(node, "prefill_min_tokens", 2)?;
        if prefill_min_tokens < 2 {
            return Err(error(format!(
                "prefill_min_tokens must be at least 2, got {prefill_min_tokens}"
            )));
        }
        let normalize_routing_weights = bool_attr(node, "normalize_routing_weights", false)?;
        if bool_attr(node, "use_sparse_mixer", false)? {
            return Err(error(
                "use_sparse_mixer=1 is unsupported by the CUDA kernel",
            ));
        }
        let swiglu_fusion = int_attr(node, "swiglu_fusion", 0)?;
        if !(0..=2).contains(&swiglu_fusion) {
            return Err(error(format!(
                "swiglu_fusion must be 0, 1, or 2, got {swiglu_fusion}"
            )));
        }
        if activation != Activation::Swiglu && swiglu_fusion != 0 {
            return Err(error(
                "swiglu_fusion is only valid when activation_type='swiglu'",
            ));
        }
        Ok(Self {
            k: usize::try_from(k).map_err(|_| error("k exceeds usize limits"))?,
            prefill_min_tokens: usize::try_from(prefill_min_tokens)
                .map_err(|_| error("prefill_min_tokens exceeds usize limits"))?,
            activation,
            normalize_routing_weights,
            swiglu_fusion: swiglu_fusion as usize,
            activation_alpha: float_attr(node, "activation_alpha", 1.0)?,
            activation_beta: float_attr(node, "activation_beta", 0.0)?,
            swiglu_limit: float_attr(node, "swiglu_limit", f32::INFINITY)?,
        })
    }

    fn fc1_size(self, inter: usize) -> Result<usize> {
        if self.activation == Activation::Swiglu && self.swiglu_fusion != 0 {
            inter
                .checked_mul(2)
                .ok_or_else(|| error("fused SwiGLU FC1 width exceeds usize limits"))
        } else {
            Ok(inter)
        }
    }

    fn uses_separate_gate(self, has_fc3: bool) -> bool {
        (self.activation == Activation::Swiglu && self.swiglu_fusion == 0)
            || (self.activation == Activation::Silu && has_fc3)
    }
}

#[derive(Clone, Copy, Debug)]
enum FloatDtype {
    F32,
    F16,
    Bf16,
}

impl FloatDtype {
    fn from_input(dtype: DataType) -> Result<Self> {
        match dtype {
            DataType::Float32 => Ok(Self::F32),
            DataType::Float16 => Ok(Self::F16),
            DataType::BFloat16 => Ok(Self::Bf16),
            other => Err(error(format!(
                "input requires Float32, Float16, or BFloat16, got {other:?}"
            ))),
        }
    }

    fn linear_entry(self) -> &'static str {
        match self {
            Self::F32 => LINEAR_F32_ENTRY,
            Self::F16 => LINEAR_F16_ENTRY,
            Self::Bf16 => LINEAR_BF16_ENTRY,
        }
    }

    fn combine_entry(self) -> &'static str {
        match self {
            Self::F32 => COMBINE_F32_ENTRY,
            Self::F16 => COMBINE_F16_ENTRY,
            Self::Bf16 => COMBINE_BF16_ENTRY,
        }
    }

    fn gather_entry(self) -> &'static str {
        match self {
            Self::F32 => qmoe_grouping::GATHER_F32_ENTRY,
            Self::F16 => qmoe_grouping::GATHER_F16_ENTRY,
            Self::Bf16 => qmoe_grouping::GATHER_BF16_ENTRY,
        }
    }

    fn needs_half_headers(self) -> bool {
        !matches!(self, Self::F32)
    }
}

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

impl KernelFactory for QMoEFactory {
    fn create(&self, node: &Node, _input_shapes: &[Vec<usize>]) -> Result<Box<dyn Kernel>> {
        let attributes = MoeAttributes::from_node(node)?;
        let bits = int_attr(node, "expert_weight_bits", 4)?;
        if !matches!(bits, 1 | 2 | 4 | 8) {
            return Err(error(format!(
                "expert_weight_bits must be one of {{1, 2, 4, 8}}, got {bits}"
            )));
        }
        let block_size = int_attr(node, "block_size", 0)?;
        if block_size < 16 || !(block_size as usize).is_power_of_two() {
            return Err(error(format!(
                "block_size must be a power of two and at least 16, got {block_size}"
            )));
        }
        let quant_type = match node.attr("quant_type") {
            Some(value) => value
                .as_str()
                .ok_or_else(|| error("attribute quant_type must be a string"))?,
            None => "int",
        };
        if quant_type != "int" {
            return Err(error(format!(
                "quant_type='{quant_type}' is unsupported by CUDA QMoE; this kernel accepts only \
                 ORT integer-affine quant_type='int'. Native IQ/MXFP4 block layouts are not \
                 representable by QMoE's separate scales/zero-points inputs and require a \
                 block-quantized MoE operator"
            )));
        }
        Ok(Box::new(QMoEKernel {
            runtime: self.runtime.clone(),
            attributes,
            bits: bits as usize,
            block_size: block_size as usize,
            scratch: Mutex::new(ScratchPool::default()),
            warmed: AtomicBool::new(false),
        }))
    }
}

pub(crate) fn unsupported_reason(node: &Node) -> Option<Cow<'static, str>> {
    let bits = node
        .attr("expert_weight_bits")
        .map_or(Some(4), |value| value.as_int());
    match bits {
        Some(1 | 2 | 4 | 8) => {}
        Some(bits) => {
            return Some(Cow::Owned(format!(
                "QMoE: CUDA supports expert_weight_bits 1, 2, 4, or 8, got {bits} — requantize the expert weights to a supported width"
            )));
        }
        None => {
            return Some(Cow::Borrowed(
                "QMoE: expert_weight_bits must be an integer (supported: 1, 2, 4, 8)",
            ));
        }
    }
    match node.attr("block_size") {
        Some(attribute) => match attribute.as_int() {
            Some(value) if value >= 16 && (value as usize).is_power_of_two() => {}
            Some(value) => {
                return Some(Cow::Owned(format!(
                    "QMoE: CUDA requires block_size to be a power of two at least 16, got {value} — requantize the expert weights with a supported block size"
                )));
            }
            None => {
                return Some(Cow::Borrowed(
                    "QMoE: block_size must be an integer power of two at least 16",
                ));
            }
        },
        None => {
            return Some(Cow::Borrowed(
                "QMoE: missing integer block_size — export a power-of-two block size of at least 16",
            ));
        }
    }
    match node
        .attr("quant_type")
        .map_or(Some("int"), |value| value.as_str())
    {
        Some("int") => {}
        Some(quant_type) => {
            return Some(Cow::Owned(format!(
                "QMoE: CUDA supports only quant_type='int', got '{quant_type}' — use ORT integer-affine expert weights or a block-quantized MoE operator"
            )));
        }
        None => {
            return Some(Cow::Borrowed(
                "QMoE: quant_type must be the string 'int' for CUDA integer-affine expert weights",
            ));
        }
    }
    None
}

pub struct QMoEKernel {
    runtime: Arc<CudaRuntime>,
    attributes: MoeAttributes,
    bits: usize,
    block_size: usize,
    scratch: Mutex<ScratchPool>,
    warmed: AtomicBool,
}

#[derive(Clone, Copy)]
struct QuantizedExperts<'a> {
    packed: &'a TensorView<'a>,
    scales: &'a TensorView<'a>,
    zero_points: Option<&'a TensorView<'a>>,
    bias: Option<&'a TensorView<'a>>,
    out_features: usize,
    in_features: usize,
    packed_in: usize,
    blocks: usize,
    zero_point_bytes: usize,
}

#[derive(Clone, Copy)]
struct ExpertGrouping {
    counts: CUdeviceptr,
    offsets: CUdeviceptr,
    cursors: CUdeviceptr,
    grouped_routes: CUdeviceptr,
    grouped_input: CUdeviceptr,
}

impl<'a> QuantizedExperts<'a> {
    #[allow(clippy::too_many_arguments)]
    fn validate(
        name: &str,
        packed: &'a TensorView<'a>,
        scales: &'a TensorView<'a>,
        zero_points: Option<&'a TensorView<'a>>,
        bias: Option<&'a TensorView<'a>>,
        experts: usize,
        out_features: usize,
        in_features: usize,
        bits: usize,
        block_size: usize,
    ) -> Result<Self> {
        require_dtype(
            &format!("{name}_experts_weights"),
            packed.dtype,
            DataType::Uint8,
        )?;
        require_dtype(&format!("{name}_scales"), scales.dtype, DataType::Float32)?;
        let pack_size = 8 / bits;
        if !in_features.is_multiple_of(pack_size) {
            return Err(error(format!(
                "{name} input features {in_features} must be divisible by pack_size {pack_size}"
            )));
        }
        if !in_features.is_multiple_of(block_size) {
            return Err(error(format!(
                "{name} input features {in_features} must be divisible by block_size {block_size}"
            )));
        }
        let packed_in = in_features / pack_size;
        let blocks = in_features / block_size;
        let zero_point_bytes = checked_div_ceil(
            blocks,
            pack_size,
            &format!("{name} zero-point row byte count"),
        )?;
        require_shape(
            &format!("{name}_experts_weights"),
            packed.shape,
            &[experts, out_features, packed_in],
        )?;
        require_shape(
            &format!("{name}_scales"),
            scales.shape,
            &[experts, out_features, blocks],
        )?;
        if let Some(zero_points) = zero_points {
            require_dtype(
                &format!("{name}_zero_points"),
                zero_points.dtype,
                DataType::Uint8,
            )?;
            require_shape(
                &format!("{name}_zero_points"),
                zero_points.shape,
                &[experts, out_features, zero_point_bytes],
            )?;
        }
        if let Some(bias) = bias {
            require_dtype(
                &format!("{name}_experts_bias"),
                bias.dtype,
                DataType::Float32,
            )?;
            require_shape(
                &format!("{name}_experts_bias"),
                bias.shape,
                &[experts, out_features],
            )?;
        }
        for (tensor_name, tensor) in [
            (format!("{name}_experts_weights"), Some(packed)),
            (format!("{name}_scales"), Some(scales)),
            (format!("{name}_zero_points"), zero_points),
            (format!("{name}_experts_bias"), bias),
        ] {
            if let Some(tensor) = tensor {
                checked_tensor_layout(&tensor_name, tensor.shape, tensor.dtype)?;
                if !tensor.is_contiguous() {
                    return Err(error(format!(
                        "{tensor_name} must be contiguous on the CUDA execution provider"
                    )));
                }
            }
        }
        Ok(Self {
            packed,
            scales,
            zero_points,
            bias,
            out_features,
            in_features,
            packed_in,
            blocks,
            zero_point_bytes,
        })
    }
}

impl Kernel for QMoEKernel {
    fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        if !(7..=21).contains(&inputs.len()) || outputs.len() != 1 {
            return Err(error(format!(
                "expected 7 to 21 inputs and exactly 1 output, got {} inputs and {} outputs",
                inputs.len(),
                outputs.len()
            )));
        }
        for (index, name) in [
            (0, "input"),
            (1, "router_probs"),
            (2, "fc1_experts_weights"),
            (3, "fc1_scales"),
            (5, "fc2_experts_weights"),
            (6, "fc2_scales"),
        ] {
            if inputs[index].is_absent() {
                return Err(error(format!(
                    "required input {index} ('{name}') is absent"
                )));
            }
        }
        if let Some((index, _)) = inputs
            .iter()
            .enumerate()
            .skip(15)
            .find(|(_, input)| !input.is_absent())
        {
            return Err(error(format!(
                "input {index} is only used by FP4/FP8 QMoE modes, which are deferred"
            )));
        }

        let dtype = FloatDtype::from_input(inputs[0].dtype)?;
        if outputs[0].dtype != inputs[0].dtype {
            return Err(error(format!(
                "output dtype {:?} must equal input dtype {:?}",
                outputs[0].dtype, inputs[0].dtype
            )));
        }
        require_dtype("router_probs", inputs[1].dtype, DataType::Float32)?;
        if dtype.needs_half_headers() {
            self.runtime.require_nvrtc_half_headers("QMoE")?;
        }

        let input_shape = inputs[0].shape;
        if !matches!(input_shape.len(), 2 | 3) {
            return Err(error(format!(
                "input must be 2-D [rows, hidden] or 3-D [batch, sequence, hidden], got {input_shape:?}"
            )));
        }
        require_shape("output", outputs[0].shape, input_shape)?;
        let hidden = *input_shape
            .last()
            .ok_or_else(|| error("input rank unexpectedly empty"))?;
        let rows = checked_product(
            &input_shape[..input_shape.len() - 1],
            "flattened input row count",
        )?;
        require_rank("router_probs", inputs[1].shape, 2)?;
        if inputs[1].shape[0] != rows {
            return Err(error(format!(
                "router_probs rows {} must equal flattened input rows {rows}",
                inputs[1].shape[0]
            )));
        }
        let experts = inputs[1].shape[1];
        if self.attributes.k > experts {
            return Err(error(format!(
                "requires 0 < k <= num_experts, got k={} and num_experts={experts}",
                self.attributes.k
            )));
        }
        if !hidden.is_multiple_of(self.block_size) {
            return Err(error(format!(
                "hidden_size {hidden} must be divisible by block_size {}",
                self.block_size
            )));
        }

        require_rank("fc2_experts_weights", inputs[5].shape, 3)?;
        if inputs[5].shape[0] != experts || inputs[5].shape[1] != hidden {
            return Err(error(format!(
                "fc2_experts_weights must start with [experts={experts}, hidden={hidden}], got {:?}",
                inputs[5].shape
            )));
        }
        let pack_size = 8 / self.bits;
        let inter = inputs[5].shape[2]
            .checked_mul(pack_size)
            .ok_or_else(|| error("fc2 inter_size exceeds usize limits"))?;
        if inter == 0 || !inter.is_multiple_of(self.block_size) {
            return Err(error(format!(
                "inferred inter_size {inter} must be non-zero and divisible by block_size {}",
                self.block_size
            )));
        }
        let fc1_size = self.attributes.fc1_size(inter)?;

        let fc1 = QuantizedExperts::validate(
            "fc1",
            &inputs[2],
            &inputs[3],
            optional_input(inputs, 11),
            optional_input(inputs, 4),
            experts,
            fc1_size,
            hidden,
            self.bits,
            self.block_size,
        )?;
        let fc2 = QuantizedExperts::validate(
            "fc2",
            &inputs[5],
            &inputs[6],
            optional_input(inputs, 12),
            optional_input(inputs, 7),
            experts,
            hidden,
            inter,
            self.bits,
            self.block_size,
        )?;

        let has_fc3 = optional_input(inputs, 8).is_some();
        let uses_separate_gate = self.attributes.uses_separate_gate(has_fc3);
        let fc3 = if uses_separate_gate {
            Some(QuantizedExperts::validate(
                "fc3",
                optional_input(inputs, 8)
                    .ok_or_else(|| error("unfused swiglu requires input 8 fc3_experts_weights"))?,
                optional_input(inputs, 9)
                    .ok_or_else(|| error("fc3_experts_weights requires input 9 fc3_scales"))?,
                optional_input(inputs, 13),
                optional_input(inputs, 10),
                experts,
                inter,
                hidden,
                self.bits,
                self.block_size,
            )?)
        } else {
            for (index, name) in [
                (8, "fc3_experts_weights"),
                (9, "fc3_scales"),
                (10, "fc3_experts_bias"),
                (13, "fc3_zero_points"),
            ] {
                if optional_input(inputs, index).is_some() {
                    return Err(error(format!(
                        "{name} is only valid for unfused swiglu or silu gated-GLU"
                    )));
                }
            }
            None
        };

        if let Some(router_weights) = optional_input(inputs, 14) {
            require_dtype("router_weights", router_weights.dtype, DataType::Float32)?;
            require_shape("router_weights", router_weights.shape, &[rows, experts])?;
        }
        for (name, tensor) in [("input", &inputs[0]), ("router_probs", &inputs[1])] {
            checked_tensor_layout(name, tensor.shape, tensor.dtype)?;
            if !tensor.is_contiguous() {
                return Err(error(format!(
                    "{name} must be contiguous on the CUDA execution provider"
                )));
            }
        }
        if let Some(router_weights) = optional_input(inputs, 14) {
            checked_tensor_layout("router_weights", router_weights.shape, router_weights.dtype)?;
            if !router_weights.is_contiguous() {
                return Err(error(
                    "router_weights must be contiguous on the CUDA execution provider",
                ));
            }
        }
        checked_tensor_layout("output", outputs[0].shape, outputs[0].dtype)?;
        if !outputs[0].is_contiguous() {
            return Err(error(
                "output must be contiguous on the CUDA execution provider",
            ));
        }
        if rows == 0 || hidden == 0 {
            return Ok(());
        }

        let routes = checked_product(&[rows, self.attributes.k], "route count")?;
        let route_index_bytes = checked_bytes(routes, std::mem::size_of::<i32>(), "route indices")?;
        let route_weight_bytes =
            checked_bytes(routes, std::mem::size_of::<f32>(), "route weights")?;
        let fc1_elements = checked_product(&[routes, fc1_size], "FC1 scratch element count")?;
        let fc1_bytes = checked_bytes(fc1_elements, 4, "FC1 scratch")?;
        let activated_elements =
            checked_product(&[routes, inter], "activation scratch element count")?;
        let activated_bytes = checked_bytes(activated_elements, 4, "activation scratch")?;
        let route_output_elements =
            checked_product(&[routes, hidden], "route output element count")?;
        let route_output_bytes = checked_bytes(route_output_elements, 4, "route output scratch")?;
        let grouping_sizes = (rows > 1)
            .then(|| {
                let expert_entries = experts
                    .checked_add(1)
                    .ok_or_else(|| error("expert offset entry count exceeds usize limits"))?;
                let counts =
                    checked_bytes(experts, std::mem::size_of::<u64>(), "expert token counts")?;
                let offsets = checked_bytes(
                    expert_entries,
                    std::mem::size_of::<u64>(),
                    "expert token offsets",
                )?;
                let grouped_routes =
                    checked_bytes(routes, std::mem::size_of::<u64>(), "grouped route indices")?;
                let grouped_features = hidden.max(inter);
                let grouped_elements = checked_product(
                    &[routes, grouped_features],
                    "grouped activation element count",
                )?;
                let grouped_input =
                    checked_bytes(grouped_elements, 4, "grouped activation scratch")?;
                Ok::<_, EpError>((counts, offsets, grouped_routes, grouped_input))
            })
            .transpose()?;

        let capturing = self.runtime.is_capturing()?;
        let mut scratch = self
            .scratch
            .lock()
            .map_err(|_| error("QMoE scratch pool mutex poisoned"))?;
        let route_indices = scratch.ensure(&self.runtime, 0, route_index_bytes, capturing)?;
        let route_weights = scratch.ensure(&self.runtime, 1, route_weight_bytes, capturing)?;
        let fc1_output = scratch.ensure(&self.runtime, 2, fc1_bytes, capturing)?;
        let fc3_output = fc3
            .map(|_| scratch.ensure(&self.runtime, 3, activated_bytes, capturing))
            .transpose()?;
        let activated = scratch.ensure(&self.runtime, 4, activated_bytes, capturing)?;
        let route_output = scratch.ensure(&self.runtime, 5, route_output_bytes, capturing)?;
        let grouping = grouping_sizes
            .map(
                |(counts_bytes, offsets_bytes, grouped_routes_bytes, grouped_input_bytes)| {
                    Ok::<_, EpError>(ExpertGrouping {
                        counts: scratch.ensure(&self.runtime, 6, counts_bytes, capturing)?,
                        offsets: scratch.ensure(&self.runtime, 7, offsets_bytes, capturing)?,
                        cursors: scratch.ensure(&self.runtime, 8, counts_bytes, capturing)?,
                        grouped_routes: scratch.ensure(
                            &self.runtime,
                            9,
                            grouped_routes_bytes,
                            capturing,
                        )?,
                        grouped_input: scratch.ensure(
                            &self.runtime,
                            10,
                            grouped_input_bytes,
                            capturing,
                        )?,
                    })
                },
            )
            .transpose()?;

        self.launch_route(
            &inputs[1],
            optional_input(inputs, 14),
            route_indices,
            route_weights,
            rows,
            experts,
        )?;
        if let Some(grouping) = grouping {
            self.launch_grouping(route_indices, grouping, routes, experts)?;
            self.launch_gather(
                dtype,
                tensor_ptr(&inputs[0]),
                grouping,
                routes,
                rows,
                hidden,
                false,
            )?;
            self.launch_grouped_linear(grouping, fc1, fc1_output, routes, experts)?;
            self.launch_linear(
                dtype,
                tensor_ptr(&inputs[0]),
                route_indices,
                Some(grouping.counts),
                fc1,
                fc1_output,
                routes,
                false,
            )?;
            if let (Some(fc3), Some(fc3_output)) = (fc3, fc3_output) {
                self.launch_grouped_linear(grouping, fc3, fc3_output, routes, experts)?;
                self.launch_linear(
                    dtype,
                    tensor_ptr(&inputs[0]),
                    route_indices,
                    Some(grouping.counts),
                    fc3,
                    fc3_output,
                    routes,
                    false,
                )?;
            }
            self.launch_activation(fc1_output, fc3_output, activated, routes, inter)?;
            self.launch_gather(
                FloatDtype::F32,
                activated,
                grouping,
                routes,
                routes,
                inter,
                true,
            )?;
            self.launch_grouped_linear(grouping, fc2, route_output, routes, experts)?;
            self.launch_linear(
                FloatDtype::F32,
                activated,
                route_indices,
                Some(grouping.counts),
                fc2,
                route_output,
                routes,
                true,
            )?;
        } else {
            self.launch_linear(
                dtype,
                tensor_ptr(&inputs[0]),
                route_indices,
                None,
                fc1,
                fc1_output,
                routes,
                false,
            )?;
            if let (Some(fc3), Some(fc3_output)) = (fc3, fc3_output) {
                self.launch_linear(
                    dtype,
                    tensor_ptr(&inputs[0]),
                    route_indices,
                    None,
                    fc3,
                    fc3_output,
                    routes,
                    false,
                )?;
            }
            self.launch_activation(fc1_output, fc3_output, activated, routes, inter)?;
            self.launch_linear(
                FloatDtype::F32,
                activated,
                route_indices,
                None,
                fc2,
                route_output,
                routes,
                true,
            )?;
        }
        self.launch_combine(
            dtype,
            route_output,
            route_weights,
            &mut outputs[0],
            rows,
            hidden,
        )?;
        let result = if capturing {
            Ok(())
        } else {
            self.runtime.synchronize()
        };
        if result.is_ok() && !capturing {
            self.warmed.store(true, Ordering::Relaxed);
        }
        result
    }

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

    fn capture_support(&self) -> onnx_runtime_ep_api::CaptureSupport {
        if self.warmed.load(Ordering::Relaxed) {
            onnx_runtime_ep_api::CaptureSupport::Supported
        } else {
            onnx_runtime_ep_api::CaptureSupport::unsupported(
                "requires a warmed fixed-shape eager QMoE pass to size the pooled scratch and \
                 compile every routed expert kernel",
            )
        }
    }
}

impl QMoEKernel {
    fn launch_route(
        &self,
        router_probs: &TensorView,
        router_weights: Option<&TensorView>,
        route_indices: CUdeviceptr,
        route_weights: CUdeviceptr,
        rows: usize,
        experts: usize,
    ) -> Result<()> {
        let function = self.runtime.nvrtc_function(MODULE, CUDA_SRC, ROUTE_ENTRY)?;
        let router_probs = tensor_ptr(router_probs);
        let router_weights = router_weights.map(tensor_ptr).unwrap_or(0);
        let rows = as_u64("row count", rows)?;
        let experts = as_i32("expert count", experts)?;
        let top_k = as_i32("top-k", self.attributes.k)?;
        let normalize = i32::from(self.attributes.normalize_routing_weights);
        let config = self.pointwise_launch_config(rows)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&router_probs)
            .arg(&router_weights)
            .arg(&route_indices)
            .arg(&route_weights)
            .arg(&rows)
            .arg(&experts)
            .arg(&top_k)
            .arg(&normalize);
        // SAFETY: tensor layouts and scratch sizes were validated, and the ABI
        // matches `qmoe_route`.
        unsafe { builder.launch(config) }
            .map(|_| ())
            .map_err(|err| driver_err("launch QMoE routing", err))
    }

    fn launch_grouping(
        &self,
        route_indices: CUdeviceptr,
        grouping: ExpertGrouping,
        routes: usize,
        experts: usize,
    ) -> Result<()> {
        let routes_u64 = as_u64("route count", routes)?;
        let experts_i32 = as_i32("expert count", experts)?;
        let expert_entries = experts
            .checked_add(1)
            .ok_or_else(|| error("expert offset entry count exceeds usize limits"))?;
        let init_total = routes.max(expert_entries);

        let init = self.runtime.nvrtc_function(
            qmoe_grouping::MODULE,
            qmoe_grouping::CUDA_SRC,
            qmoe_grouping::INIT_ENTRY,
        )?;
        let mut builder = self.runtime.stream().launch_builder(&init);
        builder
            .arg(&grouping.counts)
            .arg(&grouping.offsets)
            .arg(&grouping.cursors)
            .arg(&grouping.grouped_routes)
            .arg(&routes_u64)
            .arg(&experts_i32);
        // SAFETY: all grouping buffers have their checked counts/offsets/routes
        // sizes, and the scalar ABI matches `qmoe_group_init`.
        unsafe {
            builder.launch(self.pointwise_launch_config(as_u64(
                "group initialization element count",
                init_total,
            )?)?)
        }
        .map_err(|err| driver_err("initialize QMoE expert grouping", err))?;

        let count = self.runtime.nvrtc_function(
            qmoe_grouping::MODULE,
            qmoe_grouping::CUDA_SRC,
            qmoe_grouping::COUNT_ENTRY,
        )?;
        let mut builder = self.runtime.stream().launch_builder(&count);
        builder
            .arg(&route_indices)
            .arg(&grouping.counts)
            .arg(&routes_u64)
            .arg(&experts_i32);
        // SAFETY: route_indices covers `routes` and counts covers `experts`.
        unsafe { builder.launch(self.pointwise_launch_config(routes_u64)?) }
            .map_err(|err| driver_err("count QMoE routes by expert", err))?;

        let prefix = self.runtime.nvrtc_function(
            qmoe_grouping::MODULE,
            qmoe_grouping::CUDA_SRC,
            qmoe_grouping::PREFIX_ENTRY,
        )?;
        let mut builder = self.runtime.stream().launch_builder(&prefix);
        builder
            .arg(&grouping.counts)
            .arg(&grouping.offsets)
            .arg(&routes_u64)
            .arg(&experts_i32);
        // SAFETY: the single-thread prefix kernel reads `experts` counts and
        // writes `experts + 1` offsets.
        unsafe {
            builder.launch(LaunchConfig {
                grid_dim: (1, 1, 1),
                block_dim: (1, 1, 1),
                shared_mem_bytes: 0,
            })
        }
        .map_err(|err| driver_err("scan QMoE expert token offsets", err))?;

        let assign = self.runtime.nvrtc_function(
            qmoe_grouping::MODULE,
            qmoe_grouping::CUDA_SRC,
            qmoe_grouping::ASSIGN_ENTRY,
        )?;
        let mut builder = self.runtime.stream().launch_builder(&assign);
        builder
            .arg(&route_indices)
            .arg(&grouping.offsets)
            .arg(&grouping.cursors)
            .arg(&grouping.grouped_routes)
            .arg(&routes_u64)
            .arg(&experts_i32);
        // SAFETY: offsets and cursors cover all experts, grouped_routes covers
        // all routes, and every device-side write is bounds guarded.
        unsafe { builder.launch(self.pointwise_launch_config(routes_u64)?) }
            .map(|_| ())
            .map_err(|err| driver_err("assign QMoE grouped routes", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_gather(
        &self,
        dtype: FloatDtype,
        input: CUdeviceptr,
        grouping: ExpertGrouping,
        routes: usize,
        input_rows: usize,
        features: usize,
        input_rows_are_routes: bool,
    ) -> Result<()> {
        let function = self.runtime.nvrtc_function(
            qmoe_grouping::MODULE,
            qmoe_grouping::CUDA_SRC,
            dtype.gather_entry(),
        )?;
        let total = checked_product(&[routes, features], "grouped gather element count")?;
        let routes = as_u64("route count", routes)?;
        let input_rows = as_u64("gather input row count", input_rows)?;
        let input_rows_are_routes = i32::from(input_rows_are_routes);
        let top_k = as_i32("top-k", self.attributes.k)?;
        let features = as_i32("gather feature count", features)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&input)
            .arg(&grouping.grouped_routes)
            .arg(&grouping.grouped_input)
            .arg(&routes)
            .arg(&input_rows)
            .arg(&input_rows_are_routes)
            .arg(&top_k)
            .arg(&features);
        // SAFETY: grouped_routes covers every route, grouped_input covers
        // routes*features f32 values, and source row selection is bounds guarded.
        unsafe {
            builder.launch(
                self.pointwise_launch_config(as_u64("grouped gather element count", total)?)?,
            )
        }
        .map(|_| ())
        .map_err(|err| driver_err("gather QMoE expert activation rows", err))
    }

    fn launch_grouped_linear(
        &self,
        grouping: ExpertGrouping,
        weights: QuantizedExperts<'_>,
        output: CUdeviceptr,
        routes: usize,
        experts: usize,
    ) -> Result<()> {
        let capabilities = self.runtime.capabilities();
        let preferred_threads = self.preferred_reduction_threads();
        let tile = qmoe_gemm::tile_for(
            capabilities.compute_capability(),
            preferred_threads,
            capabilities.max_shared_memory_per_block_optin(),
        );
        let (module, source) = qmoe_gemm::module_source(tile);
        let function = self
            .runtime
            .nvrtc_function(module, source, qmoe_gemm::ENTRY)?;
        let tasks = checked_product(
            &[experts, weights.out_features],
            "grouped linear expert-feature task count",
        )?;
        let config = self.runtime.reduction_launch_config(
            &function,
            self.reduction_grid(tasks)?,
            preferred_threads,
            tile.checked_mul(std::mem::size_of::<f32>() as u32)
                .ok_or_else(|| error("grouped GEMM shared-memory stride overflow"))?,
        )?;
        let packed = tensor_ptr(weights.packed);
        let scales = tensor_ptr(weights.scales);
        let zero_points = weights.zero_points.map(tensor_ptr).unwrap_or(0);
        let bias = weights.bias.map(tensor_ptr).unwrap_or(0);
        let routes = as_u64("route count", routes)?;
        let tasks = as_u64("grouped linear task count", tasks)?;
        let gemm_min_tokens = as_u64(
            "prefill GEMM token threshold",
            self.attributes.prefill_min_tokens,
        )?;
        let experts = as_i32("expert count", experts)?;
        let out_features = as_i32("output feature count", weights.out_features)?;
        let in_features = as_i32("input feature count", weights.in_features)?;
        let packed_in = as_i32("packed input width", weights.packed_in)?;
        let blocks = as_i32("block count", weights.blocks)?;
        let zero_point_bytes = as_i32("zero-point row byte count", weights.zero_point_bytes)?;
        let bits = as_i32("expert weight bits", self.bits)?;
        let block_size = as_i32("block size", self.block_size)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&grouping.grouped_input)
            .arg(&grouping.grouped_routes)
            .arg(&grouping.counts)
            .arg(&grouping.offsets)
            .arg(&packed)
            .arg(&scales)
            .arg(&zero_points)
            .arg(&bias)
            .arg(&output)
            .arg(&routes)
            .arg(&tasks)
            .arg(&gemm_min_tokens)
            .arg(&experts)
            .arg(&out_features)
            .arg(&in_features)
            .arg(&packed_in)
            .arg(&blocks)
            .arg(&zero_point_bytes)
            .arg(&bits)
            .arg(&block_size);
        // SAFETY: grouped rows, expert metadata, packed weights, and outputs all
        // have checked sizes. The kernel guards empty experts and every scatter.
        unsafe { builder.launch(config) }
            .map(|_| ())
            .map_err(|err| driver_err("launch QMoE grouped block-dequant GEMM", err))
    }

    #[allow(clippy::too_many_arguments)]
    fn launch_linear(
        &self,
        dtype: FloatDtype,
        input_ptr: CUdeviceptr,
        route_indices: CUdeviceptr,
        expert_counts: Option<CUdeviceptr>,
        weights: QuantizedExperts<'_>,
        output: CUdeviceptr,
        routes: usize,
        input_rows_are_routes: bool,
    ) -> Result<()> {
        let layout = QuantLayout {
            bits: self.bits,
            block_size: self.block_size,
            has_zero_points: weights.zero_points.is_some(),
        };
        let (module, source) = linear_module_source(layout);
        let function = self
            .runtime
            .nvrtc_function(module, source, dtype.linear_entry())?;
        let packed = tensor_ptr(weights.packed);
        let expert_counts = expert_counts.unwrap_or(0);
        let scales = tensor_ptr(weights.scales);
        let zero_points = weights.zero_points.map(tensor_ptr).unwrap_or(0);
        let bias = weights.bias.map(tensor_ptr).unwrap_or(0);
        let tasks = checked_product(&[routes, weights.out_features], "linear output task count")?;
        let grid_x = self.reduction_grid(tasks)?;
        let config = self.runtime.reduction_launch_config(
            &function,
            grid_x,
            self.preferred_reduction_threads(),
            std::mem::size_of::<f32>() as u32,
        )?;
        let routes = as_u64("route count", routes)?;
        let gemm_min_tokens = as_u64(
            "prefill GEMM token threshold",
            self.attributes.prefill_min_tokens,
        )?;
        let input_rows_are_routes = i32::from(input_rows_are_routes);
        let top_k = as_i32("top-k", self.attributes.k)?;
        let out_features = as_i32("output feature count", weights.out_features)?;
        let in_features = as_i32("input feature count", weights.in_features)?;
        let packed_in = as_i32("packed input width", weights.packed_in)?;
        let blocks = as_i32("block count", weights.blocks)?;
        let zero_point_bytes = as_i32("zero-point row byte count", weights.zero_point_bytes)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&input_ptr)
            .arg(&route_indices)
            .arg(&expert_counts)
            .arg(&packed)
            .arg(&scales)
            .arg(&zero_points)
            .arg(&bias)
            .arg(&output)
            .arg(&routes)
            .arg(&gemm_min_tokens)
            .arg(&input_rows_are_routes)
            .arg(&top_k)
            .arg(&out_features)
            .arg(&in_features)
            .arg(&packed_in)
            .arg(&blocks)
            .arg(&zero_point_bytes);
        // SAFETY: all packed tensors and scratch buffers cover the validated
        // expert-major ranges, and the scalar ABI matches `qmoe_linear_*`.
        unsafe { builder.launch(config) }
            .map(|_| ())
            .map_err(|err| driver_err("launch QMoE block-dequant expert GEMV", err))
    }

    fn launch_activation(
        &self,
        fc1: CUdeviceptr,
        fc3: Option<CUdeviceptr>,
        activated: CUdeviceptr,
        routes: usize,
        inter: usize,
    ) -> Result<()> {
        let function = self
            .runtime
            .nvrtc_function(MODULE, CUDA_SRC, ACTIVATE_ENTRY)?;
        let total = checked_product(&[routes, inter], "activation element count")?;
        let config = self.pointwise_launch_config(as_u64("activation element count", total)?)?;
        let fc3 = fc3.unwrap_or(0);
        let routes = as_u64("route count", routes)?;
        let inter = as_i32("intermediate feature count", inter)?;
        let activation = self.attributes.activation.kernel_id();
        let swiglu_fusion = as_i32("swiglu_fusion", self.attributes.swiglu_fusion)?;
        let alpha = self.attributes.activation_alpha;
        let beta = self.attributes.activation_beta;
        let limit = self.attributes.swiglu_limit;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&fc1)
            .arg(&fc3)
            .arg(&activated)
            .arg(&routes)
            .arg(&inter)
            .arg(&activation)
            .arg(&swiglu_fusion)
            .arg(&alpha)
            .arg(&beta)
            .arg(&limit);
        // SAFETY: scratch buffers cover every routed intermediate element and
        // the ABI matches `qmoe_activate`.
        unsafe { builder.launch(config) }
            .map(|_| ())
            .map_err(|err| driver_err("launch QMoE activation", err))
    }

    fn launch_combine(
        &self,
        dtype: FloatDtype,
        route_output: CUdeviceptr,
        route_weights: CUdeviceptr,
        output: &mut TensorMut,
        rows: usize,
        hidden: usize,
    ) -> Result<()> {
        let function = self
            .runtime
            .nvrtc_function(MODULE, CUDA_SRC, dtype.combine_entry())?;
        let total = checked_product(&[rows, hidden], "combined output element count")?;
        let config = self.pointwise_launch_config(as_u64("output element count", total)?)?;
        let output_ptr = cuptr(output.data_ptr_mut::<u8>() as *const c_void);
        let rows = as_u64("row count", rows)?;
        let hidden = as_i32("hidden feature count", hidden)?;
        let top_k = as_i32("top-k", self.attributes.k)?;
        let mut builder = self.runtime.stream().launch_builder(&function);
        builder
            .arg(&route_output)
            .arg(&route_weights)
            .arg(&output_ptr)
            .arg(&rows)
            .arg(&hidden)
            .arg(&top_k);
        // SAFETY: routed output and weights cover rows*top_k, output covers
        // rows*hidden, and the ABI matches `qmoe_combine_*`.
        unsafe { builder.launch(config) }
            .map(|_| ())
            .map_err(|err| driver_err("launch QMoE weighted combine", err))
    }

    fn preferred_reduction_threads(&self) -> u32 {
        let capabilities = self.runtime.capabilities();
        let preferred = if capabilities.compute_capability().0 >= 7 {
            256
        } else {
            128
        };
        preferred.min(capabilities.max_threads_per_block())
    }

    fn reduction_grid(&self, tasks: usize) -> Result<u32> {
        if tasks == 0 {
            return Ok(1);
        }
        let capabilities = self.runtime.capabilities();
        let saturation = u64::from(capabilities.multiprocessor_count()).saturating_mul(16);
        let grid = u64::try_from(tasks)
            .unwrap_or(u64::MAX)
            .min(saturation.max(1))
            .min(u64::from(u32::MAX));
        u32::try_from(grid).map_err(|_| error("reduction grid exceeds CUDA limits"))
    }

    fn pointwise_launch_config(&self, total: u64) -> Result<LaunchConfig> {
        let capabilities = self.runtime.capabilities();
        let preferred = if capabilities.compute_capability().0 >= 7 {
            256
        } else {
            128
        };
        let threads = preferred.min(capabilities.max_threads_per_block()).max(1);
        let blocks_needed = total.div_ceil(u64::from(threads)).max(1);
        let saturation = u64::from(capabilities.multiprocessor_count()).saturating_mul(16);
        let grid_x = blocks_needed
            .min(saturation.max(1))
            .min(u64::from(u32::MAX));
        Ok(LaunchConfig {
            grid_dim: (
                u32::try_from(grid_x).map_err(|_| error("pointwise grid exceeds CUDA limits"))?,
                1,
                1,
            ),
            block_dim: (threads, 1, 1),
            shared_mem_bytes: 0,
        })
    }
}

const SCRATCH_SLOTS: usize = 11;

#[derive(Clone, Copy, Debug, Default)]
struct ScratchSlot {
    ptr: CUdeviceptr,
    capacity: usize,
}

#[derive(Debug)]
struct ScratchPool {
    slots: [ScratchSlot; SCRATCH_SLOTS],
}

impl Default for ScratchPool {
    fn default() -> Self {
        Self {
            slots: [ScratchSlot::default(); SCRATCH_SLOTS],
        }
    }
}

impl ScratchPool {
    fn ensure(
        &mut self,
        runtime: &CudaRuntime,
        index: usize,
        bytes: usize,
        capturing: bool,
    ) -> Result<CUdeviceptr> {
        let slot = &mut self.slots[index];
        let bytes = bytes.max(1);
        if slot.ptr != 0 && slot.capacity >= bytes {
            return Ok(slot.ptr);
        }
        if capturing {
            return Err(error(format!(
                "QMoE scratch slot {index} needs {bytes} bytes but the warmed capacity is {} bytes",
                slot.capacity
            )));
        }
        let fresh = runtime.alloc_raw(bytes)?;
        if slot.ptr != 0 {
            // SAFETY: the previous pointer came from this runtime and is replaced
            // only after the new allocation succeeds.
            unsafe {
                let _ = runtime.free_raw(slot.ptr);
            }
        }
        slot.ptr = fresh;
        slot.capacity = bytes;
        Ok(fresh)
    }
}

impl Drop for QMoEKernel {
    fn drop(&mut self) {
        let scratch = self
            .scratch
            .get_mut()
            .expect("cuda_ep QMoE scratch pool poisoned");
        for slot in scratch.slots.iter_mut().rev() {
            if slot.ptr != 0 {
                // SAFETY: every non-zero pointer came from this runtime and is
                // freed exactly once when the kernel is dropped.
                let _ = unsafe { self.runtime.free_raw(slot.ptr) };
                slot.ptr = 0;
                slot.capacity = 0;
            }
        }
    }
}

fn tensor_ptr(tensor: &TensorView) -> CUdeviceptr {
    cuptr(tensor.data_ptr::<u8>() as *const c_void)
}

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

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

fn bool_attr(node: &Node, name: &str, default: bool) -> Result<bool> {
    match int_attr(node, name, i64::from(default))? {
        0 => Ok(false),
        1 => Ok(true),
        value => Err(error(format!(
            "attribute {name} must be 0 or 1, got {value}"
        ))),
    }
}

fn float_attr(node: &Node, name: &str, default: f32) -> Result<f32> {
    match node.attr(name) {
        Some(value) => value
            .as_float()
            .ok_or_else(|| error(format!("attribute {name} must be a float"))),
        None => Ok(default),
    }
}

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

fn require_rank(name: &str, shape: &[usize], rank: usize) -> Result<()> {
    if shape.len() != rank {
        return Err(error(format!(
            "{name} must be {rank}-D, got shape {shape:?}"
        )));
    }
    Ok(())
}

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

fn checked_product(factors: &[usize], context: &str) -> Result<usize> {
    let mut product = 1usize;
    let mut has_zero = false;
    for &factor in factors {
        if factor == 0 {
            has_zero = true;
        } else {
            product = product
                .checked_mul(factor)
                .ok_or_else(|| error(format!("{context} exceeds usize limits")))?;
        }
    }
    Ok(if has_zero { 0 } else { product })
}

fn checked_bytes(elements: usize, element_size: usize, context: &str) -> Result<usize> {
    let bytes = elements
        .checked_mul(element_size)
        .ok_or_else(|| error(format!("{context} byte count exceeds usize limits")))?;
    if bytes > isize::MAX as usize {
        return Err(error(format!(
            "{context} byte count {bytes} exceeds isize::MAX"
        )));
    }
    Ok(bytes)
}

fn checked_tensor_layout(name: &str, shape: &[usize], dtype: DataType) -> Result<usize> {
    let elements = checked_product(shape, &format!("{name} element count"))?;
    checked_bytes(elements, dtype.byte_size(), name)?;
    Ok(elements)
}

fn checked_div_ceil(value: usize, divisor: usize, context: &str) -> Result<usize> {
    value
        .checked_add(divisor - 1)
        .map(|adjusted| adjusted / divisor)
        .ok_or_else(|| error(format!("{context} exceeds usize limits")))
}

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

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use onnx_runtime_ir::{Attribute, NodeId};

    fn node(attrs: &[(&str, Attribute)]) -> Node {
        let mut node = Node::new(NodeId(0), "QMoE", Vec::new(), Vec::new());
        node.domain = "com.microsoft".into();
        for (name, value) in attrs {
            node.attributes.insert((*name).into(), value.clone());
        }
        node
    }

    #[test]
    fn attributes_match_cpu_activation_contract() {
        for activation in ["relu", "gelu", "silu", "swiglu", "identity"] {
            let attrs = MoeAttributes::from_node(&node(&[(
                "activation_type",
                Attribute::String(activation.as_bytes().to_vec()),
            )]))
            .unwrap();
            assert!(attrs.activation.kernel_id() >= 0);
        }
    }

    #[test]
    fn placement_accepts_byte_dividing_integer_widths_only() {
        for bits in [1, 2, 4, 8] {
            let supported = node(&[
                ("expert_weight_bits", Attribute::Int(bits)),
                ("block_size", Attribute::Int(16)),
            ]);
            assert!(unsupported_reason(&supported).is_none(), "bits={bits}");
        }
        for bits in [0, 3, 5, 16] {
            let unsupported = node(&[
                ("expert_weight_bits", Attribute::Int(bits)),
                ("block_size", Attribute::Int(16)),
            ]);
            assert!(unsupported_reason(&unsupported).is_some(), "bits={bits}");
            let reason = unsupported_reason(&unsupported).expect("unsupported bits reason");
            assert!(reason.contains("1, 2, 4, or 8"), "{reason}");
            assert!(reason.contains("requantize"), "{reason}");
        }
    }

    #[test]
    fn placement_rejects_native_iq_layouts_until_block_quantized_moe_exists() {
        for quant_type in [
            "mxfp4", "iq4_nl", "iq4_xs", "iq3_s", "iq3_xxs", "iq2_s", "iq2_xs", "iq2_xxs", "iq1_s",
            "iq1_m",
        ] {
            let unsupported = node(&[
                ("expert_weight_bits", Attribute::Int(2)),
                ("block_size", Attribute::Int(16)),
                (
                    "quant_type",
                    Attribute::String(quant_type.as_bytes().to_vec()),
                ),
            ]);
            assert!(unsupported_reason(&unsupported).is_some(), "{quant_type}");
        }
    }

    #[test]
    fn checked_product_does_not_hide_overflow_behind_zero() {
        let error = checked_product(&[0, usize::MAX, 2], "test").unwrap_err();
        assert!(error.to_string().contains("exceeds usize limits"));
    }

    #[test]
    fn launch_preferences_are_compute_capability_driven_in_source() {
        assert!(CUDA_SRC.contains("gridDim.x"));
        assert!(!CUDA_SRC.contains("sm_90"));
        assert!(!CUDA_SRC.contains("__CUDA_ARCH__ >= 900"));
    }

    #[test]
    fn linear_sources_specialize_every_quant_layout_dimension() {
        let symmetric = QuantLayout {
            bits: 4,
            block_size: 32,
            has_zero_points: false,
        };
        let affine = QuantLayout {
            has_zero_points: true,
            ..symmetric
        };
        let block_128 = QuantLayout {
            block_size: 128,
            ..affine
        };
        let int8 = QuantLayout {
            bits: 8,
            ..block_128
        };

        let variants = [symmetric, affine, block_128, int8].map(linear_module_source);
        assert_eq!(
            variants
                .map(|variant| variant.0)
                .into_iter()
                .collect::<std::collections::HashSet<_>>()
                .len(),
            variants.len()
        );
        for (layout, (_, source)) in [symmetric, affine, block_128, int8]
            .into_iter()
            .zip(variants)
        {
            assert!(source.contains(&format!("#define QMOE_BITS {}", layout.bits)));
            assert!(source.contains(&format!("#define QMOE_BLOCK_SIZE {}", layout.block_size)));
            assert!(source.contains(&format!(
                "#define QMOE_HAS_ZERO_POINTS {}",
                usize::from(layout.has_zero_points)
            )));
        }
        assert!(variants[0].1.contains("qmoe_int4_chunk"));
    }
}