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
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
//! Fused **normalization** kernels on the GPU via runtime-compiled (NVRTC)
//! kernels: `LayerNormalization` (ai.onnx + `com.microsoft`),
//! `SkipLayerNormalization` and `SimplifiedLayerNormalization` /
//! `RMSNormalization` (`com.microsoft` / ai.onnx).
//!
//! ## Backend choice — custom fused NVRTC, and *why* (the "我们能优化的才自己写" case)
//!
//! A library path (cuDNN/cub reduction + several pointwise passes) reads the
//! activation from HBM multiple times. The **fused** kernel does the mean/variance
//! reduction, the normalize, and the affine (`γ·x̂ + β`) in **one** pass over a
//! single HBM read — the classic normalization fusion win, and PyTorch's own
//! `LayerNorm` CUDA kernel is fused for exactly this reason.
//! `SkipLayerNormalization` folds the residual add (`input + skip + bias`) into
//! the same kernel, saving an entire tensor round-trip. `RMSNormalization` drops
//! the mean subtraction (root-mean-square scale only) — the LLaMA-family norm.
//!
//! Numerics mirror `crates/onnx-runtime-ep-cpu/src/kernels/layernorm.rs`:
//!
//! ```text
//! LayerNorm: y = (x - mean) / sqrt(var + eps) · scale + bias
//! RMSNorm:   y = x / sqrt(mean(x²) + eps) · scale
//! ```
//!
//! with `mean`/`var` the **population** statistics (divide by N) over the
//! normalized axes `[axis..]` (LayerNorm) or the last dimension (Skip/RMS).
//!
//! ## Limits (actionable errors, never panics — RULES.md #1)
//!
//! * activation dtype other than f32/f16/bf16 → deferred (names the dtype + op).
//! * `axis`/last-dim size 0, or a `scale`/`bias`/`gamma`/`beta` length that does
//!   not match the normalized size → rejected, naming the offending length.
//! * non-contiguous (strided) operands → "materialise first" error.

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

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, not_implemented};
use crate::runtime::{CudaRuntime, cuptr};

use super::softmax::resolve_axis;

/// NVRTC source for the fused f32 `LayerNormalization`. One block per group
/// (`group = prod(shape[..axis])`); the block reduces the mean then the variance
/// over `norm_size = prod(shape[axis..])` in shared memory, then writes the
/// normalized+affine output in a third pass. Optional `mean`/`inv_std` outputs
/// are written when the pointers are non-null.
const LAYERNORM_SRC: &str = r#"
#include <cuda_fp16.h>
#include <cuda_bf16.h>

__device__ __forceinline__ float load_layernorm_param(
    const void* values, const int is_half, const int index) {
    return is_half
        ? __half2float(((const __half*)values)[index])
        : ((const float*)values)[index];
}

extern "C" __global__ void layernorm_f32(
    const float* x,
    const float* scale,
    const float* bias,        // null when absent
    float*       y,
    float*       mean_out,    // null when not requested
    float*       invstd_out,  // null when not requested
    const int    num_groups,
    const int    norm_size,
    const int    has_bias,
    const float  epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt  = blockDim.x;

    // Pass 1: mean.
    float s = 0.0f;
    for (int j = tid; j < norm_size; j += nt) s += x[base + j];
    red[tid] = s;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float mean = red[0] / (float)norm_size;
    __syncthreads();

    // Pass 2: population variance.
    float v = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        const float d = x[base + j] - mean;
        v += d * d;
    }
    red[tid] = v;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float var = red[0] / (float)norm_size;
    const float inv_std = 1.0f / sqrtf(var + epsilon);

    if (tid == 0) {
        if (mean_out)   mean_out[g]   = mean;
        if (invstd_out) invstd_out[g] = inv_std;
    }

    // Pass 3: normalize + affine.
    for (int j = tid; j < norm_size; j += nt) {
        const float xhat = (x[base + j] - mean) * inv_std;
        float o = xhat * scale[j];
        if (has_bias) o += bias[j];
        y[base + j] = o;
    }
}

extern "C" __global__ void layernorm_f16(
    const __half* x,
    const void*   scale,
    const void*   bias,
    __half*       y,
    float*        mean_out,
    float*        invstd_out,
    const int     num_groups,
    const int     norm_size,
    const int     scale_is_half,
    const int     bias_is_half,
    const int     has_bias,
    const float   epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt = blockDim.x;

    float s = 0.0f;
    for (int j = tid; j < norm_size; j += nt)
        s += __half2float(x[base + j]);
    red[tid] = s;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float mean = red[0] / (float)norm_size;
    __syncthreads();

    float v = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        const float d = __half2float(x[base + j]) - mean;
        v += d * d;
    }
    red[tid] = v;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float inv_std =
        1.0f / sqrtf(red[0] / (float)norm_size + epsilon);
    if (tid == 0) {
        if (mean_out) mean_out[g] = mean;
        if (invstd_out) invstd_out[g] = inv_std;
    }

    for (int j = tid; j < norm_size; j += nt) {
        const float xhat = (__half2float(x[base + j]) - mean) * inv_std;
        float o = xhat * load_layernorm_param(scale, scale_is_half, j);
        if (has_bias)
            o += load_layernorm_param(bias, bias_is_half, j);
        y[base + j] = __float2half_rn(o);
    }
}

__device__ __forceinline__ float load_layernorm_bf16_param(
    const void* values, const int is_bf16, const int index) {
    return is_bf16
        ? __bfloat162float(((const __nv_bfloat16*)values)[index])
        : ((const float*)values)[index];
}

extern "C" __global__ void layernorm_bf16(
    const __nv_bfloat16* x,
    const void*          scale,
    const void*          bias,
    __nv_bfloat16*       y,
    float*               mean_out,
    float*               invstd_out,
    const int            num_groups,
    const int            norm_size,
    const int            scale_is_bf16,
    const int            bias_is_bf16,
    const int            has_bias,
    const float          epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt = blockDim.x;

    float s = 0.0f;
    for (int j = tid; j < norm_size; j += nt)
        s += __bfloat162float(x[base + j]);
    red[tid] = s;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float mean = red[0] / (float)norm_size;
    __syncthreads();

    float v = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        const float d = __bfloat162float(x[base + j]) - mean;
        v += d * d;
    }
    red[tid] = v;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float inv_std =
        1.0f / sqrtf(red[0] / (float)norm_size + epsilon);
    if (tid == 0) {
        if (mean_out) mean_out[g] = mean;
        if (invstd_out) invstd_out[g] = inv_std;
    }

    for (int j = tid; j < norm_size; j += nt) {
        const float xhat = (__bfloat162float(x[base + j]) - mean) * inv_std;
        float o = xhat * load_layernorm_bf16_param(scale, scale_is_bf16, j);
        if (has_bias)
            o += load_layernorm_bf16_param(bias, bias_is_bf16, j);
        y[base + j] = __float2bfloat16_rn(o);
    }
}
"#;

/// NVRTC source for the fused f32 `RMSNormalization` /
/// `SimplifiedLayerNormalization`: no mean subtraction, scale by the inverse
/// root-mean-square.
const RMSNORM_SRC: &str = r#"
#include <cuda_fp16.h>
#include <cuda_bf16.h>

__device__ __forceinline__ float load_rmsnorm_scale(
    const void* values, const int is_half, const int index) {
    return is_half
        ? __half2float(((const __half*)values)[index])
        : ((const float*)values)[index];
}

extern "C" __global__ void rmsnorm_f32(
    const float* x,
    const float* scale,
    float*       y,
    float*       invstd_out,  // null when not requested
    const int    num_groups,
    const int    norm_size,
    const float  epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt  = blockDim.x;

    // Keep the correctness path in the CPU kernel's left-to-right f32 order.
    // Accuracy-level-4 MatMulNBits quantizes activations, so even a one-ulp
    // normalization difference can cross an int8 rounding boundary in decode.
    if (tid == 0) {
        float ss = 0.0f;
        for (int j = 0; j < norm_size; ++j) {
            const float xv = x[base + j];
            // Match the CPU kernel's separate multiply then add. NVRTC otherwise
            // contracts this expression to FMA and changes recurrent decode state.
            ss = __fadd_rn(ss, __fmul_rn(xv, xv));
        }
        red[0] = ss;
    }
    __syncthreads();
    const float ms = red[0] / (float)norm_size;
    const float inv_std = 1.0f / sqrtf(ms + epsilon);
    if (tid == 0 && invstd_out) invstd_out[g] = inv_std;

    for (int j = tid; j < norm_size; j += nt)
        y[base + j] = x[base + j] * inv_std * scale[j];
}

extern "C" __global__ void rmsnorm_f16(
    const __half* x,
    const void*   scale,
    __half*       y,
    float*        invstd_out,
    const int     num_groups,
    const int     norm_size,
    const int     scale_is_half,
    const float   epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt = blockDim.x;

    float ss = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        const float xv = __half2float(x[base + j]);
        ss += xv * xv;
    }
    red[tid] = ss;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float inv_std =
        1.0f / sqrtf(red[0] / (float)norm_size + epsilon);
    if (tid == 0 && invstd_out) invstd_out[g] = inv_std;

    for (int j = tid; j < norm_size; j += nt) {
        const float o = __half2float(x[base + j]) * inv_std
            * load_rmsnorm_scale(scale, scale_is_half, j);
        y[base + j] = __float2half_rn(o);
    }
}

__device__ __forceinline__ float load_rmsnorm_bf16_scale(
    const void* values, const int is_bf16, const int index) {
    return is_bf16
        ? __bfloat162float(((const __nv_bfloat16*)values)[index])
        : ((const float*)values)[index];
}

extern "C" __global__ void rmsnorm_bf16(
    const __nv_bfloat16* x,
    const void*          scale,
    __nv_bfloat16*       y,
    float*               invstd_out,
    const int            num_groups,
    const int            norm_size,
    const int            scale_is_bf16,
    const float          epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt = blockDim.x;

    float ss = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        const float xv = __bfloat162float(x[base + j]);
        ss += xv * xv;
    }
    red[tid] = ss;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float inv_std =
        1.0f / sqrtf(red[0] / (float)norm_size + epsilon);
    if (tid == 0 && invstd_out) invstd_out[g] = inv_std;

    for (int j = tid; j < norm_size; j += nt) {
        const float o = __bfloat162float(x[base + j]) * inv_std
            * load_rmsnorm_bf16_scale(scale, scale_is_bf16, j);
        y[base + j] = __float2bfloat16_rn(o);
    }
}
"#;

/// NVRTC source for `com.microsoft::SkipSimplifiedLayerNormalization`.
/// The residual sum supports right-aligned NumPy broadcasting for `skip`.
const SKIP_RMSNORM_SRC: &str = r#"
#include <cuda_fp16.h>

__device__ __forceinline__ float load_skip_val(
    const void* values, const int is_half, const int index) {
    return is_half
        ? __half2float(((const __half*)values)[index])
        : ((const float*)values)[index];
}

template <bool DenseSkip>
__device__ __forceinline__ void skip_rmsnorm_f32_tpl(
    const float* input,
    const float* skip,
    const float* gamma,
    const float* bias,          // null when absent
    float*       y,
    float*       sum_out,       // null when not requested
    float*       mean_out,      // null when not requested (always zero)
    float*       invstd_out,    // null when not requested
    const unsigned long long* metadata,
    const int    rank,
    const int    num_groups,
    const int    norm_size,
    const int    has_bias,
    const float  epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;
    const unsigned long long* shape = metadata;
    const unsigned long long* skip_strides = metadata + rank;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt  = blockDim.x;

    float sum_squares = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        unsigned long long skip_index = (unsigned long long)base + j;
        if (!DenseSkip) {
            unsigned long long linear = skip_index;
            skip_index = 0;
            for (int d = rank - 1; d >= 0; --d) {
                const unsigned long long coord = linear % shape[d];
                linear /= shape[d];
                skip_index += coord * skip_strides[d];
            }
        }
        float sv = input[base + j] + skip[skip_index];
        if (has_bias) sv += bias[j];
        y[base + j] = sv;
        if (sum_out) sum_out[base + j] = sv;
        sum_squares = __fadd_rn(sum_squares, __fmul_rn(sv, sv));
    }

    // Fixed block tree: every thread owns the same strided subsequence, then
    // power-of-two offsets combine partials in a launch-invariant order.
    red[tid] = sum_squares;
    __syncthreads();
    for (int offset = nt >> 1; offset > 0; offset >>= 1) {
        if (tid < offset) {
            red[tid] = __fadd_rn(red[tid], red[tid + offset]);
        }
        __syncthreads();
    }
    const float inv_std = 1.0f / sqrtf(red[0] / (float)norm_size + epsilon);
    if (tid == 0) {
        if (mean_out) mean_out[g] = 0.0f;
        if (invstd_out) invstd_out[g] = inv_std;
    }
    __syncthreads();
    for (int j = tid; j < norm_size; j += nt)
        y[base + j] = (y[base + j] * inv_std) * gamma[j];
}

extern "C" __global__ void skip_rmsnorm_f32_dense(
    const float* input,
    const float* skip,
    const float* gamma,
    const float* bias,
    float* y,
    float* sum_out,
    float* mean_out,
    float* invstd_out,
    const unsigned long long* metadata,
    const int rank,
    const int num_groups,
    const int norm_size,
    const int has_bias,
    const float epsilon)
{
    skip_rmsnorm_f32_tpl<true>(input, skip, gamma, bias, y, sum_out, mean_out,
        invstd_out, metadata, rank, num_groups, norm_size, has_bias, epsilon);
}

extern "C" __global__ void skip_rmsnorm_f32(
    const float* input,
    const float* skip,
    const float* gamma,
    const float* bias,
    float* y,
    float* sum_out,
    float* mean_out,
    float* invstd_out,
    const unsigned long long* metadata,
    const int rank,
    const int num_groups,
    const int norm_size,
    const int has_bias,
    const float epsilon)
{
    skip_rmsnorm_f32_tpl<false>(input, skip, gamma, bias, y, sum_out, mean_out,
        invstd_out, metadata, rank, num_groups, norm_size, has_bias, epsilon);
}

union SkipHalf4 {
    unsigned long long raw;
    __half2 pair[2];
};

// One warp covers aligned half4 chunks. The launch predicate guarantees that
// norm_size is divisible by 32 lanes * 4 halves, so every lane owns the same
// number of complete chunks and no tail handling is needed.
extern "C" __global__ void skip_rmsnorm_f16_warp_half4(
    const __half* input,
    const __half* skip,
    const void*   gamma,
    const void*   bias,
    __half*       y,
    __half*       sum_out,
    void*         mean_out,
    void*         invstd_out,
    const unsigned long long* metadata,
    const int     rank,
    const int     num_groups,
    const int     norm_size,
    const int     has_bias,
    const int     dense_skip,
    const int     gamma_is_half,
    const int     bias_is_half,
    const int     stat_is_half,
    const float   epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;
    const int lane = threadIdx.x;
    const int chunks_per_lane = norm_size / (32 * 4);
    const unsigned long long* input4 =
        (const unsigned long long*)(input + base);
    const unsigned long long* skip4 =
        (const unsigned long long*)(skip + base);
    const unsigned long long* gamma4 =
        (const unsigned long long*)gamma;
    unsigned long long* y4 = (unsigned long long*)(y + base);
    unsigned long long* sum4 =
        sum_out ? (unsigned long long*)(sum_out + base) : 0;
    float ss0 = 0.0f;
    float ss1 = 0.0f;
    float ss2 = 0.0f;
    float ss3 = 0.0f;

    for (int item = 0; item < chunks_per_lane; ++item) {
        const int chunk = lane + item * 32;
        SkipHalf4 input_v;
        SkipHalf4 skip_v;
        SkipHalf4 residual;
        input_v.raw = input4[chunk];
        skip_v.raw = skip4[chunk];
        residual.pair[0] = __hadd2(input_v.pair[0], skip_v.pair[0]);
        residual.pair[1] = __hadd2(input_v.pair[1], skip_v.pair[1]);
        y4[chunk] = residual.raw;
        if (sum4) sum4[chunk] = residual.raw;
        const float2 rounded0 = __half22float2(residual.pair[0]);
        const float2 rounded1 = __half22float2(residual.pair[1]);
        ss0 += rounded0.x * rounded0.x;
        ss1 += rounded0.y * rounded0.y;
        ss2 += rounded1.x * rounded1.x;
        ss3 += rounded1.y * rounded1.y;
    }

    float ss = (ss0 + ss1) + (ss2 + ss3);
    for (int off = 16; off > 0; off >>= 1) {
        ss += __shfl_down_sync(0xffffffffu, ss, off);
    }
    float inv_std = 0.0f;
    if (lane == 0) {
        inv_std = 1.0f / sqrtf(ss / (float)norm_size + epsilon);
        if (mean_out) {
            if (stat_is_half) ((__half*)mean_out)[g] = __float2half_rn(0.0f);
            else ((float*)mean_out)[g] = 0.0f;
        }
        if (invstd_out) {
            if (stat_is_half) ((__half*)invstd_out)[g] = __float2half_rn(inv_std);
            else ((float*)invstd_out)[g] = inv_std;
        }
    }
    inv_std = __shfl_sync(0xffffffffu, inv_std, 0);

    const float* gamma_f = (const float*)gamma;
    for (int item = 0; item < chunks_per_lane; ++item) {
        const int chunk = lane + item * 32;
        SkipHalf4 residual;
        SkipHalf4 output;
        residual.raw = y4[chunk];
        const float2 value0 = __half22float2(residual.pair[0]);
        const float2 value1 = __half22float2(residual.pair[1]);
        // gamma is only ever a final multiplicand (never part of the fp32
        // variance accumulation), so an fp32 gamma is loaded at full precision
        // while an fp16 gamma keeps the wide half4 load. This lets decoders that
        // export gamma in fp32 (e.g. Phi) still take the vectorized warp path.
        float scale0x, scale0y, scale1x, scale1y;
        if (gamma_is_half) {
            SkipHalf4 scale;
            scale.raw = gamma4[chunk];
            const float2 scale0 = __half22float2(scale.pair[0]);
            const float2 scale1 = __half22float2(scale.pair[1]);
            scale0x = scale0.x;
            scale0y = scale0.y;
            scale1x = scale1.x;
            scale1y = scale1.y;
        } else {
            const int j = chunk << 2;
            scale0x = gamma_f[j];
            scale0y = gamma_f[j + 1];
            scale1x = gamma_f[j + 2];
            scale1y = gamma_f[j + 3];
        }
        output.pair[0] = __floats2half2_rn(
            value0.x * inv_std * scale0x,
            value0.y * inv_std * scale0y);
        output.pair[1] = __floats2half2_rn(
            value1.x * inv_std * scale1x,
            value1.y * inv_std * scale1y);
        y4[chunk] = output.raw;
    }
}

extern "C" __global__ void skip_rmsnorm_f16(
    const __half* input,
    const __half* skip,
    const void*   gamma,
    const void*   bias,         // null when absent
    __half*       y,
    __half*       sum_out,      // null when not requested
    void*         mean_out,     // null when not requested (always zero)
    void*         invstd_out,   // null when not requested
    const unsigned long long* metadata,
    const int     rank,
    const int     num_groups,
    const int     norm_size,
    const int     has_bias,
    const int     dense_skip,
    const int     gamma_is_half,
    const int     bias_is_half,
    const int     stat_is_half,
    const float   epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;
    const unsigned long long* shape = metadata;
    const unsigned long long* skip_strides = metadata + rank;

    const int lane = threadIdx.x;

    // fp32 accumulate over the fp16-rounded residual so the RMS matches the
    // residual value stored into `sum_out` and reused by the next layer.
    float ss = 0.0f;
    const bool vectorized = dense_skip && ((base & 1) == 0);
    if (vectorized) {
        const int pairs = norm_size >> 1;
        const __half2* input2 = (const __half2*)(input + base);
        const __half2* skip2 = (const __half2*)(skip + base);
        __half2* y2 = (__half2*)(y + base);
        __half2* sum2 = sum_out ? (__half2*)(sum_out + base) : 0;
        for (int pair = lane; pair < pairs; pair += 32) {
            const float2 input_v = __half22float2(input2[pair]);
            const float2 skip_v = __half22float2(skip2[pair]);
            const int j = pair << 1;
            float sv0 = input_v.x + skip_v.x;
            float sv1 = input_v.y + skip_v.y;
            if (has_bias) {
                sv0 += load_skip_val(bias, bias_is_half, j);
                sv1 += load_skip_val(bias, bias_is_half, j + 1);
            }
            const __half svh0 = __float2half_rn(sv0);
            const __half svh1 = __float2half_rn(sv1);
            const __half2 svh = __halves2half2(svh0, svh1);
            y2[pair] = svh;
            if (sum2) sum2[pair] = svh;
            const float2 rounded = __half22float2(svh);
            ss += rounded.x * rounded.x;
            ss += rounded.y * rounded.y;
        }
        if ((norm_size & 1) && lane == 0) {
            const int j = norm_size - 1;
            float sv = __half2float(input[base + j]) + __half2float(skip[base + j]);
            if (has_bias) sv += load_skip_val(bias, bias_is_half, j);
            const __half svh = __float2half_rn(sv);
            y[base + j] = svh;
            if (sum_out) sum_out[base + j] = svh;
            const float rounded = __half2float(svh);
            ss += rounded * rounded;
        }
    } else {
        for (int j = lane; j < norm_size; j += 32) {
            unsigned long long linear = (unsigned long long)base + j;
            unsigned long long skip_index = 0;
            for (int d = rank - 1; d >= 0; --d) {
                const unsigned long long coord = linear % shape[d];
                linear /= shape[d];
                skip_index += coord * skip_strides[d];
            }
            float sv = __half2float(input[base + j]) + __half2float(skip[skip_index]);
            if (has_bias) sv += load_skip_val(bias, bias_is_half, j);
            const __half svh = __float2half_rn(sv);
            y[base + j] = svh;
            if (sum_out) sum_out[base + j] = svh;
            const float rounded = __half2float(svh);
            ss += rounded * rounded;
        }
    }
    __syncwarp();
    for (int off = 16; off > 0; off >>= 1) {
        ss += __shfl_down_sync(0xffffffffu, ss, off);
    }
    float inv_std = 0.0f;
    if (lane == 0) {
        inv_std = 1.0f / sqrtf(ss / (float)norm_size + epsilon);
        if (mean_out) {
            if (stat_is_half) ((__half*)mean_out)[g] = __float2half_rn(0.0f);
            else ((float*)mean_out)[g] = 0.0f;
        }
        if (invstd_out) {
            if (stat_is_half) ((__half*)invstd_out)[g] = __float2half_rn(inv_std);
            else ((float*)invstd_out)[g] = inv_std;
        }
    }
    inv_std = __shfl_sync(0xffffffffu, inv_std, 0);
    if (vectorized) {
        const int pairs = norm_size >> 1;
        __half2* y2 = (__half2*)(y + base);
        for (int pair = lane; pair < pairs; pair += 32) {
            const float2 residual = __half22float2(y2[pair]);
            const int j = pair << 1;
            const float out0 = residual.x * inv_std
                * load_skip_val(gamma, gamma_is_half, j);
            const float out1 = residual.y * inv_std
                * load_skip_val(gamma, gamma_is_half, j + 1);
            y2[pair] = __floats2half2_rn(out0, out1);
        }
        if ((norm_size & 1) && lane == 0) {
            const int j = norm_size - 1;
            const float v = __half2float(y[base + j]) * inv_std
                * load_skip_val(gamma, gamma_is_half, j);
            y[base + j] = __float2half_rn(v);
        }
    } else {
        for (int j = lane; j < norm_size; j += 32) {
            const float v = __half2float(y[base + j]) * inv_std
                * load_skip_val(gamma, gamma_is_half, j);
            y[base + j] = __float2half_rn(v);
        }
    }
}
"#;

/// NVRTC source for the fused f32 `SkipLayerNormalization` (`com.microsoft`):
/// `y = LayerNorm(input + skip + bias) · gamma + beta`. The residual sum is
/// computed once into `y` (scratch) and optionally published to `sum_out`, then
/// the standard two-pass LayerNorm runs over it.
const SKIP_LAYERNORM_SRC: &str = r#"
extern "C" __global__ void skip_layernorm_f32(
    const float* input,
    const float* skip,
    const float* gamma,
    const float* beta,        // null when absent
    const float* bias,        // null when absent (per-channel, length norm_size)
    float*       y,
    float*       sum_out,      // null when not requested
    float*       mean_out,     // null when not requested
    float*       invstd_out,   // null when not requested
    const int    num_groups,
    const int    norm_size,
    const int    has_beta,
    const int    has_bias,
    const float  epsilon)
{
    const int g = blockIdx.x;
    if (g >= num_groups) return;
    const size_t base = (size_t)g * norm_size;

    extern __shared__ float red[];
    const int tid = threadIdx.x;
    const int nt  = blockDim.x;

    // Residual sum s = input + skip (+ bias); stash in y and optionally sum_out.
    for (int j = tid; j < norm_size; j += nt) {
        float sv = input[base + j] + skip[base + j];
        if (has_bias) sv += bias[j];
        y[base + j] = sv;
        if (sum_out) sum_out[base + j] = sv;
    }
    __syncthreads();

    // Pass 1: mean of s.
    float s = 0.0f;
    for (int j = tid; j < norm_size; j += nt) s += y[base + j];
    red[tid] = s;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float mean = red[0] / (float)norm_size;
    __syncthreads();

    // Pass 2: population variance of s.
    float v = 0.0f;
    for (int j = tid; j < norm_size; j += nt) {
        const float d = y[base + j] - mean;
        v += d * d;
    }
    red[tid] = v;
    __syncthreads();
    for (int off = nt >> 1; off > 0; off >>= 1) {
        if (tid < off) red[tid] += red[tid + off];
        __syncthreads();
    }
    const float var = red[0] / (float)norm_size;
    const float inv_std = 1.0f / sqrtf(var + epsilon);
    if (tid == 0) {
        if (mean_out)   mean_out[g]   = mean;
        if (invstd_out) invstd_out[g] = inv_std;
    }
    __syncthreads();

    // Pass 3: normalize + affine (gamma / optional beta).
    for (int j = tid; j < norm_size; j += nt) {
        const float xhat = (y[base + j] - mean) * inv_std;
        float o = xhat * gamma[j];
        if (has_beta) o += beta[j];
        y[base + j] = o;
    }
}
"#;

const LAYERNORM_MODULE: &str = "layernorm_bf16_v2";
const RMSNORM_MODULE: &str = "rmsnorm_bf16_v2";
const SKIP_RMSNORM_MODULE: &str = "skip_rmsnorm_f16_warp_v5";
const SKIP_LAYERNORM_MODULE: &str = "skip_layernorm_f32";

/// Threads per block for the norm reductions (power of two → exact tree reduce).
const NORM_BLOCK: u32 = 256;
const SKIP_RMSNORM_WARP_HALF4_MULTIPLE: usize = 32 * 4;

fn preferred_norm_block_threads(norm_size: usize, max_threads_per_block: u32) -> u32 {
    let reported_limit = max_threads_per_block.clamp(32, NORM_BLOCK);
    let device_limit = 1 << (31 - reported_limit.leading_zeros());
    let useful_threads = norm_size
        .max(32)
        .next_power_of_two()
        .min(NORM_BLOCK as usize) as u32;
    useful_threads.min(device_limit)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SkipRmsnormVariant {
    F32Dense,
    F32,
    F16Generic,
    F16WarpHalf4,
}

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

/// Environment opt-out for the fp32-gamma warp-half4 path, mirroring the other
/// CUDA A/B switches. Any value other than unset/empty/`0` forces an fp16
/// activation norm with an fp32 gamma back onto the generic warp kernel (for
/// A/B measurement or rollback); an fp16 gamma is unaffected.
const FP32_GAMMA_WARP_DISABLE_ENV: &str = "ONNX_GENAI_CUDA_DISABLE_FP32_GAMMA_WARP_NORM";

fn fp32_gamma_warp_disabled() -> bool {
    std::env::var_os(FP32_GAMMA_WARP_DISABLE_ENV)
        .is_some_and(|value| value != "0" && !value.is_empty())
}

/// Select the one-warp half4 path by its actual data-layout capabilities, never
/// by a model-specific hidden dimension.
fn select_skip_rmsnorm_variant(
    is_half: bool,
    dense_skip: bool,
    norm_size: usize,
    has_bias: bool,
    gamma_is_half: bool,
) -> SkipRmsnormSelection {
    // gamma is only a final multiplicand (never part of the fp32 variance
    // accumulation), so the vectorized warp path serves an fp32 gamma at full
    // precision too. The A/B switch keeps the pre-existing fp16-gamma-only gate.
    let gamma_ok = gamma_is_half || !fp32_gamma_warp_disabled();
    if is_half
        && dense_skip
        && norm_size.is_multiple_of(SKIP_RMSNORM_WARP_HALF4_MULTIPLE)
        && !has_bias
        && gamma_ok
    {
        SkipRmsnormSelection {
            variant: SkipRmsnormVariant::F16WarpHalf4,
            entry: "skip_rmsnorm_f16_warp_half4",
            reason: if gamma_is_half {
                "variant=warp_half4;dtype=fp16;dense_skip;bias=none;gamma=fp16;\
                 hidden%128==0;one_warp"
            } else {
                "variant=warp_half4;dtype=fp16;dense_skip;bias=none;gamma=fp32;\
                 hidden%128==0;one_warp"
            },
        }
    } else if is_half {
        SkipRmsnormSelection {
            variant: SkipRmsnormVariant::F16Generic,
            entry: "skip_rmsnorm_f16",
            reason: "variant=generic;dtype=fp16;not(dense_skip & bias=none & \
                     hidden%128==0)",
        }
    } else if dense_skip {
        SkipRmsnormSelection {
            variant: SkipRmsnormVariant::F32Dense,
            entry: "skip_rmsnorm_f32_dense",
            reason: "variant=parallel_block_tree;dtype=fp32;dense_skip;fixed_reduction_order",
        }
    } else {
        SkipRmsnormSelection {
            variant: SkipRmsnormVariant::F32,
            entry: "skip_rmsnorm_f32",
            reason: "variant=generic;dtype=fp32",
        }
    }
}

/// Reject any non-f32 tensor with an actionable, op-named error (RULES.md #1).
fn require_f32(op: &str, name: &str, dt: DataType) -> Result<()> {
    if dt != DataType::Float32 {
        return Err(not_implemented(format!(
            "{op} with {name} dtype {dt:?} (this slice is f32-only; f16/bf16 pending)"
        )));
    }
    Ok(())
}

fn require_float_storage(op: &str, name: &str, dt: DataType) -> Result<()> {
    if !matches!(
        dt,
        DataType::Float16 | DataType::BFloat16 | DataType::Float32
    ) {
        return Err(not_implemented(format!(
            "{op} with {name} dtype {dt:?} (expected f16, bf16, or f32)"
        )));
    }
    Ok(())
}

fn require_param_for_activation(
    op: &str,
    name: &str,
    activation: DataType,
    parameter: DataType,
) -> Result<()> {
    if parameter != DataType::Float32 && parameter != activation {
        return Err(not_implemented(format!(
            "{op} with {name} dtype {parameter:?} for {activation:?} activations \
             (expected matching storage dtype or f32)"
        )));
    }
    Ok(())
}

fn require_f16_or_f32(op: &str, name: &str, dt: DataType) -> Result<()> {
    if !matches!(dt, DataType::Float16 | DataType::Float32) {
        return Err(not_implemented(format!(
            "{op} with {name} dtype {dt:?} (expected f16 or f32)"
        )));
    }
    Ok(())
}

fn layernorm_entry(dtype: DataType) -> &'static str {
    match dtype {
        DataType::Float16 => "layernorm_f16",
        DataType::BFloat16 => "layernorm_bf16",
        DataType::Float32 => "layernorm_f32",
        _ => unreachable!("LayerNormalization dtype must be validated before dispatch"),
    }
}

fn rmsnorm_entry(dtype: DataType) -> &'static str {
    match dtype {
        DataType::Float16 => "rmsnorm_f16",
        DataType::BFloat16 => "rmsnorm_bf16",
        DataType::Float32 => "rmsnorm_f32",
        _ => unreachable!("RMSNormalization dtype must be validated before dispatch"),
    }
}

/// Reject a strided view with a "materialise first" error.
fn require_contiguous(op: &str, name: &str, contiguous: bool) -> Result<()> {
    if !contiguous {
        return Err(not_implemented(format!(
            "{op} with a non-contiguous (strided) {name}; \
             insert an explicit copy to materialise it before the op"
        )));
    }
    Ok(())
}

fn dim_overflow(op: &str, name: &str, v: usize) -> EpError {
    EpError::KernelFailed(format!(
        "cuda_ep {op}: {name} ({v}) exceeds the i32 kernel bound"
    ))
}

// ───────────────────────────── LayerNormalization ──────────────────────────

/// Factory reading `axis` (default -1) and `epsilon` (default 1e-5).
pub struct LayerNormFactory {
    pub runtime: Arc<CudaRuntime>,
}

impl KernelFactory for LayerNormFactory {
    fn create(&self, node: &Node, _input_shapes: &[Vec<usize>]) -> Result<Box<dyn Kernel>> {
        let axis = node.attr("axis").and_then(|a| a.as_int()).unwrap_or(-1);
        let epsilon = node
            .attr("epsilon")
            .and_then(|a| a.as_float())
            .unwrap_or(1e-5);
        Ok(Box::new(LayerNormKernel {
            axis,
            epsilon,
            runtime: self.runtime.clone(),
            warmed_signature: Mutex::new(None),
            last_call_capture_safe: AtomicBool::new(false),
        }))
    }
}

/// Fused f32/f16 LayerNormalization kernel.
#[derive(Debug)]
pub struct LayerNormKernel {
    axis: i64,
    epsilon: f32,
    runtime: Arc<CudaRuntime>,
    warmed_signature: Mutex<Option<NormCaptureSignature>>,
    last_call_capture_safe: AtomicBool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct NormCaptureSignature {
    activation_dtype: DataType,
    scale_dtype: DataType,
    bias_dtype: Option<DataType>,
    input_shape: Vec<usize>,
    output_dtypes_and_shapes: Vec<(DataType, Vec<usize>)>,
}

impl NormCaptureSignature {
    /// Build the exact-shape capture signature for a normalization launch.
    ///
    /// CUDA graph replay re-runs the recorded kernel verbatim, so the launch
    /// geometry — fixed by `num_groups` (`prod(input_shape[..axis])`) and the
    /// normalization size — together with every activation/scale/bias dtype and
    /// output dtype/shape must be byte-for-byte identical between the eager
    /// warmup and the captured step. Encoding all of them here lets the
    /// warmed-signature drift check reject any change during capture, so a
    /// fixed multi-group shape (e.g. Qwen3's per-head Q/K RMSNorm, 16 or 8
    /// groups per layer) is exactly as replayable as a single-group token norm:
    /// both resolve a deterministic launch config from the fixed shape with no
    /// host-side runtime-value branching or per-op allocation.
    fn build(
        activation_dtype: DataType,
        scale_dtype: DataType,
        bias_dtype: Option<DataType>,
        input_shape: &[usize],
        outputs: &[TensorMut],
    ) -> Self {
        Self {
            activation_dtype,
            scale_dtype,
            bias_dtype,
            input_shape: input_shape.to_vec(),
            output_dtypes_and_shapes: outputs
                .iter()
                .map(|output| (output.dtype, output.shape.to_vec()))
                .collect(),
        }
    }
}

impl LayerNormKernel {
    fn run(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.last_call_capture_safe.store(false, Ordering::Relaxed);
        if !(2..=3).contains(&inputs.len()) || outputs.is_empty() || outputs.len() > 3 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep LayerNormalization: expected 2-3 inputs (X, Scale[, B]) and \
                 1-3 outputs (Y[, Mean, InvStdDev]), got {} and {}",
                inputs.len(),
                outputs.len()
            )));
        }
        let x = &inputs[0];
        let scale = &inputs[1];
        let bias = inputs.get(2);
        require_float_storage("LayerNormalization", "X", x.dtype)?;
        if x.dtype == DataType::Float32 {
            require_f32("LayerNormalization", "Scale", scale.dtype)?;
        } else {
            require_param_for_activation("LayerNormalization", "Scale", x.dtype, scale.dtype)?;
        }
        if outputs[0].dtype != x.dtype {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep LayerNormalization: Y dtype {:?} must match X dtype {:?}",
                outputs[0].dtype, x.dtype
            )));
        }
        require_contiguous("LayerNormalization", "X", x.is_contiguous())?;
        require_contiguous("LayerNormalization", "Scale", scale.is_contiguous())?;
        require_contiguous("LayerNormalization", "Y", outputs[0].is_contiguous())?;

        let rank = x.shape.len();
        let axis = resolve_axis("LayerNormalization", self.axis, rank)?;
        let norm_size: usize = x.shape[axis..].iter().product();
        let num_groups: usize = x.shape[..axis].iter().product();
        if norm_size == 0 {
            return Err(EpError::KernelFailed(
                "cuda_ep LayerNormalization: empty normalization axis".into(),
            ));
        }
        if scale.numel() != norm_size {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep LayerNormalization: Scale has {} elements, expected {norm_size} \
                 (= prod(shape[axis..]))",
                scale.numel()
            )));
        }
        let bias_ptr = match bias {
            None => 0u64,
            Some(b) => {
                if x.dtype == DataType::Float32 {
                    require_f32("LayerNormalization", "B", b.dtype)?;
                } else {
                    require_param_for_activation("LayerNormalization", "B", x.dtype, b.dtype)?;
                }
                require_contiguous("LayerNormalization", "B", b.is_contiguous())?;
                if b.numel() != norm_size {
                    return Err(EpError::KernelFailed(format!(
                        "cuda_ep LayerNormalization: B has {} elements, expected {norm_size}",
                        b.numel()
                    )));
                }
                cuptr(b.data_ptr::<u8>() as *const c_void)
            }
        };
        if outputs[0].shape != x.shape {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep LayerNormalization: Y shape {:?} must equal X shape {:?}",
                outputs[0].shape, x.shape
            )));
        }
        if num_groups == 0 {
            return Ok(());
        }
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let elements = x.numel() as u64;
            let groups = num_groups as u64;
            let mut flops = elements
                .saturating_mul(7)
                .saturating_add(groups.saturating_mul(5));
            if bias.is_some() {
                flops = flops.saturating_add(elements);
            }
            flops
        });

        // Optional Mean / InvStdDev outputs (per group). Validate dtype only when
        // present; their length is num_groups.
        let x_ptr = cuptr(x.data_ptr::<u8>() as *const c_void);
        let scale_ptr = cuptr(scale.data_ptr::<u8>() as *const c_void);
        let y_ptr = cuptr(outputs[0].data_ptr_mut::<u8>() as *const c_void);
        let (mean_ptr, invstd_ptr) = optional_stat_ptrs("LayerNormalization", outputs, num_groups)?;

        let (groups_u, norm_i) = (
            u32::try_from(num_groups)
                .map_err(|_| dim_overflow("LayerNormalization", "num_groups", num_groups))?,
            i32::try_from(norm_size)
                .map_err(|_| dim_overflow("LayerNormalization", "norm_size", norm_size))?,
        );
        let has_bias: i32 = i32::from(bias_ptr != 0);
        let eps = self.epsilon;
        let groups_i = groups_u_i32(groups_u);
        let signature = NormCaptureSignature::build(
            x.dtype,
            scale.dtype,
            bias.map(|bias| bias.dtype),
            x.shape,
            outputs,
        );
        let capturing = self.runtime.is_capturing()?;
        let mut warmed_signature = self
            .warmed_signature
            .lock()
            .expect("cuda_ep LayerNormalization capture signature poisoned");
        if capturing && warmed_signature.as_ref() != Some(&signature) {
            return Err(EpError::KernelFailed(
                "cuda_ep LayerNormalization: dtype or shape changed during CUDA graph capture; warm the exact fixed-shape signature before capture"
                    .into(),
            ));
        }

        let entry = layernorm_entry(x.dtype);
        let func = self
            .runtime
            .nvrtc_function(LAYERNORM_MODULE, LAYERNORM_SRC, entry)?;
        let cfg = self.runtime.reduction_launch_config(
            &func,
            groups_u,
            NORM_BLOCK,
            std::mem::size_of::<f32>() as u32,
        )?;
        let stream = self.runtime.stream();
        let mut builder = stream.launch_builder(&func);
        let scale_is_half = i32::from(scale.dtype == DataType::Float16);
        let bias_is_half = i32::from(bias.is_some_and(|bias| bias.dtype == DataType::Float16));
        let scale_is_bf16 = i32::from(scale.dtype == DataType::BFloat16);
        let bias_is_bf16 = i32::from(bias.is_some_and(|bias| bias.dtype == DataType::BFloat16));
        builder
            .arg(&x_ptr)
            .arg(&scale_ptr)
            .arg(&bias_ptr)
            .arg(&y_ptr)
            .arg(&mean_ptr)
            .arg(&invstd_ptr)
            .arg(&groups_i)
            .arg(&norm_i);
        match x.dtype {
            DataType::Float16 => {
                builder
                    .arg(&scale_is_half)
                    .arg(&bias_is_half)
                    .arg(&has_bias)
                    .arg(&eps);
            }
            DataType::BFloat16 => {
                builder
                    .arg(&scale_is_bf16)
                    .arg(&bias_is_bf16)
                    .arg(&has_bias)
                    .arg(&eps);
            }
            DataType::Float32 => {
                builder.arg(&has_bias).arg(&eps);
            }
            _ => unreachable!("LayerNormalization dtype validated above"),
        }
        // SAFETY: `func` is the compiled layernorm entry; the argument list and
        // ABI match its signature; every non-null pointer is a live device
        // allocation sized as validated above (X/Y: num_groups·norm_size;
        // scale/bias: norm_size; mean/invstd: num_groups).
        unsafe { builder.launch(cfg) }.map_err(|e| driver_err(&format!("launch {entry}"), e))?;
        if !capturing {
            *warmed_signature = Some(signature.clone());
        }
        self.last_call_capture_safe.store(true, Ordering::Relaxed);
        Ok(())
    }
}

impl Kernel for LayerNormKernel {
    fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.run(inputs, outputs)
    }
    fn supports_strided_input(&self, _idx: usize) -> bool {
        false
    }
    fn capture_support(&self) -> onnx_runtime_ep_api::CaptureSupport {
        if self.last_call_capture_safe.load(Ordering::Relaxed) {
            onnx_runtime_ep_api::CaptureSupport::Supported
        } else {
            onnx_runtime_ep_api::CaptureSupport::unsupported(
                "LayerNormalization shape/dtype signature does not match the warmed fixed-shape capture signature",
            )
        }
    }
}

// ─────────────────────── RMSNorm / SimplifiedLayerNorm ──────────────────────

/// Factory reading `axis` (default -1) and `epsilon` (default 1e-5).
pub struct RmsNormFactory {
    pub runtime: Arc<CudaRuntime>,
}

impl KernelFactory for RmsNormFactory {
    fn create(&self, node: &Node, _input_shapes: &[Vec<usize>]) -> Result<Box<dyn Kernel>> {
        if node
            .attr("stash_type")
            .is_some_and(|attribute| attribute.as_int() != Some(1))
        {
            return Err(EpError::KernelFailed(
                "RMSNormalization: stash_type must be 1 (float)".into(),
            ));
        }
        let axis = node.attr("axis").and_then(|a| a.as_int()).unwrap_or(-1);
        let epsilon = node
            .attr("epsilon")
            .and_then(|a| a.as_float())
            .unwrap_or(1e-5);
        Ok(Box::new(RmsNormKernel {
            axis,
            epsilon,
            runtime: self.runtime.clone(),
            warmed_signature: Mutex::new(None),
            last_call_capture_safe: AtomicBool::new(false),
        }))
    }
}

/// Fused f32/f16 RMSNormalization / SimplifiedLayerNormalization kernel.
#[derive(Debug)]
pub struct RmsNormKernel {
    axis: i64,
    epsilon: f32,
    runtime: Arc<CudaRuntime>,
    warmed_signature: Mutex<Option<NormCaptureSignature>>,
    last_call_capture_safe: AtomicBool,
}

impl RmsNormKernel {
    fn run(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.last_call_capture_safe.store(false, Ordering::Relaxed);
        let op = "RMSNormalization";
        if inputs.len() != 2 || outputs.is_empty() || outputs.len() > 2 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: expected 2 inputs (X, Scale) and 1-2 outputs \
                 (Y[, InvStdDev]), got {} and {}",
                inputs.len(),
                outputs.len()
            )));
        }
        let x = &inputs[0];
        let scale = &inputs[1];
        require_float_storage(op, "X", x.dtype)?;
        if x.dtype == DataType::Float32 {
            require_f32(op, "Scale", scale.dtype)?;
        } else {
            require_param_for_activation(op, "Scale", x.dtype, scale.dtype)?;
        }
        if outputs[0].dtype != x.dtype {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: Y dtype {:?} must match X dtype {:?}",
                outputs[0].dtype, x.dtype
            )));
        }
        require_contiguous(op, "X", x.is_contiguous())?;
        require_contiguous(op, "Scale", scale.is_contiguous())?;
        require_contiguous(op, "Y", outputs[0].is_contiguous())?;

        let rank = x.shape.len();
        let axis = resolve_axis(op, self.axis, rank)?;
        let norm_size: usize = x.shape[axis..].iter().product();
        let num_groups: usize = x.shape[..axis].iter().product();
        if norm_size == 0 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: empty normalization axis"
            )));
        }
        if scale.numel() != norm_size {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: Scale has {} elements, expected {norm_size}",
                scale.numel()
            )));
        }
        if outputs[0].shape != x.shape {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: Y shape {:?} must equal X shape {:?}",
                outputs[0].shape, x.shape
            )));
        }
        if num_groups == 0 {
            return Ok(());
        }
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let elements = x.numel() as u64;
            elements
                .saturating_mul(4)
                .saturating_add((num_groups as u64).saturating_mul(4))
        });

        let x_ptr = cuptr(x.data_ptr::<u8>() as *const c_void);
        let scale_ptr = cuptr(scale.data_ptr::<u8>() as *const c_void);
        let y_ptr = cuptr(outputs[0].data_ptr_mut::<u8>() as *const c_void);
        // Only one optional stat output (InvStdDev) for the simplified norm.
        let invstd_ptr = match outputs.get_mut(1) {
            None => 0u64,
            Some(t) => {
                require_f32(op, "InvStdDev", t.dtype)?;
                if t.numel() != num_groups {
                    return Err(EpError::KernelFailed(format!(
                        "cuda_ep {op}: InvStdDev has {} elements, expected {num_groups}",
                        t.numel()
                    )));
                }
                cuptr(t.data_ptr_mut::<u8>() as *const c_void)
            }
        };

        let (groups_u, norm_i) = (
            u32::try_from(num_groups).map_err(|_| dim_overflow(op, "num_groups", num_groups))?,
            i32::try_from(norm_size).map_err(|_| dim_overflow(op, "norm_size", norm_size))?,
        );
        let eps = self.epsilon;
        let signature = NormCaptureSignature::build(x.dtype, scale.dtype, None, x.shape, outputs);
        let capturing = self.runtime.is_capturing()?;
        let mut warmed_signature = self
            .warmed_signature
            .lock()
            .expect("cuda_ep RMSNormalization capture signature poisoned");
        if capturing && warmed_signature.as_ref() != Some(&signature) {
            return Err(EpError::KernelFailed(
                "cuda_ep RMSNormalization: dtype or shape changed during CUDA graph capture; warm the exact fixed-shape signature before capture"
                    .into(),
            ));
        }

        let entry = rmsnorm_entry(x.dtype);
        let func = self
            .runtime
            .nvrtc_function(RMSNORM_MODULE, RMSNORM_SRC, entry)?;
        let cfg = self.runtime.reduction_launch_config(
            &func,
            groups_u,
            NORM_BLOCK,
            std::mem::size_of::<f32>() as u32,
        )?;
        let stream = self.runtime.stream();
        let mut builder = stream.launch_builder(&func);
        let groups_i = groups_u_i32(groups_u);
        let scale_is_half = i32::from(scale.dtype == DataType::Float16);
        let scale_is_bf16 = i32::from(scale.dtype == DataType::BFloat16);
        builder
            .arg(&x_ptr)
            .arg(&scale_ptr)
            .arg(&y_ptr)
            .arg(&invstd_ptr)
            .arg(&groups_i)
            .arg(&norm_i);
        match x.dtype {
            DataType::Float16 => {
                builder.arg(&scale_is_half).arg(&eps);
            }
            DataType::BFloat16 => {
                builder.arg(&scale_is_bf16).arg(&eps);
            }
            DataType::Float32 => {
                builder.arg(&eps);
            }
            _ => unreachable!("RMSNormalization dtype validated above"),
        }
        // SAFETY: `func` is the compiled rmsnorm entry; the argument list/ABI
        // match; pointers are live device allocations sized as validated.
        unsafe { builder.launch(cfg) }.map_err(|e| driver_err(&format!("launch {entry}"), e))?;
        if !capturing {
            *warmed_signature = Some(signature.clone());
        }
        self.last_call_capture_safe.store(true, Ordering::Relaxed);
        Ok(())
    }
}

impl Kernel for RmsNormKernel {
    fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.run(inputs, outputs)
    }
    fn supports_strided_input(&self, _idx: usize) -> bool {
        false
    }
    fn capture_support(&self) -> onnx_runtime_ep_api::CaptureSupport {
        if self.last_call_capture_safe.load(Ordering::Relaxed) {
            onnx_runtime_ep_api::CaptureSupport::Supported
        } else {
            onnx_runtime_ep_api::CaptureSupport::unsupported(
                "SimplifiedLayerNormalization/RMSNorm shape/dtype signature does not match the warmed fixed-shape capture signature",
            )
        }
    }
}

// ───────────────────── SkipSimplifiedLayerNormalization ─────────────────────

/// Factory reading `epsilon` (default 1e-5) for the fused residual RMS norm.
pub struct SkipSimplifiedLayerNormFactory {
    pub runtime: Arc<CudaRuntime>,
}

impl KernelFactory for SkipSimplifiedLayerNormFactory {
    fn create(&self, node: &Node, _input_shapes: &[Vec<usize>]) -> Result<Box<dyn Kernel>> {
        let epsilon = node
            .attr("epsilon")
            .and_then(|a| a.as_float())
            .unwrap_or(1e-5);
        Ok(Box::new(SkipSimplifiedLayerNormKernel {
            epsilon,
            runtime: self.runtime.clone(),
            metadata: Mutex::new(SkipBroadcastMetadataCache::new(self.runtime.clone())),
            last_call_capture_safe: AtomicBool::new(false),
        }))
    }
}

/// Fused f32 `SkipSimplifiedLayerNormalization` kernel (`com.microsoft`).
#[derive(Debug)]
pub struct SkipSimplifiedLayerNormKernel {
    epsilon: f32,
    runtime: Arc<CudaRuntime>,
    metadata: Mutex<SkipBroadcastMetadataCache>,
    last_call_capture_safe: AtomicBool,
}

#[derive(Debug)]
struct SkipBroadcastMetadataCache {
    runtime: Arc<CudaRuntime>,
    ptr: CUdeviceptr,
    input_shape: Vec<usize>,
    skip_shape: Vec<usize>,
}

impl SkipBroadcastMetadataCache {
    fn new(runtime: Arc<CudaRuntime>) -> Self {
        Self {
            runtime,
            ptr: 0,
            input_shape: Vec::new(),
            skip_shape: Vec::new(),
        }
    }

    fn reserve(&mut self, input_shape: &[usize], skip_shape: &[usize]) -> Result<CUdeviceptr> {
        if self.ptr != 0 && self.input_shape == input_shape && self.skip_shape == skip_shape {
            return Ok(self.ptr);
        }
        if self.runtime.is_capturing()? {
            return Err(EpError::KernelFailed(
                "cuda_ep SkipSimplifiedLayerNormalization: broadcast metadata shape changed \
                 during CUDA graph capture; warm the fixed decode shape before capture"
                    .into(),
            ));
        }

        let metadata = skip_broadcast_metadata(input_shape, skip_shape);
        let metadata_bytes = u64_bytes(&metadata);
        let ptr = self.runtime.alloc_raw(metadata_bytes.len())?;
        // SAFETY: `ptr` exactly covers the metadata byte slice.
        if let Err(error) = unsafe { self.runtime.htod(metadata_bytes, ptr) } {
            // SAFETY: `ptr` is still exclusively owned and no launch used it.
            let _ = unsafe { self.runtime.free_raw(ptr) };
            return Err(error);
        }
        if self.ptr != 0 {
            // A dynamic shape change may replace metadata still referenced by
            // queued work. Fixed-shape decode always takes the cache-hit path.
            if let Err(error) = self.runtime.synchronize() {
                // SAFETY: `ptr` is still exclusively owned and has not escaped.
                let _ = unsafe { self.runtime.free_raw(ptr) };
                return Err(error);
            }
            // SAFETY: synchronization completed all prior users of `self.ptr`.
            if let Err(error) = unsafe { self.runtime.free_raw(self.ptr) } {
                // SAFETY: `ptr` is still exclusively owned and has not escaped.
                let _ = unsafe { self.runtime.free_raw(ptr) };
                return Err(error);
            }
        }
        self.ptr = ptr;
        self.input_shape.clear();
        self.input_shape.extend_from_slice(input_shape);
        self.skip_shape.clear();
        self.skip_shape.extend_from_slice(skip_shape);
        Ok(ptr)
    }
}

impl Drop for SkipBroadcastMetadataCache {
    fn drop(&mut self) {
        if self.ptr != 0 {
            let _ = self.runtime.synchronize();
            // SAFETY: this cache exclusively owns the persistent allocation.
            let _ = unsafe { self.runtime.free_raw(self.ptr) };
            self.ptr = 0;
        }
    }
}

impl SkipSimplifiedLayerNormKernel {
    fn run(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.last_call_capture_safe.store(false, Ordering::Relaxed);
        let op = "SkipSimplifiedLayerNormalization";
        if !(3..=4).contains(&inputs.len()) || outputs.is_empty() || outputs.len() > 4 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: expected 3-4 inputs (input, skip, gamma[, bias]) and 1-4 outputs, got {} and {}",
                inputs.len(),
                outputs.len()
            )));
        }
        let input = &inputs[0];
        let skip = &inputs[1];
        let gamma = &inputs[2];
        let bias = inputs.get(3).filter(|bias| !bias.is_absent());
        require_f16_or_f32(op, "input", input.dtype)?;
        let is_half = input.dtype == DataType::Float16;
        if skip.dtype != input.dtype {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: skip dtype {:?} must match input dtype {:?}",
                skip.dtype, input.dtype
            )));
        }
        if outputs[0].dtype != input.dtype {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: output dtype {:?} must match input dtype {:?}",
                outputs[0].dtype, input.dtype
            )));
        }
        if is_half {
            require_f16_or_f32(op, "gamma", gamma.dtype)?;
        } else {
            require_f32(op, "gamma", gamma.dtype)?;
        }
        require_contiguous(op, "input", input.is_contiguous())?;
        require_contiguous(op, "skip", skip.is_contiguous())?;
        require_contiguous(op, "gamma", gamma.is_contiguous())?;
        require_contiguous(op, "output", outputs[0].is_contiguous())?;
        if is_half {
            self.runtime.require_nvrtc_half_headers(op)?;
        }

        let rank = input.shape.len();
        if rank == 0 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: input must have rank >= 1"
            )));
        }
        let norm_size = input.shape[rank - 1];
        let num_groups: usize = input.shape[..rank - 1].iter().product();
        if norm_size == 0 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: empty hidden (last) dimension"
            )));
        }
        if gamma.shape != [norm_size] {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: gamma shape {:?} must equal [{norm_size}]",
                gamma.shape
            )));
        }
        let bias_ptr = optional_norm_vec_ptr(op, "bias", bias, norm_size, is_half)?;
        let broadcast =
            onnx_runtime_ir::broadcast_shapes(input.shape, skip.shape).map_err(EpError::Ir)?;
        if broadcast != input.shape {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: skip shape {:?} is not broadcastable to input shape {:?}",
                skip.shape, input.shape
            )));
        }
        if outputs[0].shape != input.shape {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: output shape {:?} must equal input shape {:?}",
                outputs[0].shape, input.shape
            )));
        }
        if num_groups == 0 {
            return Ok(());
        }
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let elements = input.numel() as u64;
            let groups = num_groups as u64;
            let mut flops = elements
                .saturating_mul(5)
                .saturating_add(groups.saturating_mul(4));
            if bias.is_some() {
                flops = flops.saturating_add(elements);
            }
            flops
        });

        // Optional Mean/InvStdDev stat outputs may be f16 in a half graph (they
        // are typically unused). Track their precision so the kernel narrows.
        let gamma_is_half = i32::from(gamma.dtype == DataType::Float16);
        let bias_is_half = i32::from(bias.is_some_and(|b| b.dtype == DataType::Float16));
        let (mean_ptr, invstd_ptr, stat_is_half) = if is_half {
            let mean = optional_half_stat_ptr(op, "Mean", outputs, 1, num_groups)?;
            let invstd = optional_half_stat_ptr(op, "InvStdDev", outputs, 2, num_groups)?;
            let stat_half = i32::from(
                outputs.get(1).is_some_and(|t| t.dtype == DataType::Float16)
                    || outputs.get(2).is_some_and(|t| t.dtype == DataType::Float16),
            );
            (mean, invstd, stat_half)
        } else {
            let (mean, invstd) = optional_stat_ptrs(op, outputs, num_groups)?;
            (mean, invstd, 0)
        };
        let sum_ptr = match outputs.get_mut(3) {
            None => 0u64,
            Some(t) => {
                if t.dtype != input.dtype {
                    return Err(EpError::KernelFailed(format!(
                        "cuda_ep {op}: input_skip_bias_sum dtype {:?} must match input dtype {:?}",
                        t.dtype, input.dtype
                    )));
                }
                if t.shape != input.shape {
                    return Err(EpError::KernelFailed(format!(
                        "cuda_ep {op}: input_skip_bias_sum shape {:?} must equal input shape {:?}",
                        t.shape, input.shape
                    )));
                }
                cuptr(t.data_ptr_mut::<u8>() as *const c_void)
            }
        };
        let (groups_u, norm_i) = (
            u32::try_from(num_groups).map_err(|_| dim_overflow(op, "num_groups", num_groups))?,
            i32::try_from(norm_size).map_err(|_| dim_overflow(op, "norm_size", norm_size))?,
        );
        let rank_i = i32::try_from(rank).map_err(|_| dim_overflow(op, "rank", rank))?;
        let has_bias = i32::from(bias_ptr != 0);
        let input_ptr = cuptr(input.data_ptr::<u8>() as *const c_void);
        let skip_ptr = cuptr(skip.data_ptr::<u8>() as *const c_void);
        let gamma_ptr = cuptr(gamma.data_ptr::<u8>() as *const c_void);
        let y_ptr = cuptr(outputs[0].data_ptr_mut::<u8>() as *const c_void);
        let mut metadata = self
            .metadata
            .lock()
            .expect("cuda_ep skip normalization metadata cache poisoned");
        let metadata_ptr = metadata.reserve(input.shape, skip.shape)?;
        let dense_skip = i32::from(skip.numel() == input.numel());
        let selection = select_skip_rmsnorm_variant(
            is_half,
            dense_skip != 0,
            norm_size,
            bias_ptr != 0,
            gamma_is_half != 0,
        );
        let variant_name = match selection.variant {
            SkipRmsnormVariant::F32Dense => "skip_rmsnorm_f32_dense",
            SkipRmsnormVariant::F32 => "skip_rmsnorm_f32",
            SkipRmsnormVariant::F16Generic => "skip_rmsnorm_f16_generic",
            SkipRmsnormVariant::F16WarpHalf4 => "skip_rmsnorm_f16_warp_half4",
        };
        onnx_runtime_ep_api::record_kernel_variant!(
            variant_name,
            "SkipSimplifiedLayerNormalization hidden={norm_size}: {}",
            selection.reason
        );
        let func =
            self.runtime
                .nvrtc_function(SKIP_RMSNORM_MODULE, SKIP_RMSNORM_SRC, selection.entry)?;
        let stream = self.runtime.stream();
        let mut builder = stream.launch_builder(&func);
        let groups_i = groups_u_i32(groups_u);
        builder
            .arg(&input_ptr)
            .arg(&skip_ptr)
            .arg(&gamma_ptr)
            .arg(&bias_ptr)
            .arg(&y_ptr)
            .arg(&sum_ptr)
            .arg(&mean_ptr)
            .arg(&invstd_ptr)
            .arg(&metadata_ptr)
            .arg(&rank_i)
            .arg(&groups_i)
            .arg(&norm_i)
            .arg(&has_bias);
        if is_half {
            builder
                .arg(&dense_skip)
                .arg(&gamma_is_half)
                .arg(&bias_is_half)
                .arg(&stat_is_half)
                .arg(&self.epsilon);
        } else {
            builder.arg(&self.epsilon);
        }
        // SAFETY: all pointers reference validated device buffers; metadata has
        // two rank-length u64 arrays describing the output shape and skip strides.
        let cfg = if is_half {
            LaunchConfig {
                grid_dim: (groups_u, 1, 1),
                block_dim: (32, 1, 1),
                shared_mem_bytes: 0,
            }
        } else {
            let preferred_threads = preferred_norm_block_threads(
                norm_size,
                self.runtime.capabilities().max_threads_per_block(),
            );
            self.runtime.reduction_launch_config(
                &func,
                groups_u,
                preferred_threads,
                std::mem::size_of::<f32>() as u32,
            )?
        };
        unsafe { builder.launch(cfg) }
            .map_err(|e| driver_err(&format!("launch {}", selection.entry), e))?;
        // Unlike the plain RMS/LayerNorm kernels, this fused residual norm is
        // kept single-group for capture on purpose. It normalizes the hidden
        // (last) axis per token, so decode — the only phase that captures — is
        // always num_groups == 1; a fixed multi-group shape would only ever
        // arise in the uncaptured prefill. Its capture drift is guarded by the
        // shape-keyed `SkipBroadcastMetadataCache` (which rejects a shape change
        // mid-capture) rather than a dtype-encoding `NormCaptureSignature`, so
        // admitting multi-group here would broaden capture with no decode
        // benefit and weaker drift detection. Left conservative by design.
        self.last_call_capture_safe
            .store(num_groups == 1, Ordering::Relaxed);
        Ok(())
    }
}

impl Kernel for SkipSimplifiedLayerNormKernel {
    fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.run(inputs, outputs)
    }
    fn supports_strided_input(&self, _idx: usize) -> bool {
        false
    }
    fn capture_support(&self) -> onnx_runtime_ep_api::CaptureSupport {
        if self.last_call_capture_safe.load(Ordering::Relaxed) {
            onnx_runtime_ep_api::CaptureSupport::Supported
        } else {
            onnx_runtime_ep_api::CaptureSupport::unsupported(
                "SkipSimplifiedLayerNormalization shape/dtype signature does not match the warmed single-group capture signature",
            )
        }
    }
}

// ─────────────────────────── SkipLayerNormalization ─────────────────────────

/// Factory reading `epsilon` (default 1e-5). SkipLayerNorm always normalizes the
/// last dimension (hidden size), so it takes no `axis`.
pub struct SkipLayerNormFactory {
    pub runtime: Arc<CudaRuntime>,
}

impl KernelFactory for SkipLayerNormFactory {
    fn create(&self, node: &Node, _input_shapes: &[Vec<usize>]) -> Result<Box<dyn Kernel>> {
        let epsilon = node
            .attr("epsilon")
            .and_then(|a| a.as_float())
            .unwrap_or(1e-5);
        Ok(Box::new(SkipLayerNormKernel {
            epsilon,
            runtime: self.runtime.clone(),
            last_call_capture_safe: AtomicBool::new(false),
        }))
    }
}

/// Fused f32 SkipLayerNormalization kernel (`com.microsoft`).
///
/// Inputs: `input`, `skip`, `gamma`, optional `beta`, optional `bias`.
/// Outputs: `output`, optional `mean`, optional `inv_std_var`, optional
/// `input_skip_bias_sum` (positional slots 1..=3).
#[derive(Debug)]
pub struct SkipLayerNormKernel {
    epsilon: f32,
    runtime: Arc<CudaRuntime>,
    last_call_capture_safe: AtomicBool,
}

impl SkipLayerNormKernel {
    fn run(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.last_call_capture_safe.store(false, Ordering::Relaxed);
        let op = "SkipLayerNormalization";
        if !(3..=5).contains(&inputs.len()) || outputs.is_empty() || outputs.len() > 4 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: expected 3-5 inputs (input, skip, gamma[, beta][, bias]) \
                 and 1-4 outputs, got {} and {}",
                inputs.len(),
                outputs.len()
            )));
        }
        let input = &inputs[0];
        let skip = &inputs[1];
        let gamma = &inputs[2];
        let beta = inputs.get(3);
        let bias = inputs.get(4);
        require_f32(op, "input", input.dtype)?;
        require_f32(op, "skip", skip.dtype)?;
        require_f32(op, "gamma", gamma.dtype)?;
        require_f32(op, "output", outputs[0].dtype)?;
        require_contiguous(op, "input", input.is_contiguous())?;
        require_contiguous(op, "skip", skip.is_contiguous())?;
        require_contiguous(op, "gamma", gamma.is_contiguous())?;
        require_contiguous(op, "output", outputs[0].is_contiguous())?;

        let rank = input.shape.len();
        if rank == 0 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: input must have rank >= 1"
            )));
        }
        if skip.shape != input.shape {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: skip shape {:?} must equal input shape {:?}",
                skip.shape, input.shape
            )));
        }
        let norm_size = input.shape[rank - 1];
        let num_groups: usize = input.shape[..rank - 1].iter().product();
        if norm_size == 0 {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: empty hidden (last) dimension"
            )));
        }
        if gamma.numel() != norm_size {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: gamma has {} elements, expected {norm_size} (hidden size)",
                gamma.numel()
            )));
        }
        let beta_ptr = optional_vec_ptr(op, "beta", beta, norm_size)?;
        let bias_ptr = optional_vec_ptr(op, "bias", bias, norm_size)?;
        if outputs[0].shape != input.shape {
            return Err(EpError::KernelFailed(format!(
                "cuda_ep {op}: output shape {:?} must equal input shape {:?}",
                outputs[0].shape, input.shape
            )));
        }
        if num_groups == 0 {
            return Ok(());
        }
        crate::trace::record_kernel_metrics(inputs, outputs, || {
            let elements = input.numel() as u64;
            let groups = num_groups as u64;
            let mut flops = elements
                .saturating_mul(8)
                .saturating_add(groups.saturating_mul(5));
            if beta_ptr != 0 {
                flops = flops.saturating_add(elements);
            }
            if bias_ptr != 0 {
                flops = flops.saturating_add(elements);
            }
            flops
        });

        let input_ptr = cuptr(input.data_ptr::<u8>() as *const c_void);
        let skip_ptr = cuptr(skip.data_ptr::<u8>() as *const c_void);
        let gamma_ptr = cuptr(gamma.data_ptr::<u8>() as *const c_void);
        let y_ptr = cuptr(outputs[0].data_ptr_mut::<u8>() as *const c_void);

        // Optional outputs: mean (slot 1), inv_std_var (slot 2) — length
        // num_groups; input_skip_bias_sum (slot 3) — length input.numel().
        let (mean_ptr, invstd_ptr) = optional_stat_ptrs(op, outputs, num_groups)?;
        let sum_ptr = match outputs.get_mut(3) {
            None => 0u64,
            Some(t) => {
                require_f32(op, "input_skip_bias_sum", t.dtype)?;
                if t.numel() != input.numel() {
                    return Err(EpError::KernelFailed(format!(
                        "cuda_ep {op}: input_skip_bias_sum has {} elements, expected {}",
                        t.numel(),
                        input.numel()
                    )));
                }
                cuptr(t.data_ptr_mut::<u8>() as *const c_void)
            }
        };

        let (groups_u, norm_i) = (
            u32::try_from(num_groups).map_err(|_| dim_overflow(op, "num_groups", num_groups))?,
            i32::try_from(norm_size).map_err(|_| dim_overflow(op, "norm_size", norm_size))?,
        );
        let has_beta: i32 = i32::from(beta_ptr != 0);
        let has_bias: i32 = i32::from(bias_ptr != 0);
        let eps = self.epsilon;

        let func = self.runtime.nvrtc_function(
            SKIP_LAYERNORM_MODULE,
            SKIP_LAYERNORM_SRC,
            "skip_layernorm_f32",
        )?;
        let cfg = self.runtime.reduction_launch_config(
            &func,
            groups_u,
            NORM_BLOCK,
            std::mem::size_of::<f32>() as u32,
        )?;
        let stream = self.runtime.stream();
        let mut builder = stream.launch_builder(&func);
        let groups_i = groups_u_i32(groups_u);
        builder
            .arg(&input_ptr)
            .arg(&skip_ptr)
            .arg(&gamma_ptr)
            .arg(&beta_ptr)
            .arg(&bias_ptr)
            .arg(&y_ptr)
            .arg(&sum_ptr)
            .arg(&mean_ptr)
            .arg(&invstd_ptr)
            .arg(&groups_i)
            .arg(&norm_i)
            .arg(&has_beta)
            .arg(&has_bias)
            .arg(&eps);
        // SAFETY: `func` is the compiled skip-layernorm entry; argument list/ABI
        // match; each non-null pointer is a live device allocation sized as
        // validated (input/skip/output/sum: num_groups·norm_size; gamma/beta/
        // bias: norm_size; mean/invstd: num_groups).
        unsafe { builder.launch(cfg) }.map_err(|e| driver_err("launch skip_layernorm_f32", e))?;
        // Kept single-group for capture on purpose: SkipLayerNorm normalizes the
        // hidden (last) axis per token, so the only captured phase (decode) is
        // always num_groups == 1 and a multi-group shape arises solely in the
        // uncaptured prefill. This kernel also carries no `NormCaptureSignature`
        // drift guard at all, so generalizing it would admit multi-group capture
        // with neither a decode benefit nor dtype/shape drift detection. Left
        // conservative by design.
        self.last_call_capture_safe
            .store(num_groups == 1, Ordering::Relaxed);
        Ok(())
    }
}

impl Kernel for SkipLayerNormKernel {
    fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> {
        self.run(inputs, outputs)
    }
    fn supports_strided_input(&self, _idx: usize) -> bool {
        false
    }
    fn capture_support(&self) -> onnx_runtime_ep_api::CaptureSupport {
        if self.last_call_capture_safe.load(Ordering::Relaxed) {
            onnx_runtime_ep_api::CaptureSupport::Supported
        } else {
            onnx_runtime_ep_api::CaptureSupport::unsupported(
                "SkipLayerNormalization shape/dtype signature does not match the warmed single-group capture signature",
            )
        }
    }
}

// ───────────────────────────────── helpers ─────────────────────────────────

/// The kernels take `num_groups` as a signed `int`; convert the validated `u32`.
fn groups_u_i32(groups: u32) -> i32 {
    groups as i32
}

/// Resolve the optional per-group `Mean` (output slot 1) and `InvStdDev` (slot 2)
/// device pointers, validating f32 dtype and `num_groups` length when present.
fn skip_broadcast_metadata(input: &[usize], skip: &[usize]) -> Vec<u64> {
    let mut metadata = input.iter().map(|&dim| dim as u64).collect::<Vec<_>>();
    let contiguous = onnx_runtime_ir::compute_contiguous_strides(skip);
    let leading = input.len() - skip.len();
    metadata.extend((0..input.len()).map(|axis| {
        if axis < leading || skip[axis - leading] == 1 {
            0
        } else {
            contiguous[axis - leading] as u64
        }
    }));
    metadata
}

fn u64_bytes(values: &[u64]) -> &[u8] {
    // SAFETY: u64 is plain data and the byte slice retains the input lifetime.
    unsafe {
        std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
    }
}

fn optional_stat_ptrs(
    op: &str,
    outputs: &mut [TensorMut],
    num_groups: usize,
) -> Result<(CUdeviceptr, CUdeviceptr)> {
    let mean = optional_out_ptr(op, "Mean", outputs, 1, num_groups)?;
    let invstd = optional_out_ptr(op, "InvStdDev", outputs, 2, num_groups)?;
    Ok((mean, invstd))
}

fn optional_out_ptr(
    op: &str,
    name: &str,
    outputs: &mut [TensorMut],
    idx: usize,
    expect: usize,
) -> Result<CUdeviceptr> {
    match outputs.get_mut(idx) {
        None => Ok(0),
        Some(t) => {
            require_f32(op, name, t.dtype)?;
            if t.numel() != expect {
                return Err(EpError::KernelFailed(format!(
                    "cuda_ep {op}: {name} has {} elements, expected {expect}",
                    t.numel()
                )));
            }
            Ok(cuptr(t.data_ptr_mut::<u8>() as *const c_void))
        }
    }
}

/// Resolve an optional length-`expect` input vector (f32, contiguous) to a
/// device pointer, or 0 when absent.
fn optional_vec_ptr(
    op: &str,
    name: &str,
    t: Option<&TensorView>,
    expect: usize,
) -> Result<CUdeviceptr> {
    match t {
        None => Ok(0),
        Some(v) => {
            require_f32(op, name, v.dtype)?;
            require_contiguous(op, name, v.is_contiguous())?;
            if v.numel() != expect {
                return Err(EpError::KernelFailed(format!(
                    "cuda_ep {op}: {name} has {} elements, expected {expect}",
                    v.numel()
                )));
            }
            Ok(cuptr(v.data_ptr::<u8>() as *const c_void))
        }
    }
}

/// Optional length-`expect` input vector accepting either f16 or f32 (used by
/// the half normalization paths, which pass a per-tensor `*_is_half` flag).
fn optional_norm_vec_ptr(
    op: &str,
    name: &str,
    t: Option<&TensorView>,
    expect: usize,
    allow_half: bool,
) -> Result<CUdeviceptr> {
    match t {
        None => Ok(0),
        Some(v) => {
            if allow_half {
                require_f16_or_f32(op, name, v.dtype)?;
            } else {
                require_f32(op, name, v.dtype)?;
            }
            require_contiguous(op, name, v.is_contiguous())?;
            if v.numel() != expect {
                return Err(EpError::KernelFailed(format!(
                    "cuda_ep {op}: {name} has {} elements, expected {expect}",
                    v.numel()
                )));
            }
            Ok(cuptr(v.data_ptr::<u8>() as *const c_void))
        }
    }
}

/// Optional per-group stat output (Mean/InvStdDev) accepting f16 or f32. Half
/// graphs frequently declare these unused outputs in the model's activation
/// dtype; the kernel narrows the stat write to match.
fn optional_half_stat_ptr(
    op: &str,
    name: &str,
    outputs: &mut [TensorMut],
    idx: usize,
    expect: usize,
) -> Result<CUdeviceptr> {
    match outputs.get_mut(idx) {
        None => Ok(0),
        Some(t) => {
            require_f16_or_f32(op, name, t.dtype)?;
            if t.numel() != expect {
                return Err(EpError::KernelFailed(format!(
                    "cuda_ep {op}: {name} has {} elements, expected {expect}",
                    t.numel()
                )));
            }
            Ok(cuptr(t.data_ptr_mut::<u8>() as *const c_void))
        }
    }
}

#[cfg(test)]
mod tests {
    use half::{bf16, f16};
    use onnx_runtime_ep_api::{DevicePtr, DevicePtrMut, ExecutionProvider};
    use onnx_runtime_ir::compute_contiguous_strides;

    use super::*;
    use crate::CudaExecutionProvider;

    #[test]
    fn sources_expose_their_entry_points() {
        assert!(LAYERNORM_SRC.contains("layernorm_f32"));
        assert!(LAYERNORM_SRC.contains("layernorm_f16"));
        assert!(LAYERNORM_SRC.contains("layernorm_bf16"));
        assert!(RMSNORM_SRC.contains("rmsnorm_f32"));
        assert!(RMSNORM_SRC.contains("rmsnorm_f16"));
        assert!(RMSNORM_SRC.contains("rmsnorm_bf16"));
        assert!(SKIP_LAYERNORM_SRC.contains("skip_layernorm_f32"));
        assert!(SKIP_RMSNORM_SRC.contains("skip_rmsnorm_f32"));
        assert!(SKIP_RMSNORM_SRC.contains("skip_rmsnorm_f32_dense"));
        assert!(SKIP_RMSNORM_SRC.contains("skip_rmsnorm_f16"));
        assert!(SKIP_RMSNORM_SRC.contains("skip_rmsnorm_f16_warp_half4"));
    }

    #[test]
    fn norm_dispatch_preserves_existing_entries_and_adds_bf16() {
        assert_eq!(layernorm_entry(DataType::Float16), "layernorm_f16");
        assert_eq!(layernorm_entry(DataType::Float32), "layernorm_f32");
        assert_eq!(layernorm_entry(DataType::BFloat16), "layernorm_bf16");
        assert_eq!(rmsnorm_entry(DataType::Float16), "rmsnorm_f16");
        assert_eq!(rmsnorm_entry(DataType::Float32), "rmsnorm_f32");
        assert_eq!(rmsnorm_entry(DataType::BFloat16), "rmsnorm_bf16");
    }

    #[test]
    fn norm_block_width_respects_shape_and_device_limit() {
        assert_eq!(preferred_norm_block_threads(3584, 1024), 256);
        assert_eq!(preferred_norm_block_threads(96, 1024), 128);
        assert_eq!(preferred_norm_block_threads(3584, 128), 128);
        assert_eq!(preferred_norm_block_threads(17, 1024), 32);
    }

    fn skip_rmsnorm_residuals(hidden: usize) -> (Vec<f16>, Vec<f16>) {
        let residual = (0..hidden)
            .map(|index| {
                let input = f16::from_f32(((index * 37 % 101) as f32 - 50.0) / 31.0);
                let skip = f16::from_f32(((index * 17 % 67) as f32 - 33.0) / 47.0);
                let bias = f16::from_f32(((index * 11 % 29) as f32 - 14.0) / 113.0);
                f16::from_f32(input.to_f32() + skip.to_f32() + bias.to_f32())
            })
            .collect();
        let gamma = (0..hidden)
            .map(|index| f16::from_f32(0.75 + (index * 13 % 41) as f32 / 64.0))
            .collect();
        (residual, gamma)
    }

    fn normalize_f16(residual: &[f16], gamma: &[f16], sum_squares: f32) -> Vec<f16> {
        let inv_std = 1.0 / (sum_squares / residual.len() as f32 + 1e-5).sqrt();
        residual
            .iter()
            .zip(gamma)
            .map(|(residual, gamma)| f16::from_f32(residual.to_f32() * inv_std * gamma.to_f32()))
            .collect()
    }

    fn previous_shared_tree_skip_rmsnorm(residual: &[f16], gamma: &[f16]) -> Vec<f16> {
        let mut lanes = [0.0f32; NORM_BLOCK as usize];
        for (lane, sum) in lanes.iter_mut().enumerate() {
            for value in residual.iter().skip(lane).step_by(NORM_BLOCK as usize) {
                let value = value.to_f32();
                *sum += value * value;
            }
        }
        let mut offset = lanes.len() / 2;
        while offset > 0 {
            for lane in 0..offset {
                lanes[lane] += lanes[lane + offset];
            }
            offset /= 2;
        }
        normalize_f16(residual, gamma, lanes[0])
    }

    fn generic_warp_shuffle_skip_rmsnorm(residual: &[f16], gamma: &[f16]) -> Vec<f16> {
        let mut lanes = [0.0f32; 32];
        let pairs = residual.len() / 2;
        for (lane, sum) in lanes.iter_mut().enumerate() {
            for pair in (lane..pairs).step_by(32) {
                let first = residual[pair * 2].to_f32();
                let second = residual[pair * 2 + 1].to_f32();
                *sum += first * first;
                *sum += second * second;
            }
        }
        if residual.len() % 2 != 0 {
            let tail = residual[residual.len() - 1].to_f32();
            lanes[0] += tail * tail;
        }
        let mut offset = 16;
        while offset > 0 {
            let previous = lanes;
            for lane in 0..(32 - offset) {
                lanes[lane] += previous[lane + offset];
            }
            offset /= 2;
        }
        normalize_f16(residual, gamma, lanes[0])
    }

    fn half4_warp_skip_rmsnorm(residual: &[f16], gamma: &[f16]) -> Vec<f16> {
        assert!(
            residual
                .len()
                .is_multiple_of(SKIP_RMSNORM_WARP_HALF4_MULTIPLE)
        );
        let mut lanes = [0.0f32; 32];
        let chunks_per_lane = residual.len() / SKIP_RMSNORM_WARP_HALF4_MULTIPLE;
        for (lane, sum) in lanes.iter_mut().enumerate() {
            let mut ss0 = 0.0f32;
            let mut ss1 = 0.0f32;
            let mut ss2 = 0.0f32;
            let mut ss3 = 0.0f32;
            for item in 0..chunks_per_lane {
                let base = (lane + item * 32) * 4;
                let value0 = residual[base].to_f32();
                let value1 = residual[base + 1].to_f32();
                let value2 = residual[base + 2].to_f32();
                let value3 = residual[base + 3].to_f32();
                ss0 += value0 * value0;
                ss1 += value1 * value1;
                ss2 += value2 * value2;
                ss3 += value3 * value3;
            }
            *sum = (ss0 + ss1) + (ss2 + ss3);
        }
        let mut offset = 16;
        while offset > 0 {
            let previous = lanes;
            for lane in 0..(32 - offset) {
                lanes[lane] += previous[lane + offset];
            }
            offset /= 2;
        }
        normalize_f16(residual, gamma, lanes[0])
    }

    fn fixed_seven_half4_warp_skip_rmsnorm(residual: &[f16; 896], gamma: &[f16; 896]) -> Vec<f16> {
        let mut lanes = [0.0f32; 32];
        for (lane, sum) in lanes.iter_mut().enumerate() {
            let mut ss0 = 0.0f32;
            let mut ss1 = 0.0f32;
            let mut ss2 = 0.0f32;
            let mut ss3 = 0.0f32;
            for item in 0..7 {
                let base = (lane + item * 32) * 4;
                let value0 = residual[base].to_f32();
                let value1 = residual[base + 1].to_f32();
                let value2 = residual[base + 2].to_f32();
                let value3 = residual[base + 3].to_f32();
                ss0 += value0 * value0;
                ss1 += value1 * value1;
                ss2 += value2 * value2;
                ss3 += value3 * value3;
            }
            *sum = (ss0 + ss1) + (ss2 + ss3);
        }
        let mut offset = 16;
        while offset > 0 {
            let previous = lanes;
            for lane in 0..(32 - offset) {
                lanes[lane] += previous[lane + offset];
            }
            offset /= 2;
        }
        normalize_f16(residual, gamma, lanes[0])
    }

    #[test]
    fn warp_shuffle_skip_rmsnorm_matches_shared_tree_for_hidden_and_tail_sizes() {
        for hidden in [896, 1024, 2048, 4096, 5120] {
            let (residual, gamma) = skip_rmsnorm_residuals(hidden);
            let previous = previous_shared_tree_skip_rmsnorm(&residual, &gamma);
            let warp = half4_warp_skip_rmsnorm(&residual, &gamma);
            let max_error = previous
                .iter()
                .zip(&warp)
                .map(|(previous, warp)| (previous.to_f32() - warp.to_f32()).abs())
                .fold(0.0f32, f32::max);
            assert!(
                max_error <= 2.0e-3,
                "hidden={hidden} shared-tree/warp max fp16 error {max_error}"
            );
        }

        let hidden = 900;
        let (residual, gamma) = skip_rmsnorm_residuals(hidden);
        let previous = previous_shared_tree_skip_rmsnorm(&residual, &gamma);
        let generic = generic_warp_shuffle_skip_rmsnorm(&residual, &gamma);
        let max_error = previous
            .iter()
            .zip(&generic)
            .map(|(previous, generic)| (previous.to_f32() - generic.to_f32()).abs())
            .fold(0.0f32, f32::max);
        assert!(
            max_error <= 2.0e-3,
            "hidden={hidden} shared-tree/generic max fp16 error {max_error}"
        );
    }

    #[test]
    fn fp16_skip_rmsnorm_warp_selection_is_structural() {
        for hidden in [128, 256, 512, 896, 1024, 2048, 4096, 5120] {
            let selection = select_skip_rmsnorm_variant(true, true, hidden, false, true);
            assert_eq!(
                selection.variant,
                SkipRmsnormVariant::F16WarpHalf4,
                "hidden={hidden}: {}",
                selection.reason
            );
            assert!(selection.reason.contains("hidden%128==0"));
        }

        let tail = select_skip_rmsnorm_variant(true, true, 900, false, true);
        assert_eq!(tail.variant, SkipRmsnormVariant::F16Generic);
        assert!(tail.reason.contains("hidden%128==0"));
    }

    #[test]
    fn generalized_half4_warp_is_bit_identical_for_hidden_896() {
        let (residual, gamma) = skip_rmsnorm_residuals(896);
        let residual: [f16; 896] = residual.try_into().unwrap();
        let gamma: [f16; 896] = gamma.try_into().unwrap();
        let fixed = fixed_seven_half4_warp_skip_rmsnorm(&residual, &gamma);
        let generalized = half4_warp_skip_rmsnorm(&residual, &gamma);
        assert_eq!(
            fixed
                .iter()
                .map(|value| value.to_bits())
                .collect::<Vec<_>>(),
            generalized
                .iter()
                .map(|value| value.to_bits())
                .collect::<Vec<_>>()
        );
    }

    fn f16_bytes(values: &[f16]) -> &[u8] {
        // SAFETY: f16 is plain two-byte data and the byte slice retains the input lifetime.
        unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
        }
    }

    fn run_fp16_skip_rmsnorm_gpu(
        ep: &CudaExecutionProvider,
        hidden: usize,
    ) -> (Vec<f16>, Vec<f16>, Vec<f16>) {
        let shape = [1, hidden];
        let strides = compute_contiguous_strides(&shape);
        let gamma_shape = [hidden];
        let gamma_strides = compute_contiguous_strides(&gamma_shape);
        let input = (0..hidden)
            .map(|index| f16::from_f32(((index * 37 % 101) as f32 - 50.0) / 31.0))
            .collect::<Vec<_>>();
        let skip = (0..hidden)
            .map(|index| f16::from_f32(((index * 17 % 67) as f32 - 33.0) / 47.0))
            .collect::<Vec<_>>();
        let gamma = (0..hidden)
            .map(|index| f16::from_f32(0.75 + (index * 13 % 41) as f32 / 64.0))
            .collect::<Vec<_>>();
        let residual = input
            .iter()
            .zip(&skip)
            .map(|(input, skip)| f16::from_f32(input.to_f32() + skip.to_f32()))
            .collect::<Vec<_>>();

        let input_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let skip_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let gamma_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let mut output_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let runtime = ep.runtime();
        unsafe {
            runtime
                .htod(f16_bytes(&input), cuptr(input_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(f16_bytes(&skip), cuptr(skip_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(f16_bytes(&gamma), cuptr(gamma_buffer.as_ptr()))
                .unwrap();
        }

        {
            let inputs = [
                TensorView::new(
                    DevicePtr(input_buffer.as_ptr()),
                    DataType::Float16,
                    &shape,
                    &strides,
                    ep.device_id(),
                ),
                TensorView::new(
                    DevicePtr(skip_buffer.as_ptr()),
                    DataType::Float16,
                    &shape,
                    &strides,
                    ep.device_id(),
                ),
                TensorView::new(
                    DevicePtr(gamma_buffer.as_ptr()),
                    DataType::Float16,
                    &gamma_shape,
                    &gamma_strides,
                    ep.device_id(),
                ),
            ];
            let output = TensorMut::new(
                DevicePtrMut(output_buffer.as_mut_ptr()),
                DataType::Float16,
                &shape,
                &strides,
                ep.device_id(),
            );
            let kernel = SkipSimplifiedLayerNormKernel {
                epsilon: 1e-5,
                runtime: runtime.clone(),
                metadata: Mutex::new(SkipBroadcastMetadataCache::new(runtime.clone())),
                last_call_capture_safe: AtomicBool::new(false),
            };
            kernel.run(&inputs, &mut [output]).unwrap();
        }

        let mut output_bytes = vec![0u8; hidden * std::mem::size_of::<f16>()];
        unsafe {
            runtime
                .dtoh(&mut output_bytes, cuptr(output_buffer.as_ptr()))
                .unwrap();
        }
        let output = output_bytes
            .chunks_exact(2)
            .map(|raw| f16::from_bits(u16::from_ne_bytes(raw.try_into().unwrap())))
            .collect();
        ep.deallocate(input_buffer).unwrap();
        ep.deallocate(skip_buffer).unwrap();
        ep.deallocate(gamma_buffer).unwrap();
        ep.deallocate(output_buffer).unwrap();
        (output, residual, gamma)
    }

    fn f32_bytes(values: &[f32]) -> &[u8] {
        // SAFETY: f32 is plain-old-data; reinterpreting as bytes is sound.
        unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
        }
    }

    #[test]
    fn fp32_dense_skip_rmsnorm_matches_reference_and_optional_outputs() {
        let Ok(ep) = CudaExecutionProvider::new(0) else {
            eprintln!("skipping fp32 dense skip RMSNorm test: CUDA unavailable");
            return;
        };
        let hidden = 3584usize;
        let shape = [1, hidden];
        let strides = compute_contiguous_strides(&shape);
        let gamma_shape = [hidden];
        let gamma_strides = compute_contiguous_strides(&gamma_shape);
        let stat_shape = [1usize];
        let stat_strides = [1i64];
        let input = (0..hidden)
            .map(|index| ((index * 37 % 101) as f32 - 50.0) / 31.0)
            .collect::<Vec<_>>();
        let skip = (0..hidden)
            .map(|index| ((index * 17 % 67) as f32 - 33.0) / 47.0)
            .collect::<Vec<_>>();
        let gamma = (0..hidden)
            .map(|index| 0.75 + (index * 13 % 41) as f32 / 64.0)
            .collect::<Vec<_>>();
        let residual = input
            .iter()
            .zip(&skip)
            .map(|(input, skip)| input + skip)
            .collect::<Vec<_>>();
        let sum_squares = residual.iter().fold(0.0f64, |sum, value| {
            sum + f64::from(*value) * f64::from(*value)
        });
        let inverse_standard_deviation =
            (sum_squares / hidden as f64 + 1e-5f64).sqrt().recip() as f32;

        let allocate = |elements: usize| {
            ep.allocate(elements * std::mem::size_of::<f32>(), 256)
                .unwrap()
        };
        let input_buffer = allocate(hidden);
        let skip_buffer = allocate(hidden);
        let gamma_buffer = allocate(hidden);
        let mut output_buffer = allocate(hidden);
        let mut mean_buffer = allocate(1);
        let mut inverse_standard_deviation_buffer = allocate(1);
        let mut sum_buffer = allocate(hidden);
        let runtime = ep.runtime();
        unsafe {
            runtime
                .htod(f32_bytes(&input), cuptr(input_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(f32_bytes(&skip), cuptr(skip_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(f32_bytes(&gamma), cuptr(gamma_buffer.as_ptr()))
                .unwrap();
        }
        let inputs = [
            TensorView::new(
                DevicePtr(input_buffer.as_ptr()),
                DataType::Float32,
                &shape,
                &strides,
                ep.device_id(),
            ),
            TensorView::new(
                DevicePtr(skip_buffer.as_ptr()),
                DataType::Float32,
                &shape,
                &strides,
                ep.device_id(),
            ),
            TensorView::new(
                DevicePtr(gamma_buffer.as_ptr()),
                DataType::Float32,
                &gamma_shape,
                &gamma_strides,
                ep.device_id(),
            ),
        ];
        let mut outputs = [
            TensorMut::new(
                DevicePtrMut(output_buffer.as_mut_ptr()),
                DataType::Float32,
                &shape,
                &strides,
                ep.device_id(),
            ),
            TensorMut::new(
                DevicePtrMut(mean_buffer.as_mut_ptr()),
                DataType::Float32,
                &stat_shape,
                &stat_strides,
                ep.device_id(),
            ),
            TensorMut::new(
                DevicePtrMut(inverse_standard_deviation_buffer.as_mut_ptr()),
                DataType::Float32,
                &stat_shape,
                &stat_strides,
                ep.device_id(),
            ),
            TensorMut::new(
                DevicePtrMut(sum_buffer.as_mut_ptr()),
                DataType::Float32,
                &shape,
                &strides,
                ep.device_id(),
            ),
        ];
        let kernel = SkipSimplifiedLayerNormKernel {
            epsilon: 1e-5,
            runtime: runtime.clone(),
            metadata: Mutex::new(SkipBroadcastMetadataCache::new(runtime.clone())),
            last_call_capture_safe: AtomicBool::new(false),
        };
        kernel.run(&inputs, &mut outputs).unwrap();
        runtime.synchronize().unwrap();

        let mut output = vec![0.0f32; hidden];
        let mut mean = [f32::NAN];
        let mut got_inverse_standard_deviation = [f32::NAN];
        let mut sum = vec![0.0f32; hidden];
        unsafe {
            runtime
                .dtoh(f32_bytes_mut(&mut output), cuptr(output_buffer.as_ptr()))
                .unwrap();
            runtime
                .dtoh(f32_bytes_mut(&mut mean), cuptr(mean_buffer.as_ptr()))
                .unwrap();
            runtime
                .dtoh(
                    f32_bytes_mut(&mut got_inverse_standard_deviation),
                    cuptr(inverse_standard_deviation_buffer.as_ptr()),
                )
                .unwrap();
            runtime
                .dtoh(f32_bytes_mut(&mut sum), cuptr(sum_buffer.as_ptr()))
                .unwrap();
        }
        assert_eq!(mean[0], 0.0);
        assert_eq!(sum, residual);
        assert!((got_inverse_standard_deviation[0] - inverse_standard_deviation).abs() < 2e-6);
        for index in 0..hidden {
            let reference = residual[index] * inverse_standard_deviation * gamma[index];
            assert!(
                (output[index] - reference).abs() < 2e-5,
                "output mismatch at {index}: {} vs {reference}",
                output[index]
            );
        }
        for buffer in [
            input_buffer,
            skip_buffer,
            gamma_buffer,
            output_buffer,
            mean_buffer,
            inverse_standard_deviation_buffer,
            sum_buffer,
        ] {
            ep.deallocate(buffer).unwrap();
        }
    }

    fn f32_bytes_mut(values: &mut [f32]) -> &mut [u8] {
        // SAFETY: f32 is plain-old-data; reinterpreting as bytes is sound.
        unsafe {
            std::slice::from_raw_parts_mut(
                values.as_mut_ptr().cast::<u8>(),
                std::mem::size_of_val(values),
            )
        }
    }
    fn bf16_bytes(values: &[bf16]) -> &[u8] {
        // SAFETY: bf16 is plain two-byte data and the byte slice retains the input lifetime.
        unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
        }
    }

    fn run_bf16_norm_gpu(ep: &CudaExecutionProvider, layer_norm: bool) -> Vec<bf16> {
        let shape = [2, 5];
        let strides = compute_contiguous_strides(&shape);
        let param_shape = [shape[1]];
        let param_strides = compute_contiguous_strides(&param_shape);
        let input = (0..shape.iter().product())
            .map(|index| bf16::from_f32((index as f32 - 4.5) / 3.0))
            .collect::<Vec<_>>();
        let scale = (0..shape[1])
            .map(|index| bf16::from_f32(0.75 + index as f32 * 0.125))
            .collect::<Vec<_>>();
        let bias = (0..shape[1])
            .map(|index| bf16::from_f32((index as f32 - 2.0) / 16.0))
            .collect::<Vec<_>>();
        let bytes = std::mem::size_of_val(input.as_slice());
        let param_bytes = std::mem::size_of_val(scale.as_slice());
        let input_buffer = ep.allocate(bytes, 256).unwrap();
        let scale_buffer = ep.allocate(param_bytes, 256).unwrap();
        let bias_buffer = ep.allocate(param_bytes, 256).unwrap();
        let mut output_buffer = ep.allocate(bytes, 256).unwrap();
        let runtime = ep.runtime();
        unsafe {
            runtime
                .htod(bf16_bytes(&input), cuptr(input_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(bf16_bytes(&scale), cuptr(scale_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(bf16_bytes(&bias), cuptr(bias_buffer.as_ptr()))
                .unwrap();
        }

        let x = TensorView::new(
            DevicePtr(input_buffer.as_ptr()),
            DataType::BFloat16,
            &shape,
            &strides,
            ep.device_id(),
        );
        let scale_view = TensorView::new(
            DevicePtr(scale_buffer.as_ptr()),
            DataType::BFloat16,
            &param_shape,
            &param_strides,
            ep.device_id(),
        );
        let output = TensorMut::new(
            DevicePtrMut(output_buffer.as_mut_ptr()),
            DataType::BFloat16,
            &shape,
            &strides,
            ep.device_id(),
        );
        if layer_norm {
            let bias_view = TensorView::new(
                DevicePtr(bias_buffer.as_ptr()),
                DataType::BFloat16,
                &param_shape,
                &param_strides,
                ep.device_id(),
            );
            LayerNormKernel {
                axis: -1,
                epsilon: 1e-5,
                runtime: runtime.clone(),
                warmed_signature: Mutex::new(None),
                last_call_capture_safe: AtomicBool::new(false),
            }
            .run(&[x, scale_view, bias_view], &mut [output])
            .unwrap();
        } else {
            RmsNormKernel {
                axis: -1,
                epsilon: 1e-5,
                runtime: runtime.clone(),
                warmed_signature: Mutex::new(None),
                last_call_capture_safe: AtomicBool::new(false),
            }
            .run(&[x, scale_view], &mut [output])
            .unwrap();
        }

        let mut output_bytes = vec![0u8; bytes];
        unsafe {
            runtime
                .dtoh(&mut output_bytes, cuptr(output_buffer.as_ptr()))
                .unwrap();
        }
        let output = output_bytes
            .chunks_exact(2)
            .map(|raw| bf16::from_bits(u16::from_ne_bytes(raw.try_into().unwrap())))
            .collect();
        ep.deallocate(input_buffer).unwrap();
        ep.deallocate(scale_buffer).unwrap();
        ep.deallocate(bias_buffer).unwrap();
        ep.deallocate(output_buffer).unwrap();
        output
    }

    fn bf16_norm_reference(layer_norm: bool) -> Vec<bf16> {
        let groups = 2;
        let hidden = 5;
        let input = (0..groups * hidden)
            .map(|index| bf16::from_f32((index as f32 - 4.5) / 3.0).to_f32())
            .collect::<Vec<_>>();
        let scale = (0..hidden)
            .map(|index| bf16::from_f32(0.75 + index as f32 * 0.125).to_f32())
            .collect::<Vec<_>>();
        let bias = (0..hidden)
            .map(|index| bf16::from_f32((index as f32 - 2.0) / 16.0).to_f32())
            .collect::<Vec<_>>();
        let mut output = Vec::with_capacity(input.len());
        for group in input.chunks_exact(hidden) {
            if layer_norm {
                let mean = group.iter().sum::<f32>() / hidden as f32;
                let variance = group
                    .iter()
                    .map(|value| (value - mean) * (value - mean))
                    .sum::<f32>()
                    / hidden as f32;
                let inv_std = 1.0 / (variance + 1e-5).sqrt();
                output.extend((0..hidden).map(|index| {
                    bf16::from_f32((group[index] - mean) * inv_std * scale[index] + bias[index])
                }));
            } else {
                let mean_square =
                    group.iter().map(|value| value * value).sum::<f32>() / hidden as f32;
                let inv_std = 1.0 / (mean_square + 1e-5).sqrt();
                output.extend(
                    (0..hidden).map(|index| bf16::from_f32(group[index] * inv_std * scale[index])),
                );
            }
        }
        output
    }

    /// Run `SkipSimplifiedLayerNormalization` on the GPU with fp16 activations
    /// but an **fp32 gamma** (the shape Phi's cast-fold leaves behind), returning
    /// `(output, residual, gamma_f32)`.
    fn run_skip_rmsnorm_gpu_f32_gamma(
        ep: &CudaExecutionProvider,
        hidden: usize,
    ) -> (Vec<f16>, Vec<f16>, Vec<f32>) {
        let shape = [1, hidden];
        let strides = compute_contiguous_strides(&shape);
        let gamma_shape = [hidden];
        let gamma_strides = compute_contiguous_strides(&gamma_shape);
        let input = (0..hidden)
            .map(|index| f16::from_f32(((index * 37 % 101) as f32 - 50.0) / 31.0))
            .collect::<Vec<_>>();
        let skip = (0..hidden)
            .map(|index| f16::from_f32(((index * 17 % 67) as f32 - 33.0) / 47.0))
            .collect::<Vec<_>>();
        // fp32 gamma with sub-fp16 precision, so the full-precision multiply is
        // observable and an fp16 gamma round-trip would perturb the result.
        let gamma = (0..hidden)
            .map(|index| 0.7501 + (index % 41) as f32 * 0.012_345)
            .collect::<Vec<f32>>();
        let residual = input
            .iter()
            .zip(&skip)
            .map(|(input, skip)| f16::from_f32(input.to_f32() + skip.to_f32()))
            .collect::<Vec<_>>();

        let input_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let skip_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let gamma_buffer = ep
            .allocate(hidden * std::mem::size_of::<f32>(), 256)
            .unwrap();
        let mut output_buffer = ep
            .allocate(hidden * std::mem::size_of::<f16>(), 256)
            .unwrap();
        let runtime = ep.runtime();
        unsafe {
            runtime
                .htod(f16_bytes(&input), cuptr(input_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(f16_bytes(&skip), cuptr(skip_buffer.as_ptr()))
                .unwrap();
            runtime
                .htod(f32_bytes(&gamma), cuptr(gamma_buffer.as_ptr()))
                .unwrap();
        }
        {
            let inputs = [
                TensorView::new(
                    DevicePtr(input_buffer.as_ptr()),
                    DataType::Float16,
                    &shape,
                    &strides,
                    ep.device_id(),
                ),
                TensorView::new(
                    DevicePtr(skip_buffer.as_ptr()),
                    DataType::Float16,
                    &shape,
                    &strides,
                    ep.device_id(),
                ),
                TensorView::new(
                    DevicePtr(gamma_buffer.as_ptr()),
                    DataType::Float32,
                    &gamma_shape,
                    &gamma_strides,
                    ep.device_id(),
                ),
            ];
            let output = TensorMut::new(
                DevicePtrMut(output_buffer.as_mut_ptr()),
                DataType::Float16,
                &shape,
                &strides,
                ep.device_id(),
            );
            let kernel = SkipSimplifiedLayerNormKernel {
                epsilon: 1e-5,
                runtime: runtime.clone(),
                metadata: Mutex::new(SkipBroadcastMetadataCache::new(runtime.clone())),
                last_call_capture_safe: AtomicBool::new(false),
            };
            kernel.run(&inputs, &mut [output]).unwrap();
        }
        let mut output_bytes = vec![0u8; hidden * std::mem::size_of::<f16>()];
        unsafe {
            runtime
                .dtoh(&mut output_bytes, cuptr(output_buffer.as_ptr()))
                .unwrap();
        }
        let output = output_bytes
            .chunks_exact(2)
            .map(|raw| f16::from_bits(u16::from_ne_bytes(raw.try_into().unwrap())))
            .collect();
        ep.deallocate(input_buffer).unwrap();
        ep.deallocate(skip_buffer).unwrap();
        ep.deallocate(gamma_buffer).unwrap();
        ep.deallocate(output_buffer).unwrap();
        (output, residual, gamma)
    }

    /// warp_half4 reduction order (fp32, four accumulators) with an fp32 gamma
    /// applied at full precision, matching the widened kernel.
    fn half4_warp_skip_rmsnorm_f32_gamma(residual: &[f16], gamma: &[f32]) -> Vec<f16> {
        let mut lanes = [0.0f32; 32];
        let chunks_per_lane = residual.len() / SKIP_RMSNORM_WARP_HALF4_MULTIPLE;
        for (lane, sum) in lanes.iter_mut().enumerate() {
            let (mut ss0, mut ss1, mut ss2, mut ss3) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
            for item in 0..chunks_per_lane {
                let base = (lane + item * 32) * 4;
                let v0 = residual[base].to_f32();
                let v1 = residual[base + 1].to_f32();
                let v2 = residual[base + 2].to_f32();
                let v3 = residual[base + 3].to_f32();
                ss0 += v0 * v0;
                ss1 += v1 * v1;
                ss2 += v2 * v2;
                ss3 += v3 * v3;
            }
            *sum = (ss0 + ss1) + (ss2 + ss3);
        }
        let mut offset = 16;
        while offset > 0 {
            let previous = lanes;
            for lane in 0..(32 - offset) {
                lanes[lane] += previous[lane + offset];
            }
            offset /= 2;
        }
        let inv_std = 1.0 / (lanes[0] / residual.len() as f32 + 1e-5).sqrt();
        residual
            .iter()
            .zip(gamma)
            .map(|(r, g)| f16::from_f32(r.to_f32() * inv_std * g))
            .collect()
    }

    /// Same reduction but accumulating the sum-of-squares in fp16 (the broken
    /// contract). Used only as a mutation guard: the real kernel must diverge
    /// from this.
    fn f16_accumulation_skip_rmsnorm_f32_gamma(residual: &[f16], gamma: &[f32]) -> Vec<f16> {
        let mut ss = f16::from_f32(0.0);
        for r in residual {
            ss = f16::from_f32(ss.to_f32() + (r.to_f32() * r.to_f32()));
        }
        let inv_std = 1.0 / (ss.to_f32() / residual.len() as f32 + 1e-5).sqrt();
        residual
            .iter()
            .zip(gamma)
            .map(|(r, g)| f16::from_f32(r.to_f32() * inv_std * g))
            .collect()
    }

    #[test]
    fn f32_gamma_warp_selection_is_structural_and_gated() {
        // fp32 gamma now qualifies for the vectorized warp path (default on).
        for hidden in [128usize, 3072, 4096] {
            let sel = select_skip_rmsnorm_variant(true, true, hidden, false, false);
            assert_eq!(
                sel.variant,
                SkipRmsnormVariant::F16WarpHalf4,
                "hidden={hidden} fp32-gamma should take warp_half4"
            );
            assert!(sel.reason.contains("gamma=fp32"));
        }
        // fp16 gamma is unchanged.
        let half = select_skip_rmsnorm_variant(true, true, 3072, false, true);
        assert_eq!(half.variant, SkipRmsnormVariant::F16WarpHalf4);
        assert!(half.reason.contains("gamma=fp16"));
    }

    #[test]
    fn fp32_gamma_gpu_skip_rmsnorm_matches_warp_reference_at_phi_and_qwen_dims() {
        let ep = match CudaExecutionProvider::new_default() {
            Ok(ep) => ep,
            Err(error) => {
                eprintln!("skip: no CUDA GPU/runtime available ({error})");
                return;
            }
        };
        // 128 = Qwen-class small warp; 3072 = Phi-4-mini hidden (both %128==0).
        for hidden in [128usize, 3072] {
            let (output, residual, gamma) = run_skip_rmsnorm_gpu_f32_gamma(&ep, hidden);
            let reference = half4_warp_skip_rmsnorm_f32_gamma(&residual, &gamma);
            let max_error = output
                .iter()
                .zip(&reference)
                .map(|(got, want)| (got.to_f32() - want.to_f32()).abs())
                .fold(0.0f32, f32::max);
            // fp32-accum + fp32-gamma path is ULP-tight to the reference.
            let parity_tol = 1.0e-3f32;
            assert!(
                max_error <= parity_tol,
                "hidden={hidden} fp32-gamma warp GPU max error {max_error}"
            );

            // Mutation guard: a kernel that accumulated the sum-of-squares in
            // fp16 would exceed the parity bound above, so this test would catch
            // a broken accumulation dtype (proving the fp32 contract is real).
            let broken = f16_accumulation_skip_rmsnorm_f32_gamma(&residual, &gamma);
            let broken_error = reference
                .iter()
                .zip(&broken)
                .map(|(want, bad)| (want.to_f32() - bad.to_f32()).abs())
                .fold(0.0f32, f32::max);
            assert!(
                broken_error > parity_tol,
                "hidden={hidden} fp16-accumulation guard too weak ({broken_error}); \
                 test cannot detect a broken accumulation dtype"
            );
        }
    }

    #[test]
    fn fp16_skip_rmsnorm_gpu_is_generic_across_structural_hidden_sizes() {
        let ep = match CudaExecutionProvider::new_default() {
            Ok(ep) => ep,
            Err(error) => {
                eprintln!("skip: no CUDA GPU/runtime available ({error})");
                return;
            }
        };
        for hidden in [896, 1024, 2048, 4096, 5120] {
            let selection = select_skip_rmsnorm_variant(true, true, hidden, false, true);
            assert_eq!(selection.variant, SkipRmsnormVariant::F16WarpHalf4);
            let (output, residual, gamma) = run_fp16_skip_rmsnorm_gpu(&ep, hidden);
            let reference = previous_shared_tree_skip_rmsnorm(&residual, &gamma);
            let max_error = output
                .iter()
                .zip(&reference)
                .map(|(output, reference)| (output.to_f32() - reference.to_f32()).abs())
                .fold(0.0f32, f32::max);
            assert!(
                max_error <= 2.0e-3,
                "hidden={hidden} GPU half4/shared-tree max fp16 error {max_error}"
            );
        }

        let hidden = 900;
        let selection = select_skip_rmsnorm_variant(true, true, hidden, false, true);
        assert_eq!(selection.variant, SkipRmsnormVariant::F16Generic);
        let (output, residual, gamma) = run_fp16_skip_rmsnorm_gpu(&ep, hidden);
        let reference = previous_shared_tree_skip_rmsnorm(&residual, &gamma);
        let max_error = output
            .iter()
            .zip(&reference)
            .map(|(output, reference)| (output.to_f32() - reference.to_f32()).abs())
            .fold(0.0f32, f32::max);
        assert!(
            max_error <= 2.0e-3,
            "hidden={hidden} GPU generic/shared-tree max fp16 error {max_error}"
        );
    }

    #[test]
    fn fp16_skip_rmsnorm_source_uses_one_warp_without_shared_reduction() {
        let start = SKIP_RMSNORM_SRC
            .find("extern \"C\" __global__ void skip_rmsnorm_f16")
            .unwrap();
        let source = &SKIP_RMSNORM_SRC[start..];
        assert!(source.contains("__half2"));
        assert!(source.contains("__shfl_down_sync"));
        assert!(!source.contains("extern __shared__"));
        assert!(!source.contains("__syncthreads"));
    }

    #[test]
    fn require_f32_names_op_and_dtype() {
        let e = require_f32("LayerNormalization", "Scale", DataType::Float16).unwrap_err();
        let msg = format!("{e}");
        assert!(msg.contains("LayerNormalization"), "{msg}");
        assert!(msg.contains("Float16"), "{msg}");
    }

    #[test]
    fn require_contiguous_is_actionable() {
        let e = require_contiguous("RMSNormalization", "X", false).unwrap_err();
        let msg = format!("{e}");
        assert!(msg.contains("non-contiguous"), "{msg}");
        assert!(msg.contains("materialise"), "{msg}");
    }

    #[test]
    fn norm_group_split_matches_axis() {
        // shape [4, 8], axis -1 → 4 groups of 8; last-dim norm.
        let shape = [4usize, 8];
        let axis = resolve_axis("LayerNormalization", -1, shape.len()).unwrap();
        let norm_size: usize = shape[axis..].iter().product();
        let groups: usize = shape[..axis].iter().product();
        assert_eq!((groups, norm_size), (4, 8));
    }

    #[test]
    fn bf16_layernorm_and_rmsnorm_match_fp32_references() {
        let ep = match CudaExecutionProvider::new_default() {
            Ok(ep) => ep,
            Err(error) => {
                eprintln!("skip: no CUDA GPU/runtime available ({error})");
                return;
            }
        };
        for layer_norm in [false, true] {
            let output = run_bf16_norm_gpu(&ep, layer_norm);
            let reference = bf16_norm_reference(layer_norm);
            let max_error = output
                .iter()
                .zip(&reference)
                .map(|(actual, expected)| (actual.to_f32() - expected.to_f32()).abs())
                .fold(0.0f32, f32::max);
            assert!(
                max_error <= 0.015625,
                "{} max bf16 error {max_error}",
                if layer_norm {
                    "LayerNormalization"
                } else {
                    "RMSNormalization"
                }
            );
        }
    }
}