ferrum-kernels 0.8.7

Unified compute kernels (CUDA/Metal/CPU) and model runner for Ferrum inference
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
//! CUDA implementation of the vNext device ownership boundary.
//!
//! This module deliberately owns byte-addressed allocations instead of
//! adapting the legacy `Backend::Buffer`. vNext plans describe physical byte
//! regions, and operation providers must enqueue work only after core grants
//! submission authority.

use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::ops::Range;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Instant;

use cudarc::cublas::{result::CublasError, CudaBlas};
use cudarc::driver::{CudaContext, CudaEvent, CudaSlice, CudaStream, DevicePtr, DriverError};
#[cfg(feature = "vllm-marlin")]
use cudarc::driver::{CudaFunction, LaunchConfig, PushKernelArg};
#[cfg(feature = "vllm-marlin")]
use cudarc::nvrtc::Ptx;
use ferrum_interfaces::vnext::{
    BufferDescriptor, CapabilityId, CopyRegion, DefinitelyNotSubmitted, DeviceBatchingForm,
    DeviceBufferRetention, DeviceClass, DeviceCommandBatch, DeviceCommandEntry,
    DeviceCommandLogicalWork, DeviceCommandPhase, DeviceComputePathRequirement, DeviceDescriptor,
    DeviceErrorReport, DeviceExecutionInterval, DeviceExecutionIntervalKind, DeviceExecutionPath,
    DeviceExecutionSpanKind, DeviceExecutionTiming, DeviceId, DeviceNativeOperationId,
    DeviceNativeWorkAttribution, DeviceReplayedLogicalCommandAttribution,
    DeviceReplayedSegmentAttribution, DeviceReusableAddressScope, DeviceReusableExecutionCapture,
    DeviceReusableExecutionInvocation, DeviceReusableExecutionObservation,
    DeviceReusableExecutionPlan, DeviceReusableExecutionPreparation,
    DeviceReusableExecutionProgram, DeviceReusableExecutionProgramGapReason,
    DeviceReusableExecutionTrim, DeviceRuntime, DeviceSubmissionAttribution,
    DeviceSubmissionExecutionSpan, DeviceSubmissionExecutionTiming, DeviceSubmissionStage,
    DeviceSubmissionTimingSink, DeviceTerminal, DeviceTerminalReceipt, DeviceTimingMeasurement,
    DeviceTimingMode, DeviceTimingUnavailableReason, DisabledDeviceSubmissionTimingSink,
    DynamicStorageProfile, ElementType, FenceIndeterminate, FenceQuery, HostTransferLayout,
    ProgramBindingNodeBinding, RetainedHostMemoryRegion, StaticWeightTransformPlan,
    StaticWeightTransformRequest, StreamState, VNextError, DEVICE_COPY_NATIVE_OPERATION_ID,
    DEVICE_ZERO_NATIVE_OPERATION_ID, HOST_UPLOAD_NATIVE_OPERATION_ID,
};
use ferrum_types::AttentionExecutionPolicy;

use super::vnext_replay::{cuda_executable_candidates, CudaCommandReplayKey, CudaExecutableCache};
use super::vnext_tool_correlation;

static NEXT_RUNTIME_INSTANCE: AtomicU64 = AtomicU64::new(1);
static NEXT_STREAM_INSTANCE: AtomicU64 = AtomicU64::new(1);

struct CudaSubmissionStageTimer<'sink, S>
where
    S: DeviceSubmissionTimingSink,
{
    sink: &'sink S,
    stage: DeviceSubmissionStage,
    started: Option<Instant>,
}

impl<'sink, S> CudaSubmissionStageTimer<'sink, S>
where
    S: DeviceSubmissionTimingSink,
{
    #[inline(always)]
    fn start(sink: &'sink S, stage: DeviceSubmissionStage) -> Self {
        Self {
            sink,
            stage,
            started: S::ENABLED.then(Instant::now),
        }
    }
}

impl<S> Drop for CudaSubmissionStageTimer<'_, S>
where
    S: DeviceSubmissionTimingSink,
{
    fn drop(&mut self) {
        if let Some(started) = self.started.take() {
            if !std::thread::panicking() {
                self.sink
                    .record_device_submission(self.stage, started.elapsed());
            }
        }
    }
}

/// Typed construction input supplied by the CUDA composition root.
///
/// Capability and storage profiles come from the installed provider bundle;
/// the device runtime does not infer them from a model, GPU name, or memory
/// size. The implementation fingerprint must identify that exact bundle.
pub struct CudaDeviceRuntimeConfig {
    pub ordinal: usize,
    pub device_id: DeviceId,
    pub attention_execution_policy: AttentionExecutionPolicy,
    pub runtime_implementation_fingerprint: String,
    pub capabilities: BTreeSet<CapabilityId>,
    pub dynamic_storage_profiles: BTreeSet<DynamicStorageProfile>,
}

#[derive(Debug)]
pub enum CudaDeviceRuntimeError {
    Contract(String),
    Driver {
        operation: &'static str,
        source: DriverError,
    },
    Blas {
        operation: &'static str,
        source: CublasError,
    },
}

impl CudaDeviceRuntimeError {
    pub(super) fn contract(message: impl Into<String>) -> Self {
        Self::Contract(message.into())
    }

    pub(super) fn driver(operation: &'static str, source: DriverError) -> Self {
        Self::Driver { operation, source }
    }

    pub(super) fn blas(operation: &'static str, source: CublasError) -> Self {
        Self::Blas { operation, source }
    }

    fn driver_code(&self) -> Option<cudarc::driver::sys::CUresult> {
        match self {
            Self::Contract(_) => None,
            Self::Driver { source, .. } => Some(source.0),
            Self::Blas { .. } => None,
        }
    }
}

impl fmt::Display for CudaDeviceRuntimeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Contract(message) => formatter.write_str(message),
            Self::Driver { operation, source } => {
                write!(formatter, "CUDA {operation} failed: {source:?}")
            }
            Self::Blas { operation, source } => {
                write!(formatter, "CUDA {operation} failed: {source:?}")
            }
        }
    }
}

impl Error for CudaDeviceRuntimeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Contract(_) => None,
            Self::Driver { .. } => None,
            Self::Blas { source, .. } => Some(source),
        }
    }
}

struct CudaAllocation {
    _base: CudaSlice<u8>,
    aligned_ptr: cudarc::driver::sys::CUdeviceptr,
    requested_bytes: u64,
}

unsafe impl Send for CudaAllocation {}
unsafe impl Sync for CudaAllocation {}

/// One core-owned CUDA allocation with its exact admitted descriptor.
pub struct CudaDeviceBuffer {
    descriptor: BufferDescriptor,
    runtime_instance: u64,
    allocation: Arc<CudaAllocation>,
}

impl fmt::Debug for CudaDeviceBuffer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CudaDeviceBuffer")
            .field("descriptor", &self.descriptor)
            .field("runtime_instance", &self.runtime_instance)
            .finish_non_exhaustive()
    }
}

impl CudaDeviceBuffer {
    fn region(&self, range: Range<u64>) -> Result<CudaBufferRegion, CudaDeviceRuntimeError> {
        self.region_with_retention(range, None)
    }

    pub(crate) fn retained_region(
        &self,
        range: Range<u64>,
        retention: DeviceBufferRetention,
    ) -> Result<CudaBufferRegion, CudaDeviceRuntimeError> {
        self.region_with_retention(range, Some(retention))
    }

    fn region_with_retention(
        &self,
        range: Range<u64>,
        core_retention: Option<DeviceBufferRetention>,
    ) -> Result<CudaBufferRegion, CudaDeviceRuntimeError> {
        if range.start >= range.end
            || range.end > self.descriptor.size_bytes
            || range.end > self.allocation.requested_bytes
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA buffer region is empty or outside its admitted allocation",
            ));
        }
        let device_ptr = self
            .allocation
            .aligned_ptr
            .checked_add(range.start)
            .ok_or_else(|| CudaDeviceRuntimeError::contract("CUDA buffer pointer overflow"))?;
        let reusable_address_scope = core_retention
            .as_ref()
            .and_then(DeviceBufferRetention::reusable_address_scope);
        Ok(CudaBufferRegion {
            _allocation: Arc::clone(&self.allocation),
            _core_retention: core_retention,
            reusable_address_scope,
            runtime_instance: self.runtime_instance,
            device_ptr,
            length_bytes: range.end - range.start,
            element_type: self.descriptor.element_type,
        })
    }
}

/// Owned physical CUDA range retained by an encoded command and its fence.
#[derive(Clone)]
pub(crate) struct CudaBufferRegion {
    _allocation: Arc<CudaAllocation>,
    _core_retention: Option<DeviceBufferRetention>,
    reusable_address_scope: Option<DeviceReusableAddressScope>,
    runtime_instance: u64,
    device_ptr: cudarc::driver::sys::CUdeviceptr,
    length_bytes: u64,
    element_type: ElementType,
}

impl CudaBufferRegion {
    pub(crate) const fn device_ptr(&self) -> cudarc::driver::sys::CUdeviceptr {
        self.device_ptr
    }

    pub(crate) const fn length_bytes(&self) -> u64 {
        self.length_bytes
    }

    pub(crate) const fn element_type(&self) -> ElementType {
        self.element_type
    }
}

type EnqueueAction = Box<
    dyn Fn(
            &CudaStream,
            &CudaBlas,
            &[CudaBufferRegion],
            &[Box<[u8]>],
        ) -> Result<(), CudaDeviceRuntimeError>
        + Send
        + 'static,
>;

/// CUDA work captured by a reusable executable. Submission-scoped resource
/// dependencies must stay on `CudaDeviceCommand` so a cached executable never
/// retains request- or sequence-owned allocations.
pub(crate) struct CudaCommandExecutable {
    regions: Vec<CudaBufferRegion>,
    host_storage: Vec<Box<[u8]>>,
    enqueue: Mutex<EnqueueAction>,
}

pub(crate) struct CudaProgramBindingWrite {
    destination_offset_bytes: u64,
    payload: Box<[u8]>,
}

impl CudaProgramBindingWrite {
    pub(crate) fn new(
        destination_offset_bytes: u64,
        payload: Box<[u8]>,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        if payload.is_empty() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA program binding write payload is empty",
            ));
        }
        Ok(Self {
            destination_offset_bytes,
            payload,
        })
    }
}

struct CudaProgramBindingPatch {
    binding: ProgramBindingNodeBinding,
    destination: CudaBufferRegion,
    writes: Vec<CudaProgramBindingWrite>,
    fence_dependencies: Vec<CudaBufferRegion>,
}

struct CudaProgramBindingTransfer {
    destination_offset_bytes: u64,
    destination_stride_bytes: u64,
    row_bytes: usize,
    row_count: usize,
    payload: Box<[u8]>,
}

fn coalesce_program_binding_transfers(
    mut writes: Vec<CudaProgramBindingWrite>,
    arena_size_bytes: u64,
) -> Result<Vec<CudaProgramBindingTransfer>, CudaDeviceRuntimeError> {
    if writes.is_empty() || arena_size_bytes == 0 {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA sparse program binding transfer has no writes or arena",
        ));
    }
    writes.sort_by_key(|write| write.destination_offset_bytes);

    let mut prior_end = 0_u64;
    for write in &writes {
        let payload_bytes = u64::try_from(write.payload.len()).map_err(|_| {
            CudaDeviceRuntimeError::contract("CUDA program binding payload exceeds u64")
        })?;
        if payload_bytes == 0 {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA sparse program binding write payload is empty",
            ));
        }
        let end = write
            .destination_offset_bytes
            .checked_add(payload_bytes)
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract(
                    "CUDA sparse program binding write range overflows u64",
                )
            })?;
        if write.destination_offset_bytes < prior_end || end > arena_size_bytes {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA sparse program binding writes overlap or exceed the arena",
            ));
        }
        prior_end = end;
    }

    let mut groups = Vec::new();
    let mut group_count = 0_usize;
    let mut group_bytes = 0_usize;
    let mut group_end = None;
    for write in &writes {
        if group_end.is_some_and(|end| end != write.destination_offset_bytes) {
            groups.push((group_count, group_bytes));
            group_count = 0;
            group_bytes = 0;
        }
        group_count = group_count.checked_add(1).ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA sparse program binding transfer count overflows usize",
            )
        })?;
        group_bytes = group_bytes
            .checked_add(write.payload.len())
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract(
                    "CUDA sparse program binding transfer size overflows usize",
                )
            })?;
        group_end = Some(
            write
                .destination_offset_bytes
                .checked_add(u64::try_from(write.payload.len()).map_err(|_| {
                    CudaDeviceRuntimeError::contract("CUDA program binding payload exceeds u64")
                })?)
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA sparse program binding write range overflows u64",
                    )
                })?,
        );
    }
    groups.push((group_count, group_bytes));

    let mut writes = writes.into_iter();
    let mut rows = Vec::with_capacity(groups.len());
    for (group_count, group_bytes) in groups {
        let first = writes
            .next()
            .expect("validated sparse transfer group owns its first write");
        let destination_offset_bytes = first.destination_offset_bytes;
        if group_count == 1 {
            rows.push(CudaProgramBindingWrite {
                destination_offset_bytes,
                payload: first.payload,
            });
            continue;
        }
        let mut payload = Vec::with_capacity(group_bytes);
        payload.extend_from_slice(&first.payload);
        for _ in 1..group_count {
            let write = writes
                .next()
                .expect("validated sparse transfer group owns every adjacent write");
            payload.extend_from_slice(&write.payload);
        }
        debug_assert_eq!(payload.len(), group_bytes);
        rows.push(CudaProgramBindingWrite {
            destination_offset_bytes,
            payload: payload.into_boxed_slice(),
        });
    }
    debug_assert!(writes.next().is_none());

    let mut transfers = Vec::with_capacity(rows.len());
    let mut row_index = 0_usize;
    while row_index < rows.len() {
        let row_bytes = rows[row_index].payload.len();
        let mut row_count = 1_usize;
        let mut destination_stride_bytes = u64::try_from(row_bytes).map_err(|_| {
            CudaDeviceRuntimeError::contract("CUDA sparse program binding row size exceeds u64")
        })?;
        if let Some(next) = rows.get(row_index + 1).filter(|next| {
            next.payload.len() == row_bytes
                && next.destination_offset_bytes > rows[row_index].destination_offset_bytes
        }) {
            destination_stride_bytes = next
                .destination_offset_bytes
                .checked_sub(rows[row_index].destination_offset_bytes)
                .expect("sorted non-overlapping program binding rows have a positive stride");
            row_count = 2;
            while let Some(next) = rows.get(row_index + row_count) {
                let prior = &rows[row_index + row_count - 1];
                if next.payload.len() != row_bytes
                    || next
                        .destination_offset_bytes
                        .checked_sub(prior.destination_offset_bytes)
                        != Some(destination_stride_bytes)
                {
                    break;
                }
                row_count += 1;
            }
        }

        let packed_bytes = row_bytes.checked_mul(row_count).ok_or_else(|| {
            CudaDeviceRuntimeError::contract("CUDA sparse program binding packed rows exceed usize")
        })?;
        let destination_offset_bytes = rows[row_index].destination_offset_bytes;
        let payload = if row_count == 1 {
            std::mem::take(&mut rows[row_index].payload)
        } else {
            let mut payload = Vec::with_capacity(packed_bytes);
            for row in &rows[row_index..row_index + row_count] {
                payload.extend_from_slice(&row.payload);
            }
            debug_assert_eq!(payload.len(), packed_bytes);
            payload.into_boxed_slice()
        };
        transfers.push(CudaProgramBindingTransfer {
            destination_offset_bytes,
            destination_stride_bytes,
            row_bytes,
            row_count,
            payload,
        });
        row_index += row_count;
    }
    Ok(transfers)
}

/// Encoded CUDA work. Buffer and host-transfer storage stays alive until the
/// returned fence reaches a terminal state.
pub struct CudaDeviceCommand {
    runtime_instance: u64,
    operation: &'static str,
    batching_form: DeviceBatchingForm,
    participant_start: u32,
    participant_count: u32,
    token_count: u64,
    compute_dispatch_count: u64,
    transfer_command_count: u64,
    executable: Option<Arc<CudaCommandExecutable>>,
    fence_dependencies: Vec<CudaBufferRegion>,
    replay_key: Option<CudaCommandReplayKey>,
    reusable_address_scope: Option<DeviceReusableAddressScope>,
    replay_gap_reason: Option<DeviceReusableExecutionProgramGapReason>,
    program_binding_patch: Option<CudaProgramBindingPatch>,
    reusable_execution: Option<DeviceReusableExecutionInvocation>,
}

impl fmt::Debug for CudaDeviceCommand {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CudaDeviceCommand")
            .field("runtime_instance", &self.runtime_instance)
            .field("operation", &self.operation)
            .field("batching_form", &self.batching_form)
            .field("participant_start", &self.participant_start)
            .field("participant_count", &self.participant_count)
            .field("token_count", &self.token_count)
            .field("compute_dispatch_count", &self.compute_dispatch_count)
            .field("transfer_command_count", &self.transfer_command_count)
            .field(
                "captured_region_count",
                &self
                    .executable
                    .as_ref()
                    .map_or(0, |executable| executable.regions.len()),
            )
            .field(
                "captured_host_storage_count",
                &self
                    .executable
                    .as_ref()
                    .map_or(0, |executable| executable.host_storage.len()),
            )
            .field("fence_dependency_count", &self.fence_dependencies.len())
            .field("replayable", &self.replay_key.is_some())
            .field(
                "typed_program_binding_patch",
                &self.program_binding_patch.is_some(),
            )
            .field(
                "direct_reusable_execution",
                &self.reusable_execution.is_some(),
            )
            .finish_non_exhaustive()
    }
}

impl CudaDeviceCommand {
    /// Backend-local operation providers use this constructor after translating
    /// every logical invocation view into owned physical regions.
    pub(crate) fn operation(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        enqueue: impl Fn(&CudaStream, &[CudaBufferRegion]) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_inner(
            operation,
            regions,
            Vec::new(),
            None,
            move |stream, _blas, regions, _host_storage| enqueue(stream, regions),
        )
    }

    pub(crate) fn replayable_operation(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        replay_key: CudaCommandReplayKey,
        enqueue: impl Fn(&CudaStream, &[CudaBufferRegion]) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_inner(
            operation,
            regions,
            Vec::new(),
            Some(replay_key),
            move |stream, _blas, regions, _host_storage| enqueue(stream, regions),
        )
    }

    pub(crate) fn operation_with_blas(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        enqueue: impl Fn(&CudaStream, &CudaBlas, &[CudaBufferRegion]) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_inner(
            operation,
            regions,
            Vec::new(),
            None,
            move |stream, blas, regions, _host_storage| enqueue(stream, blas, regions),
        )
    }

    /// Encodes eager work while retaining additional submission-scoped
    /// allocations through the completion fence. Fence dependencies are not
    /// executable inputs and never make the command replayable.
    pub(crate) fn operation_with_blas_and_fence_dependencies(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        fence_dependencies: Vec<CudaBufferRegion>,
        enqueue: impl Fn(&CudaStream, &CudaBlas, &[CudaBufferRegion]) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_inner(
            operation,
            regions,
            fence_dependencies,
            None,
            move |stream, blas, regions, _host_storage| enqueue(stream, blas, regions),
        )
    }

    pub(crate) fn replayable_operation_with_blas(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        replay_key: CudaCommandReplayKey,
        enqueue: impl Fn(&CudaStream, &CudaBlas, &[CudaBufferRegion]) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_inner(
            operation,
            regions,
            Vec::new(),
            Some(replay_key),
            move |stream, blas, regions, _host_storage| enqueue(stream, blas, regions),
        )
    }

    /// Encodes replayable work whose launch addresses are stable while keeping
    /// additional submission-scoped allocations alive through the completion
    /// fence. Fence dependencies do not participate in graph identity or scope.
    pub(crate) fn replayable_operation_with_blas_and_fence_dependencies(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        fence_dependencies: Vec<CudaBufferRegion>,
        replay_key: CudaCommandReplayKey,
        enqueue: impl Fn(&CudaStream, &CudaBlas, &[CudaBufferRegion]) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_inner(
            operation,
            regions,
            fence_dependencies,
            Some(replay_key),
            move |stream, blas, regions, _host_storage| enqueue(stream, blas, regions),
        )
    }

    pub(crate) fn operation_with_host_storage_and_blas(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        host_storage: Vec<Box<[u8]>>,
        enqueue: impl Fn(
                &CudaStream,
                &CudaBlas,
                &[CudaBufferRegion],
                &[Box<[u8]>],
            ) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_with_host_storage_and_blas_inner(
            operation,
            regions,
            host_storage,
            Vec::new(),
            None,
            enqueue,
        )
    }

    pub(crate) fn replayable_operation_with_host_storage_and_blas(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        host_storage: Vec<Box<[u8]>>,
        replay_key: CudaCommandReplayKey,
        enqueue: impl Fn(
                &CudaStream,
                &CudaBlas,
                &[CudaBufferRegion],
                &[Box<[u8]>],
            ) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_with_host_storage_and_blas_inner(
            operation,
            regions,
            host_storage,
            Vec::new(),
            Some(replay_key),
            enqueue,
        )
    }

    pub(crate) fn replayable_operation_with_host_storage_blas_and_fence_dependencies(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        host_storage: Vec<Box<[u8]>>,
        fence_dependencies: Vec<CudaBufferRegion>,
        replay_key: CudaCommandReplayKey,
        enqueue: impl Fn(
                &CudaStream,
                &CudaBlas,
                &[CudaBufferRegion],
                &[Box<[u8]>],
            ) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        Self::operation_with_host_storage_and_blas_inner(
            operation,
            regions,
            host_storage,
            fence_dependencies,
            Some(replay_key),
            enqueue,
        )
    }

    fn operation_with_host_storage_and_blas_inner(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        host_storage: Vec<Box<[u8]>>,
        fence_dependencies: Vec<CudaBufferRegion>,
        replay_key: Option<CudaCommandReplayKey>,
        enqueue: impl Fn(
                &CudaStream,
                &CudaBlas,
                &[CudaBufferRegion],
                &[Box<[u8]>],
            ) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        let runtime_instance = common_runtime_instance(&regions)?;
        validate_fence_dependencies(runtime_instance, &fence_dependencies)?;
        if host_storage.iter().any(|storage| storage.is_empty()) {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA operation host storage contains an empty region",
            ));
        }
        let (replay_key, reusable_address_scope, replay_gap_reason) =
            bind_replay_contract(replay_key, operation, &regions, &host_storage);
        Ok(Self {
            runtime_instance,
            operation,
            batching_form: DeviceBatchingForm::Scalar,
            participant_start: 0,
            participant_count: 0,
            token_count: 0,
            compute_dispatch_count: 0,
            transfer_command_count: 0,
            executable: Some(Arc::new(CudaCommandExecutable {
                regions,
                host_storage,
                enqueue: Mutex::new(Box::new(enqueue)),
            })),
            fence_dependencies,
            replay_key,
            reusable_address_scope,
            replay_gap_reason,
            program_binding_patch: None,
            reusable_execution: None,
        })
    }

    fn operation_inner(
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        fence_dependencies: Vec<CudaBufferRegion>,
        replay_key: Option<CudaCommandReplayKey>,
        enqueue: impl Fn(
                &CudaStream,
                &CudaBlas,
                &[CudaBufferRegion],
                &[Box<[u8]>],
            ) -> Result<(), CudaDeviceRuntimeError>
            + Send
            + 'static,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        let runtime_instance = common_runtime_instance(&regions)?;
        validate_fence_dependencies(runtime_instance, &fence_dependencies)?;
        let host_storage = Vec::new();
        let (replay_key, reusable_address_scope, replay_gap_reason) =
            bind_replay_contract(replay_key, operation, &regions, &host_storage);
        Ok(Self {
            runtime_instance,
            operation,
            batching_form: DeviceBatchingForm::Scalar,
            participant_start: 0,
            participant_count: 0,
            token_count: 0,
            compute_dispatch_count: 0,
            transfer_command_count: 0,
            executable: Some(Arc::new(CudaCommandExecutable {
                regions,
                host_storage,
                enqueue: Mutex::new(Box::new(enqueue)),
            })),
            fence_dependencies,
            replay_key,
            reusable_address_scope,
            replay_gap_reason,
            program_binding_patch: None,
            reusable_execution: None,
        })
    }

    fn transfer(
        runtime_instance: u64,
        operation: &'static str,
        regions: Vec<CudaBufferRegion>,
        host_storage: Vec<Box<[u8]>>,
        enqueue: EnqueueAction,
    ) -> Self {
        let executable = Arc::new(CudaCommandExecutable {
            regions,
            host_storage,
            enqueue: Mutex::new(enqueue),
        });
        Self {
            runtime_instance,
            operation,
            batching_form: DeviceBatchingForm::Scalar,
            participant_start: 0,
            participant_count: 0,
            token_count: 0,
            compute_dispatch_count: 0,
            transfer_command_count: 1,
            executable: Some(executable),
            fence_dependencies: Vec::new(),
            replay_key: None,
            reusable_address_scope: None,
            replay_gap_reason: None,
            program_binding_patch: None,
            reusable_execution: None,
        }
    }

    pub(crate) fn program_binding_patch(
        operation: &'static str,
        binding: ProgramBindingNodeBinding,
        destination: CudaBufferRegion,
        mut writes: Vec<CudaProgramBindingWrite>,
        fence_dependencies: Vec<CudaBufferRegion>,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        let runtime_instance = destination.runtime_instance;
        validate_fence_dependencies(runtime_instance, &fence_dependencies)?;
        let slot = binding.slot();
        if destination.element_type != ElementType::U8
            || destination.length_bytes == 0
            || destination.length_bytes > slot.capacity_size_bytes()
            || writes.is_empty()
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA program binding destination differs from its compiled slot",
            ));
        }
        writes.sort_by_key(|write| write.destination_offset_bytes);
        let mut prior_end = 0_u64;
        for write in &writes {
            let payload_bytes = u64::try_from(write.payload.len()).map_err(|_| {
                CudaDeviceRuntimeError::contract("CUDA program binding payload exceeds u64")
            })?;
            let end = write
                .destination_offset_bytes
                .checked_add(payload_bytes)
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA program binding write range overflows u64",
                    )
                })?;
            if write.destination_offset_bytes < prior_end || end > destination.length_bytes {
                return Err(CudaDeviceRuntimeError::contract(
                    "CUDA program binding writes overlap or exceed the logical slot",
                ));
            }
            prior_end = end;
        }
        Ok(Self {
            runtime_instance,
            operation,
            batching_form: DeviceBatchingForm::Scalar,
            participant_start: 0,
            participant_count: 0,
            token_count: 0,
            compute_dispatch_count: 0,
            transfer_command_count: 0,
            executable: None,
            fence_dependencies: Vec::new(),
            replay_key: None,
            reusable_address_scope: None,
            replay_gap_reason: None,
            program_binding_patch: Some(CudaProgramBindingPatch {
                binding,
                destination,
                writes,
                fence_dependencies,
            }),
            reusable_execution: None,
        })
    }

    pub(crate) fn with_work_attribution(
        mut self,
        batching_form: DeviceBatchingForm,
        participant_count: u32,
        token_count: u64,
        compute_dispatch_count: u64,
        transfer_command_count: u64,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        if participant_count == 0 || (compute_dispatch_count == 0 && transfer_command_count == 0) {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA operation attribution has no participants or native work",
            ));
        }
        self.batching_form = batching_form;
        self.participant_start = 0;
        self.participant_count = participant_count;
        self.token_count = token_count;
        self.compute_dispatch_count = compute_dispatch_count;
        self.transfer_command_count = transfer_command_count;
        Ok(self)
    }

    fn with_initialization_native_work(
        mut self,
        compute_dispatch_count: u64,
        transfer_command_count: u64,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        if compute_dispatch_count == 0 || transfer_command_count == 0 {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA static transform attribution requires compute and transfer work",
            ));
        }
        self.compute_dispatch_count = compute_dispatch_count;
        self.transfer_command_count = transfer_command_count;
        Ok(self)
    }

    fn bind_core_logical_work(
        mut self,
        logical_work: DeviceCommandLogicalWork,
    ) -> Result<Self, CudaDeviceRuntimeError> {
        if self.participant_count != 0 || self.token_count != 0 {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA core logical work cannot replace provider command attribution",
            ));
        }
        self.batching_form = logical_work.batching_form();
        self.participant_start = logical_work.participant_start();
        self.participant_count = logical_work.participant_count();
        self.token_count = logical_work.token_count();
        Ok(self)
    }

    fn reusable_execution(
        runtime_instance: u64,
        invocation: DeviceReusableExecutionInvocation,
    ) -> Self {
        let participant_count = invocation.participant_count();
        let token_count = invocation.token_count();
        let executable = Arc::new(CudaCommandExecutable {
            regions: Vec::new(),
            host_storage: Vec::new(),
            enqueue: Mutex::new(Box::new(|_, _, _, _| {
                Err(CudaDeviceRuntimeError::contract(
                    "direct reusable execution must be resolved by the owning stream cache",
                ))
            })),
        });
        Self {
            runtime_instance,
            operation: "vnext_reusable_execution",
            batching_form: DeviceBatchingForm::ParticipantLoop,
            participant_start: 0,
            participant_count,
            token_count,
            compute_dispatch_count: 1,
            transfer_command_count: 0,
            executable: Some(executable),
            fence_dependencies: Vec::new(),
            replay_key: None,
            reusable_address_scope: None,
            replay_gap_reason: None,
            program_binding_patch: None,
            reusable_execution: Some(invocation),
        }
    }

    fn coalesced_program_bindings(
        mut commands: Vec<Self>,
    ) -> Result<Vec<Self>, CudaDeviceRuntimeError> {
        if commands.is_empty() {
            return Ok(commands);
        }
        let typed_patch_count = commands
            .iter()
            .filter(|command| command.program_binding_patch.is_some())
            .count();
        if typed_patch_count == 0 {
            if commands.len() == 1 {
                return Ok(commands);
            }
            return Self::coalesced_opaque_program_bindings(commands);
        }
        if typed_patch_count != commands.len() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA program binding prelude mixes typed and opaque patches",
            ));
        }

        let runtime_instance = commands[0].runtime_instance;
        let participant_start = commands[0].participant_start;
        let participant_count = commands[0].participant_count;
        let token_count = commands[0].token_count;
        if participant_count == 0
            || commands.iter().any(|command| {
                command.runtime_instance != runtime_instance
                    || command.participant_start != participant_start
                    || command.participant_count != participant_count
                    || command.token_count != token_count
                    || command.compute_dispatch_count != 0
                    || command.transfer_command_count == 0
                    || command.replay_key.is_some()
                    || command.reusable_address_scope.is_some()
            })
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA typed program bindings are not one compatible prelude",
            ));
        }

        let mut patches = commands
            .iter_mut()
            .map(|command| {
                command.program_binding_patch.take().ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA typed program binding patch disappeared during coalescing",
                    )
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        patches.sort_by_key(|patch| patch.binding.node_index());
        let first = patches.first().expect("non-empty typed patch set");
        let layout = first.binding.layout();
        let lane_slot = first.binding.lane_slot_identity();
        let plan_hash = first.binding.plan_hash();
        if patches.len() != layout.slots().len()
            || patches.iter().zip(layout.slots()).any(|(patch, slot)| {
                patch.binding.node_index() != slot.node_index()
                    || patch.binding.plan_hash() != plan_hash
                    || patch.binding.layout().fingerprint() != layout.fingerprint()
                    || patch.binding.lane_slot_identity() != lane_slot
                    || patch.binding.slot() != slot
            })
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA typed program bindings do not cover one compiled layout exactly",
            ));
        }

        let layout_physical_size_bytes = layout.physical_size_bytes();
        let first_destination = first.destination.clone();
        let first_slot_offset_bytes = first.binding.slot().physical_offset_bytes();
        let arena_device_ptr = first_destination
            .device_ptr
            .checked_sub(first_slot_offset_bytes)
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract(
                    "CUDA program binding arena base pointer underflows",
                )
            })?;
        let allocation_end = first_destination
            ._allocation
            .aligned_ptr
            .checked_add(first_destination._allocation.requested_bytes)
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract("CUDA program binding allocation end overflows")
            })?;
        let arena_end = arena_device_ptr
            .checked_add(layout_physical_size_bytes)
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract("CUDA program binding arena end overflows")
            })?;
        if arena_device_ptr < first_destination._allocation.aligned_ptr
            || arena_end > allocation_end
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA compiled program binding arena exceeds its admitted allocation",
            ));
        }

        let mut fence_dependencies = Vec::new();
        let mut arena_writes = Vec::new();
        for patch in patches {
            let slot = patch.binding.slot();
            let expected_device_ptr = arena_device_ptr
                .checked_add(slot.physical_offset_bytes())
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract("CUDA program binding slot pointer overflows")
                })?;
            if patch.destination.runtime_instance != runtime_instance
                || patch.destination.device_ptr != expected_device_ptr
                || patch.destination.element_type != ElementType::U8
                || !Arc::ptr_eq(
                    &patch.destination._allocation,
                    &first_destination._allocation,
                )
            {
                return Err(CudaDeviceRuntimeError::contract(
                    "CUDA program binding patch destination differs from its arena slot",
                ));
            }
            for mut write in patch.writes {
                write.destination_offset_bytes = slot
                    .physical_offset_bytes()
                    .checked_add(write.destination_offset_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA sparse program binding write offset overflows",
                        )
                    })?;
                arena_writes.push(write);
            }
            fence_dependencies.extend(patch.fence_dependencies);
        }

        let transfers =
            coalesce_program_binding_transfers(arena_writes, layout_physical_size_bytes)?;
        let transfer_command_count = u64::try_from(transfers.len()).map_err(|_| {
            CudaDeviceRuntimeError::contract(
                "CUDA sparse program binding transfer count exceeds u64",
            )
        })?;
        let mut regions = Vec::with_capacity(transfers.len());
        let mut host_storage = Vec::with_capacity(transfers.len());
        let mut transfer_shapes = Vec::with_capacity(transfers.len());
        for transfer in transfers {
            let row_bytes_u64 = u64::try_from(transfer.row_bytes).map_err(|_| {
                CudaDeviceRuntimeError::contract("CUDA sparse program binding row size exceeds u64")
            })?;
            let trailing_rows =
                u64::try_from(transfer.row_count.saturating_sub(1)).map_err(|_| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA sparse program binding row count exceeds u64",
                    )
                })?;
            let destination_span_bytes = transfer
                .destination_stride_bytes
                .checked_mul(trailing_rows)
                .and_then(|span| span.checked_add(row_bytes_u64))
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA sparse program binding destination span overflows",
                    )
                })?;
            let destination_end = transfer
                .destination_offset_bytes
                .checked_add(destination_span_bytes)
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA sparse program binding destination end overflows",
                    )
                })?;
            if destination_end > layout_physical_size_bytes {
                return Err(CudaDeviceRuntimeError::contract(
                    "CUDA sparse program binding transfer exceeds its arena",
                ));
            }
            let device_ptr = arena_device_ptr
                .checked_add(transfer.destination_offset_bytes)
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA sparse program binding destination pointer overflows",
                    )
                })?;
            regions.push(CudaBufferRegion {
                _allocation: Arc::clone(&first_destination._allocation),
                _core_retention: first_destination._core_retention.clone(),
                reusable_address_scope: first_destination.reusable_address_scope,
                runtime_instance,
                device_ptr,
                length_bytes: destination_span_bytes,
                element_type: ElementType::U8,
            });
            transfer_shapes.push((
                checked_usize(
                    transfer.destination_stride_bytes,
                    "CUDA sparse program binding destination stride",
                )?,
                transfer.row_bytes,
                transfer.row_count,
            ));
            host_storage.push(transfer.payload);
        }
        let executable = Arc::new(CudaCommandExecutable {
            regions,
            host_storage,
            enqueue: Mutex::new(Box::new(move |stream, _blas, regions, host_storage| {
                if regions.len() != host_storage.len() || regions.len() != transfer_shapes.len() {
                    return Err(CudaDeviceRuntimeError::contract(
                        "CUDA sparse program binding transfer storage differs from its shape",
                    ));
                }
                for ((region, payload), &(destination_pitch, row_bytes, row_count)) in
                    regions.iter().zip(host_storage).zip(&transfer_shapes)
                {
                    if row_count == 1 {
                        unsafe {
                            cudarc::driver::result::memcpy_htod_async(
                                region.device_ptr,
                                payload.as_ref(),
                                stream.cu_stream(),
                            )
                        }
                        .map_err(|error| {
                            CudaDeviceRuntimeError::driver("sparse program binding upload", error)
                        })?;
                        continue;
                    }
                    let copy = cudarc::driver::sys::CUDA_MEMCPY2D {
                        srcXInBytes: 0,
                        srcY: 0,
                        srcMemoryType: cudarc::driver::sys::CUmemorytype::CU_MEMORYTYPE_HOST,
                        srcHost: payload.as_ptr().cast(),
                        srcDevice: 0,
                        srcArray: std::ptr::null_mut(),
                        srcPitch: row_bytes,
                        dstXInBytes: 0,
                        dstY: 0,
                        dstMemoryType: cudarc::driver::sys::CUmemorytype::CU_MEMORYTYPE_DEVICE,
                        dstHost: std::ptr::null_mut(),
                        dstDevice: region.device_ptr,
                        dstArray: std::ptr::null_mut(),
                        dstPitch: destination_pitch,
                        WidthInBytes: row_bytes,
                        Height: row_count,
                    };
                    unsafe { cudarc::driver::sys::cuMemcpy2DAsync_v2(&copy, stream.cu_stream()) }
                        .result()
                        .map_err(|error| {
                            CudaDeviceRuntimeError::driver(
                                "strided sparse program binding upload",
                                error,
                            )
                        })?;
                }
                Ok(())
            })),
        });
        Ok(vec![Self {
            runtime_instance,
            operation: "vnext_program_binding_prelude",
            batching_form: DeviceBatchingForm::ParticipantLoop,
            participant_start,
            participant_count,
            token_count,
            compute_dispatch_count: 0,
            transfer_command_count,
            executable: Some(executable),
            fence_dependencies,
            replay_key: None,
            reusable_address_scope: None,
            replay_gap_reason: None,
            program_binding_patch: None,
            reusable_execution: None,
        }])
    }

    fn coalesced_opaque_program_bindings(
        commands: Vec<Self>,
    ) -> Result<Vec<Self>, CudaDeviceRuntimeError> {
        let runtime_instance = commands[0].runtime_instance;
        let participant_start = commands[0].participant_start;
        let participant_count = commands[0].participant_count;
        let token_count = commands[0].token_count;
        if participant_count == 0
            || commands.iter().any(|command| {
                command.runtime_instance != runtime_instance
                    || command.participant_start != participant_start
                    || command.participant_count != participant_count
                    || command.token_count != token_count
                    || command.compute_dispatch_count != 0
                    || command.transfer_command_count == 0
                    || command.replay_key.is_some()
                    || command.reusable_address_scope.is_some()
            })
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA program bindings are not one compatible eager prelude",
            ));
        }
        let transfer_command_count = commands.iter().try_fold(0_u64, |total, command| {
            total
                .checked_add(command.transfer_command_count)
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA program binding transfer count overflows u64",
                    )
                })
        })?;
        let executable = Arc::new(CudaCommandExecutable {
            regions: Vec::new(),
            host_storage: Vec::new(),
            enqueue: Mutex::new(Box::new(move |stream, blas, _regions, _host_storage| {
                commands
                    .iter()
                    .try_for_each(|command| command.enqueue(stream, blas))
            })),
        });
        Ok(vec![Self {
            runtime_instance,
            operation: "vnext_program_binding_prelude",
            batching_form: DeviceBatchingForm::ParticipantLoop,
            participant_start,
            participant_count,
            token_count,
            compute_dispatch_count: 0,
            transfer_command_count,
            executable: Some(executable),
            fence_dependencies: Vec::new(),
            replay_key: None,
            reusable_address_scope: None,
            replay_gap_reason: None,
            program_binding_patch: None,
            reusable_execution: None,
        }])
    }

    pub(crate) fn enqueue(
        &self,
        stream: &CudaStream,
        blas: &CudaBlas,
    ) -> Result<(), CudaDeviceRuntimeError> {
        let executable = self.executable.as_ref().ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "uncoalesced CUDA program binding patch cannot enqueue",
            )
        })?;
        let enqueue = executable
            .enqueue
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        enqueue(stream, blas, &executable.regions, &executable.host_storage)
    }

    pub(crate) const fn replay_key(&self) -> Option<CudaCommandReplayKey> {
        self.replay_key
    }

    pub(crate) fn reusable_execution_invocation(
        &self,
    ) -> Option<&DeviceReusableExecutionInvocation> {
        self.reusable_execution.as_ref()
    }

    pub(crate) fn replayed_logical_attribution(
        &self,
        logical_command_ordinal: u32,
        node_index: u32,
        reusable_graph_node_count: u32,
    ) -> Option<DeviceReplayedLogicalCommandAttribution> {
        DeviceReplayedLogicalCommandAttribution::new(
            logical_command_ordinal,
            node_index,
            DeviceNativeOperationId::new(self.operation)?,
            self.batching_form,
            self.participant_count,
            self.token_count,
            self.compute_dispatch_count,
            self.transfer_command_count,
            u64::from(reusable_graph_node_count),
        )
    }

    pub(crate) const fn reusable_address_scope(&self) -> Option<DeviceReusableAddressScope> {
        self.reusable_address_scope
    }

    pub(crate) const fn replay_gap_reason(
        &self,
    ) -> Option<DeviceReusableExecutionProgramGapReason> {
        self.replay_gap_reason
    }

    pub(crate) fn executable(&self) -> Arc<CudaCommandExecutable> {
        Arc::clone(
            self.executable
                .as_ref()
                .expect("replayable CUDA command owns an executable"),
        )
    }
}

fn bind_replay_contract(
    replay_key: Option<CudaCommandReplayKey>,
    operation: &'static str,
    regions: &[CudaBufferRegion],
    host_storage: &[Box<[u8]>],
) -> (
    Option<CudaCommandReplayKey>,
    Option<DeviceReusableAddressScope>,
    Option<DeviceReusableExecutionProgramGapReason>,
) {
    let Some(key) = replay_key else {
        return (
            None,
            None,
            Some(DeviceReusableExecutionProgramGapReason::ProviderReplayKeyMissing),
        );
    };
    let mut scope = DeviceReusableAddressScope::Plan;
    for region in regions {
        let Some(region_scope) = region.reusable_address_scope else {
            return (
                None,
                None,
                Some(DeviceReusableExecutionProgramGapReason::ReusableAddressScopeMissing),
            );
        };
        match region_scope {
            DeviceReusableAddressScope::Plan => {}
            DeviceReusableAddressScope::ExecutionLane(lane_id) => {
                match scope {
                    DeviceReusableAddressScope::Plan => {
                        scope = DeviceReusableAddressScope::ExecutionLane(lane_id);
                    }
                    DeviceReusableAddressScope::ExecutionLane(current) if current == lane_id => {}
                    DeviceReusableAddressScope::ExecutionLane(_) => return (
                        None,
                        None,
                        Some(DeviceReusableExecutionProgramGapReason::ReusableAddressScopeConflict),
                    ),
                }
            }
        }
    }
    (
        Some(
            key.bind_runtime_payload(
                operation,
                regions
                    .iter()
                    .map(|region| (region.device_ptr, region.length_bytes, region.element_type)),
                host_storage,
            ),
        ),
        Some(scope),
        None,
    )
}

fn common_runtime_instance(regions: &[CudaBufferRegion]) -> Result<u64, CudaDeviceRuntimeError> {
    let runtime_instance = regions
        .first()
        .map(|region| region.runtime_instance)
        .ok_or_else(|| CudaDeviceRuntimeError::contract("CUDA operation has no buffer regions"))?;
    if regions
        .iter()
        .any(|region| region.runtime_instance != runtime_instance)
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA operation mixes buffers from different runtime instances",
        ));
    }
    Ok(runtime_instance)
}

fn validate_fence_dependencies(
    runtime_instance: u64,
    dependencies: &[CudaBufferRegion],
) -> Result<(), CudaDeviceRuntimeError> {
    if dependencies
        .iter()
        .any(|region| region.runtime_instance != runtime_instance)
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA operation retains fence dependencies from another runtime instance",
        ));
    }
    Ok(())
}

fn cuda_submission_attribution(
    command_phases: &[ferrum_interfaces::vnext::DeviceCommandPhase],
    command_node_indices: &[Option<u32>],
    commands: &[CudaDeviceCommand],
    execution_paths: &[DeviceExecutionPath],
    reusable_graph_node_counts: Option<&[Option<u64>]>,
    replayed_segments: Vec<DeviceReplayedSegmentAttribution>,
) -> Result<DeviceSubmissionAttribution, CudaDeviceRuntimeError> {
    if command_phases.len() != commands.len()
        || command_node_indices.len() != commands.len()
        || execution_paths.len() != commands.len()
        || reusable_graph_node_counts.is_some_and(|counts| counts.len() != commands.len())
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA command attribution differs from its submitted batch",
        ));
    }
    let rows = commands
        .iter()
        .enumerate()
        .map(|(command_index, command)| {
            let command_index = u32::try_from(command_index)
                .map_err(|_| CudaDeviceRuntimeError::contract("CUDA command index exceeds u32"))?;
            let native_op_id =
                DeviceNativeOperationId::new(command.operation).ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA command attribution has a non-portable native operation identity",
                    )
                })?;
            DeviceNativeWorkAttribution::with_participant_range(
                command_index,
                command_node_indices[command_index as usize],
                command_phases[command_index as usize],
                native_op_id,
                execution_paths[command_index as usize],
                command.batching_form,
                command.participant_start,
                command.participant_count,
                command.token_count,
                command.compute_dispatch_count,
                command.transfer_command_count,
                reusable_graph_node_counts.and_then(|counts| counts[command_index as usize]),
            )
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract(
                    "CUDA command attribution has invalid native work metadata",
                )
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    DeviceSubmissionAttribution::with_replayed_segments(rows, replayed_segments).ok_or_else(|| {
        CudaDeviceRuntimeError::contract("CUDA submission attribution is empty or unordered")
    })
}

pub struct CudaDeviceStream {
    id: u64,
    runtime_instance: u64,
    stream: Arc<CudaStream>,
    blas: Arc<CudaBlas>,
    state: Arc<CudaStreamState>,
    executable_cache: CudaExecutableCache,
}

impl fmt::Debug for CudaDeviceStream {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CudaDeviceStream")
            .field("id", &self.id)
            .field("runtime_instance", &self.runtime_instance)
            .field("state", &self.state.snapshot())
            .finish_non_exhaustive()
    }
}

impl Drop for CudaDeviceStream {
    fn drop(&mut self) {
        if !self.state.is_quiescent() {
            // An indeterminate lane must retain captured pointer ownership.
            // Normal executor shutdown reaches quiescence and destroys every
            // graph without a device-wide synchronization.
            self.executable_cache.leak_if_in_flight();
        }
    }
}

struct CudaStreamState {
    recording: AtomicBool,
    failed: AtomicBool,
    in_flight: AtomicU64,
}

impl CudaStreamState {
    fn new() -> Self {
        Self {
            recording: AtomicBool::new(false),
            failed: AtomicBool::new(false),
            in_flight: AtomicU64::new(0),
        }
    }

    fn snapshot(&self) -> StreamState {
        if self.failed.load(Ordering::Acquire) {
            StreamState::Failed
        } else if self.recording.load(Ordering::Acquire) {
            StreamState::Recording
        } else if self.in_flight.load(Ordering::Acquire) == 0 {
            StreamState::Ready
        } else {
            StreamState::Submitted
        }
    }

    fn is_quiescent(&self) -> bool {
        !self.failed.load(Ordering::Acquire)
            && !self.recording.load(Ordering::Acquire)
            && self.in_flight.load(Ordering::Acquire) == 0
    }

    fn begin_submission(&self) -> Result<(), CudaDeviceRuntimeError> {
        if self.failed.load(Ordering::Acquire)
            || self
                .recording
                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                .is_err()
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA stream is failed or already recording a submission",
            ));
        }
        if self.failed.load(Ordering::Acquire) {
            self.recording.store(false, Ordering::Release);
            return Err(CudaDeviceRuntimeError::contract("CUDA stream is failed"));
        }
        Ok(())
    }

    fn submission_recorded(&self) -> Result<(), CudaDeviceRuntimeError> {
        self.in_flight
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                current.checked_add(1)
            })
            .map_err(|_| CudaDeviceRuntimeError::contract("CUDA in-flight count overflowed"))?;
        self.recording.store(false, Ordering::Release);
        Ok(())
    }

    fn finish_one(&self) {
        let _ = self
            .in_flight
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                current.checked_sub(1)
            });
    }

    fn fail(&self) {
        self.failed.store(true, Ordering::Release);
        self.recording.store(false, Ordering::Release);
    }

    fn synchronized(&self) {
        self.in_flight.store(0, Ordering::Release);
        self.recording.store(false, Ordering::Release);
    }
}

pub struct CudaDeviceFence {
    event: CudaEvent,
    timing: CudaFenceTiming,
    command_timing: CudaFenceCommandTiming,
    attribution: Option<DeviceSubmissionAttribution>,
    stream_state: Arc<CudaStreamState>,
    terminal_accounted: AtomicBool,
    _stream: Arc<CudaStream>,
    _blas: Arc<CudaBlas>,
    _commands: Vec<CudaDeviceCommand>,
}

enum CudaFenceTiming {
    NotRequested,
    Events { start: CudaEvent },
    Unavailable,
}

impl CudaFenceTiming {
    fn origin(&self) -> Option<&CudaEvent> {
        match self {
            Self::Events { start } => Some(start),
            Self::NotRequested | Self::Unavailable => None,
        }
    }
}

enum CudaExecutionSpanEventMeasurement {
    Events { start: CudaEvent, end: CudaEvent },
    Unavailable(DeviceTimingUnavailableReason),
}

struct CudaExecutionSpanEventTiming {
    start_command_index: u32,
    end_command_index: u32,
    span_kind: DeviceExecutionSpanKind,
    interval_kind: DeviceExecutionIntervalKind,
    operation: &'static str,
    reusable_executable_fingerprint: Option<Arc<str>>,
    measurement: CudaExecutionSpanEventMeasurement,
}

impl CudaExecutionSpanEventTiming {
    fn new(
        start_command_index: usize,
        end_command_index: usize,
        span_kind: DeviceExecutionSpanKind,
        interval_kind: DeviceExecutionIntervalKind,
        operation: &'static str,
        reusable_executable_fingerprint: Option<Arc<str>>,
        events: Option<(CudaEvent, CudaEvent)>,
    ) -> Option<Self> {
        let start_command_index = u32::try_from(start_command_index).ok()?;
        let end_command_index = u32::try_from(end_command_index).ok()?;
        let measurement = events.map_or(
            CudaExecutionSpanEventMeasurement::Unavailable(
                DeviceTimingUnavailableReason::BackendMeasurementFailed,
            ),
            |(start, end)| CudaExecutionSpanEventMeasurement::Events { start, end },
        );
        Some(Self {
            start_command_index,
            end_command_index,
            span_kind,
            interval_kind,
            operation,
            reusable_executable_fingerprint,
            measurement,
        })
    }

    fn resolve(&self, origin: &CudaEvent) -> Option<DeviceSubmissionExecutionSpan> {
        let span = match &self.measurement {
            CudaExecutionSpanEventMeasurement::Events { start, end } => {
                let interval = cuda_event_elapsed_ns(origin, start)
                    .zip(cuda_event_elapsed_ns(origin, end))
                    .and_then(|(start_offset_ns, end_offset_ns)| {
                        DeviceExecutionInterval::new_labeled(
                            self.interval_kind,
                            start_offset_ns,
                            end_offset_ns,
                            self.operation,
                        )
                    });
                match interval {
                    Some(interval) => DeviceSubmissionExecutionSpan::measured(
                        self.start_command_index,
                        self.end_command_index,
                        self.span_kind,
                        vec![interval],
                    ),
                    None => DeviceSubmissionExecutionSpan::unavailable(
                        self.start_command_index,
                        self.end_command_index,
                        self.span_kind,
                        DeviceTimingUnavailableReason::BackendMeasurementFailed,
                    ),
                }
            }
            CudaExecutionSpanEventMeasurement::Unavailable(reason) => {
                DeviceSubmissionExecutionSpan::unavailable(
                    self.start_command_index,
                    self.end_command_index,
                    self.span_kind,
                    *reason,
                )
            }
        }?;
        match &self.reusable_executable_fingerprint {
            Some(fingerprint) => {
                span.with_reusable_executable_fingerprint(fingerprint.as_ref().to_owned())
            }
            None => Some(span),
        }
    }
}

enum CudaFenceCommandTiming {
    NotRequested,
    Unavailable(DeviceTimingUnavailableReason),
    Spans {
        command_count: u32,
        spans: Vec<CudaExecutionSpanEventTiming>,
    },
}

impl CudaFenceCommandTiming {
    fn measurement(
        &self,
        origin: Option<&CudaEvent>,
    ) -> DeviceTimingMeasurement<DeviceSubmissionExecutionTiming> {
        match self {
            Self::NotRequested => DeviceTimingMeasurement::NotRequested,
            Self::Unavailable(reason) => DeviceTimingMeasurement::Unavailable(*reason),
            Self::Spans {
                command_count,
                spans,
            } => {
                let Some(origin) = origin else {
                    return DeviceTimingMeasurement::Unavailable(
                        DeviceTimingUnavailableReason::BackendMeasurementFailed,
                    );
                };
                let spans = spans
                    .iter()
                    .map(|span| span.resolve(origin))
                    .collect::<Option<Vec<_>>>()
                    .and_then(|spans| {
                        DeviceSubmissionExecutionTiming::from_spans(*command_count, spans)
                    });
                spans.map_or_else(
                    || {
                        DeviceTimingMeasurement::Unavailable(
                            DeviceTimingUnavailableReason::BackendMeasurementFailed,
                        )
                    },
                    DeviceTimingMeasurement::Measured,
                )
            }
        }
    }
}

impl fmt::Debug for CudaDeviceFence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CudaDeviceFence")
            .field("stream_state", &self.stream_state.snapshot())
            .finish_non_exhaustive()
    }
}

impl CudaDeviceFence {
    fn mark_terminal(&self) {
        if !self.terminal_accounted.swap(true, Ordering::AcqRel) {
            self.stream_state.finish_one();
        }
    }

    fn execution_timing(&self) -> DeviceTimingMeasurement<DeviceExecutionTiming> {
        let start = match &self.timing {
            CudaFenceTiming::Events { start } => start,
            _ => {
                return match &self.timing {
                    CudaFenceTiming::NotRequested => DeviceTimingMeasurement::NotRequested,
                    CudaFenceTiming::Unavailable => DeviceTimingMeasurement::Unavailable(
                        DeviceTimingUnavailableReason::BackendMeasurementFailed,
                    ),
                    CudaFenceTiming::Events { .. } => unreachable!(),
                };
            }
        };
        cuda_event_elapsed_ns(start, &self.event).map_or_else(
            || {
                DeviceTimingMeasurement::Unavailable(
                    DeviceTimingUnavailableReason::BackendMeasurementFailed,
                )
            },
            |elapsed_ns| {
                DeviceTimingMeasurement::Measured(DeviceExecutionTiming::device_event_elapsed(
                    elapsed_ns,
                ))
            },
        )
    }

    fn terminal_receipt<E>(&self, terminal: DeviceTerminal<E>) -> DeviceTerminalReceipt<E> {
        match &self.timing {
            CudaFenceTiming::NotRequested => DeviceTerminalReceipt::unprofiled(terminal),
            CudaFenceTiming::Events { .. } | CudaFenceTiming::Unavailable => {
                match &self.command_timing {
                    CudaFenceCommandTiming::NotRequested => {
                        DeviceTerminalReceipt::profiled(terminal, self.execution_timing())
                    }
                    CudaFenceCommandTiming::Unavailable(_)
                    | CudaFenceCommandTiming::Spans { .. } => {
                        DeviceTerminalReceipt::profiled_with_submission_timing(
                            terminal,
                            self.execution_timing(),
                            self.command_timing.measurement(self.timing.origin()),
                        )
                    }
                }
            }
        }
    }
}

fn cuda_event_elapsed_ns(start: &CudaEvent, end: &CudaEvent) -> Option<u64> {
    let elapsed_ms =
        unsafe { cudarc::driver::result::event::elapsed(start.cu_event(), end.cu_event()) }.ok()?;
    if !elapsed_ms.is_finite() || elapsed_ms < 0.0 {
        return None;
    }
    let elapsed_ns = f64::from(elapsed_ms) * 1_000_000.0;
    (elapsed_ns <= u64::MAX as f64).then(|| elapsed_ns.round() as u64)
}

struct QuarantinedSubmission {
    stream_id: u64,
    _stream: Arc<CudaStream>,
    _blas: Arc<CudaBlas>,
    _commands: Vec<CudaDeviceCommand>,
}

#[cfg(feature = "vllm-marlin")]
const MXFP4_BLOCKS_TO_GPTQ_WORDS_FUNCTION: &str = "gpt_oss_mxfp4_blocks_to_gptq_words";
#[cfg(feature = "vllm-marlin")]
const MXFP4_SCALES_TO_MARLIN_FUNCTION: &str = "gpt_oss_mxfp4_scales_to_marlin";

#[cfg(feature = "vllm-marlin")]
#[derive(Clone)]
struct Mxfp4MarlinPrepareFunctions {
    blocks_to_gptq_words: CudaFunction,
    scales_to_marlin: CudaFunction,
}

#[cfg(feature = "vllm-marlin")]
impl Mxfp4MarlinPrepareFunctions {
    fn load(context: &Arc<CudaContext>) -> Result<Self, CudaDeviceRuntimeError> {
        let module = context
            .load_module(Ptx::from_src(crate::ptx::MXFP4_MARLIN_PREPARE.to_owned()))
            .map_err(|error| {
                CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 prepare module load", error)
            })?;
        let blocks_to_gptq_words = module
            .load_function(MXFP4_BLOCKS_TO_GPTQ_WORDS_FUNCTION)
            .map_err(|error| {
                CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 block transpose load", error)
            })?;
        let scales_to_marlin = module
            .load_function(MXFP4_SCALES_TO_MARLIN_FUNCTION)
            .map_err(|error| {
                CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 scale prepare load", error)
            })?;
        Ok(Self {
            blocks_to_gptq_words,
            scales_to_marlin,
        })
    }
}

/// Concrete CUDA primitive runtime consumed by the shared vNext resource and
/// operation dispatch layers.
pub struct CudaDeviceRuntime {
    descriptor: DeviceDescriptor,
    attention_execution_policy: AttentionExecutionPolicy,
    runtime_instance: u64,
    context: Arc<CudaContext>,
    allocation_stream: Arc<CudaStream>,
    #[cfg(feature = "vllm-marlin")]
    mxfp4_marlin_prepare: Mxfp4MarlinPrepareFunctions,
    quarantined: Mutex<Vec<QuarantinedSubmission>>,
}

impl fmt::Debug for CudaDeviceRuntime {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CudaDeviceRuntime")
            .field("descriptor", &self.descriptor)
            .field("runtime_instance", &self.runtime_instance)
            .finish_non_exhaustive()
    }
}

impl CudaDeviceRuntime {
    pub fn new(config: CudaDeviceRuntimeConfig) -> Result<Self, CudaDeviceRuntimeError> {
        if !config.attention_execution_policy.is_resolved() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA runtime requires a resolved attention execution policy",
            ));
        }
        let context = CudaContext::new(config.ordinal)
            .map_err(|error| CudaDeviceRuntimeError::driver("context creation", error))?;
        // vNext owns all cross-stream ordering through explicit commands and
        // fences. Per-slice implicit events would create a second authority.
        unsafe {
            context.disable_event_tracking();
        }
        let allocation_stream = context
            .new_stream()
            .map_err(|error| CudaDeviceRuntimeError::driver("allocation stream creation", error))?;
        #[cfg(feature = "vllm-marlin")]
        let mxfp4_marlin_prepare = Mxfp4MarlinPrepareFunctions::load(&context)?;
        let total_memory_bytes = u64::try_from(
            context
                .total_mem()
                .map_err(|error| CudaDeviceRuntimeError::driver("memory query", error))?,
        )
        .map_err(|_| CudaDeviceRuntimeError::contract("CUDA memory size exceeds u64"))?;
        let ordinal = u32::try_from(config.ordinal)
            .map_err(|_| CudaDeviceRuntimeError::contract("CUDA ordinal exceeds u32"))?;
        let descriptor = DeviceDescriptor {
            id: config.device_id,
            class: DeviceClass::Accelerator,
            ordinal,
            total_memory_bytes,
            runtime_implementation_fingerprint: config.runtime_implementation_fingerprint,
            capabilities: config.capabilities,
            dynamic_storage_profiles: config.dynamic_storage_profiles,
        };
        descriptor
            .validate()
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
        let runtime_instance = NEXT_RUNTIME_INSTANCE
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                current.checked_add(1)
            })
            .map_err(|_| CudaDeviceRuntimeError::contract("CUDA runtime identity exhausted"))?;
        Ok(Self {
            descriptor,
            attention_execution_policy: config.attention_execution_policy,
            runtime_instance,
            context,
            allocation_stream,
            #[cfg(feature = "vllm-marlin")]
            mxfp4_marlin_prepare,
            quarantined: Mutex::new(Vec::new()),
        })
    }

    pub(super) fn context(&self) -> &Arc<CudaContext> {
        &self.context
    }

    fn validate_buffer(&self, buffer: &CudaDeviceBuffer) -> Result<(), CudaDeviceRuntimeError> {
        if buffer.runtime_instance != self.runtime_instance {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA buffer belongs to another runtime instance",
            ));
        }
        Ok(())
    }

    fn validate_stream(&self, stream: &CudaDeviceStream) -> Result<(), CudaDeviceRuntimeError> {
        if stream.runtime_instance != self.runtime_instance {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA stream belongs to another runtime instance",
            ));
        }
        Ok(())
    }

    fn quarantined(&self) -> MutexGuard<'_, Vec<QuarantinedSubmission>> {
        self.quarantined
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn quarantine(&self, stream: &CudaDeviceStream, commands: Vec<CudaDeviceCommand>) {
        self.quarantined().push(QuarantinedSubmission {
            stream_id: stream.id,
            _stream: Arc::clone(&stream.stream),
            _blas: Arc::clone(&stream.blas),
            _commands: commands,
        });
    }

    fn release_quarantine(&self, stream_id: u64) {
        self.quarantined()
            .retain(|submission| submission.stream_id != stream_id);
    }
}

#[cfg(feature = "vllm-marlin")]
const BLOCK_FP8_GROUP128_STATIC_TRANSFORM_OPERATION: &str =
    "static_weight.block_fp8_to_marlin_fp8_group128";
#[cfg(feature = "vllm-marlin")]
const GPT_OSS_MXFP4_STATIC_TRANSFORM_OPERATION: &str = "static_weight.gpt_oss_mxfp4_to_marlin";

#[cfg(feature = "vllm-marlin")]
#[derive(Clone, Copy)]
struct BlockFp8Group128CudaTransform {
    size_n: u64,
    size_k: u64,
    matrices_per_output: usize,
    source_matrix_count: usize,
    output_matrix_count: usize,
    value_matrix_bytes: u64,
    source_scale_matrix_bytes: u64,
    packed_matrix_bytes: u64,
    scale_matrix_bytes: u64,
}

#[cfg(feature = "vllm-marlin")]
#[derive(Clone, Copy)]
struct GptOssMxfp4CudaTransform {
    expert_count: u64,
    size_n: i32,
    logical_size_k: i32,
    execution_size_k: i32,
    execution_expert_packed_bytes: u64,
    execution_expert_scale_bytes: u64,
    source_expert_packed_host_bytes: usize,
    source_expert_scale_host_bytes: usize,
    packed_grid: u32,
    scale_grid: u32,
}

#[cfg(feature = "vllm-marlin")]
fn checked_product(
    values: impl IntoIterator<Item = u64>,
    context: &'static str,
) -> Result<u64, CudaDeviceRuntimeError> {
    values.into_iter().try_fold(1_u64, |product, value| {
        product
            .checked_mul(value)
            .ok_or_else(|| CudaDeviceRuntimeError::contract(format!("{context} overflows u64")))
    })
}

#[cfg(feature = "vllm-marlin")]
fn validate_static_transform_regions(
    packed: &CudaBufferRegion,
    scales: &CudaBufferRegion,
    scratch: &CudaBufferRegion,
) -> Result<(), CudaDeviceRuntimeError> {
    if packed.device_ptr() % 4 != 0 || scales.device_ptr() % 2 != 0 || scratch.device_ptr() % 4 != 0
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA static weight transform has a misaligned packed, scale, or scratch address",
        ));
    }
    let regions = [packed, scales, scratch];
    for left in 0..regions.len() {
        let left_end = regions[left]
            .device_ptr()
            .checked_add(regions[left].length_bytes())
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract(
                    "CUDA static weight transform region address overflows",
                )
            })?;
        for right in left + 1..regions.len() {
            let right_end = regions[right]
                .device_ptr()
                .checked_add(regions[right].length_bytes())
                .ok_or_else(|| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA static weight transform region address overflows",
                    )
                })?;
            if regions[left].device_ptr() < right_end && regions[right].device_ptr() < left_end {
                return Err(CudaDeviceRuntimeError::contract(
                    "CUDA static weight transform packed, scale, and scratch regions must not overlap",
                ));
            }
        }
    }
    Ok(())
}

#[cfg(feature = "vllm-marlin")]
fn encode_block_fp8_group128_static_transform(
    runtime: &CudaDeviceRuntime,
    request: StaticWeightTransformRequest<'_, '_, CudaDeviceBuffer>,
) -> Result<CudaDeviceCommand, CudaDeviceRuntimeError> {
    let (
        source_values_id,
        source_scales_id,
        packed_values_id,
        scales_id,
        logical_dimensions,
        matrices_per_output,
    ) = match request.plan() {
        StaticWeightTransformPlan::BlockFp8ToMarlinFp8Group128 {
            source_values_id,
            source_scales_id,
            packed_values_id,
            scales_id,
            logical_dimensions,
            matrices_per_output,
        } => (
            source_values_id,
            source_scales_id,
            packed_values_id,
            scales_id,
            logical_dimensions,
            *matrices_per_output,
        ),
        StaticWeightTransformPlan::GptOssMxfp4ToMarlin { .. } => {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA block-FP8 encoder received a GPT-OSS MXFP4 transform plan",
            ));
        }
    };

    if logical_dimensions.len() < 2 || !matches!(matrices_per_output, 1 | 2) {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform has an unsupported rank or fusion count",
        ));
    }
    let rank = logical_dimensions.len();
    let size_n = logical_dimensions[rank - 2];
    let size_k = logical_dimensions[rank - 1];
    if size_n == 0
        || size_k == 0
        || !size_n.is_multiple_of(128)
        || !size_k.is_multiple_of(128)
        || (matrices_per_output == 2 && (rank < 4 || logical_dimensions[rank - 3] != 2))
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform requires positive 128-aligned matrices and typed gate/up fusion",
        ));
    }

    let source_matrix_count_u64 = checked_product(
        logical_dimensions[..rank - 2].iter().copied(),
        "CUDA block-FP8 source matrix count",
    )?;
    if !source_matrix_count_u64.is_multiple_of(u64::from(matrices_per_output)) {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 source matrix count is not divisible by its fusion count",
        ));
    }
    let source_matrix_count = checked_usize(
        source_matrix_count_u64,
        "CUDA block-FP8 source matrix count",
    )?;
    let matrices_per_output = usize::try_from(matrices_per_output).expect("1 or 2 fits usize");
    let output_matrix_count = source_matrix_count / matrices_per_output;
    if output_matrix_count == 0 {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform has no output matrix",
        ));
    }

    let value_matrix_bytes = size_n.checked_mul(size_k).ok_or_else(|| {
        CudaDeviceRuntimeError::contract("CUDA block-FP8 matrix byte size overflows u64")
    })?;
    let source_scale_matrix_bytes = (size_n / 128)
        .checked_mul(size_k / 128)
        .and_then(|elements| elements.checked_mul(ElementType::Bf16.size_bytes()))
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA block-FP8 source scale matrix byte size overflows u64",
            )
        })?;
    let fused_n = size_n
        .checked_mul(matrices_per_output as u64)
        .ok_or_else(|| CudaDeviceRuntimeError::contract("CUDA block-FP8 fused N overflows u64"))?;
    let packed_matrix_bytes = fused_n.checked_mul(size_k).ok_or_else(|| {
        CudaDeviceRuntimeError::contract("CUDA block-FP8 packed matrix byte size overflows u64")
    })?;
    let scale_matrix_bytes = fused_n
        .checked_mul(size_k / 128)
        .and_then(|elements| elements.checked_mul(ElementType::F16.size_bytes()))
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA block-FP8 destination scale matrix byte size overflows u64",
            )
        })?;
    let packed_total_bytes = packed_matrix_bytes
        .checked_mul(output_matrix_count as u64)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract("CUDA block-FP8 packed stack size overflows u64")
        })?;
    let scales_total_bytes = scale_matrix_bytes
        .checked_mul(output_matrix_count as u64)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract("CUDA block-FP8 scale stack size overflows u64")
        })?;

    let sources = request.sources();
    let destinations = request.destinations();
    if sources.len() != 2
        || destinations.len() != 2
        || sources[0].component_id() != source_values_id
        || sources[1].component_id() != source_scales_id
        || destinations[0].component().id != *packed_values_id
        || destinations[1].component().id != *scales_id
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform source or destination identity/order differs from its plan",
        ));
    }

    let mut expected_source_scale_dimensions = logical_dimensions.clone();
    expected_source_scale_dimensions[rank - 2] /= 128;
    expected_source_scale_dimensions[rank - 1] /= 128;
    let mut expected_destination_scale_dimensions = logical_dimensions.clone();
    expected_destination_scale_dimensions[rank - 1] /= 128;
    if sources[0].dimensions() != logical_dimensions.as_slice()
        || sources[1].dimensions() != expected_source_scale_dimensions.as_slice()
        || destinations[0].component().dimensions != *logical_dimensions
        || destinations[1].component().dimensions != expected_destination_scale_dimensions
        || sources[0].element_type() != ElementType::U8
        || sources[1].element_type() != ElementType::Bf16
        || destinations[0].component().physical_element_type() != ElementType::U8
        || destinations[1].component().physical_element_type() != ElementType::F16
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform source/destination shape or element type differs from the group-128 ABI",
        ));
    }
    let source_values_total_bytes = value_matrix_bytes
        .checked_mul(source_matrix_count_u64)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract("CUDA block-FP8 source stack size overflows u64")
        })?;
    let source_scales_total_bytes = source_scale_matrix_bytes
        .checked_mul(source_matrix_count_u64)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract("CUDA block-FP8 source scale stack size overflows u64")
        })?;
    if sources[0].total_bytes() != source_values_total_bytes
        || sources[1].total_bytes() != source_scales_total_bytes
        || destinations[0]
            .component()
            .physical_bytes()
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?
            != packed_total_bytes
        || destinations[1]
            .component()
            .physical_bytes()
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?
            != scales_total_bytes
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform component byte extents differ from the exact product ABI",
        ));
    }

    let value_segment_bytes =
        checked_usize(value_matrix_bytes, "CUDA block-FP8 value segment byte size")?;
    let scale_segment_bytes = checked_usize(
        source_scale_matrix_bytes,
        "CUDA block-FP8 scale segment byte size",
    )?;
    if sources[0].segments().len() != source_matrix_count
        || sources[1].segments().len() != source_matrix_count
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform requires one ordered retained source segment per matrix",
        ));
    }
    let mut retained_sources = Vec::with_capacity(source_matrix_count.saturating_mul(2));
    for (matrix, segment) in sources[0].segments().iter().enumerate() {
        let retained = segment.retained_host_memory().ok_or_else(|| {
            CudaDeviceRuntimeError::contract(format!(
                "CUDA block-FP8 value matrix {matrix} lacks retained stable host memory"
            ))
        })?;
        if segment.bytes().len() != value_segment_bytes
            || retained.length_bytes() != value_segment_bytes
            || !std::ptr::eq(segment.bytes().as_ptr(), retained.bytes().as_ptr())
        {
            return Err(CudaDeviceRuntimeError::contract(format!(
                "CUDA block-FP8 value matrix {matrix} segment differs from its exact retained range"
            )));
        }
        retained_sources.push(retained.clone());
    }
    for (matrix, segment) in sources[1].segments().iter().enumerate() {
        let retained = segment.retained_host_memory().ok_or_else(|| {
            CudaDeviceRuntimeError::contract(format!(
                "CUDA block-FP8 scale matrix {matrix} lacks retained stable host memory"
            ))
        })?;
        if segment.bytes().len() != scale_segment_bytes
            || retained.length_bytes() != scale_segment_bytes
            || !std::ptr::eq(segment.bytes().as_ptr(), retained.bytes().as_ptr())
        {
            return Err(CudaDeviceRuntimeError::contract(format!(
                "CUDA block-FP8 scale matrix {matrix} segment differs from its exact retained range"
            )));
        }
        for (block, bytes) in segment.bytes().chunks_exact(2).enumerate() {
            let inverse_scale = half::bf16::from_le_bytes([bytes[0], bytes[1]]).to_f32();
            let marlin_scale = half::f16::from_f32(inverse_scale * 256.0);
            if !inverse_scale.is_finite()
                || inverse_scale <= 0.0
                || !marlin_scale.is_finite()
                || marlin_scale == half::f16::ZERO
            {
                return Err(CudaDeviceRuntimeError::contract(format!(
                    "CUDA block-FP8 scale matrix {matrix} block {block} cannot be represented by the group-128 Marlin F16 ABI"
                )));
            }
        }
        retained_sources.push(retained.clone());
    }

    let packed_destination = &destinations[0];
    let scales_destination = &destinations[1];
    let scratch = request.scratch();
    runtime.validate_buffer(packed_destination.buffer())?;
    runtime.validate_buffer(scales_destination.buffer())?;
    runtime.validate_buffer(scratch)?;
    if packed_destination.buffer().descriptor.element_type != ElementType::U8
        || scales_destination.buffer().descriptor.element_type != ElementType::F16
        || scratch.descriptor.element_type != ElementType::U8
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform buffer element types differ from U8/F16/U8",
        ));
    }
    let admitted_scratch_bytes = request
        .plan()
        .scratch_bytes()
        .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
    if admitted_scratch_bytes != packed_matrix_bytes
        || scratch.descriptor.size_bytes < admitted_scratch_bytes
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform scratch differs from its single fused-matrix plan",
        ));
    }
    let packed_end = checked_end(
        packed_destination.destination_offset_bytes(),
        packed_total_bytes,
        packed_destination.buffer().descriptor.size_bytes,
        "CUDA block-FP8 packed destination",
    )?;
    let scales_end = checked_end(
        scales_destination.destination_offset_bytes(),
        scales_total_bytes,
        scales_destination.buffer().descriptor.size_bytes,
        "CUDA block-FP8 scales destination",
    )?;
    let packed_region = packed_destination
        .buffer()
        .region(packed_destination.destination_offset_bytes()..packed_end)?;
    let scales_region = scales_destination
        .buffer()
        .region(scales_destination.destination_offset_bytes()..scales_end)?;
    let scratch_region = scratch.region(0..admitted_scratch_bytes)?;
    validate_static_transform_regions(&packed_region, &scales_region, &scratch_region)?;

    let transform = BlockFp8Group128CudaTransform {
        size_n,
        size_k,
        matrices_per_output,
        source_matrix_count,
        output_matrix_count,
        value_matrix_bytes,
        source_scale_matrix_bytes,
        packed_matrix_bytes,
        scale_matrix_bytes,
    };
    let compute_dispatch_count = (output_matrix_count as u64).checked_mul(2).ok_or_else(|| {
        CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform dispatch count overflows u64",
        )
    })?;
    let transfer_command_count = source_matrix_count_u64.checked_mul(2).ok_or_else(|| {
        CudaDeviceRuntimeError::contract(
            "CUDA block-FP8 static transform transfer count overflows u64",
        )
    })?;
    let command = CudaDeviceCommand::operation(
        BLOCK_FP8_GROUP128_STATIC_TRANSFORM_OPERATION,
        vec![packed_region, scales_region, scratch_region],
        move |stream, regions| {
            debug_assert_eq!(regions.len(), 3);
            for output_matrix in 0..transform.output_matrix_count {
                for matrix_lane in 0..transform.matrices_per_output {
                    let source_matrix = output_matrix * transform.matrices_per_output + matrix_lane;
                    let scratch_offset = (matrix_lane as u64)
                        .checked_mul(transform.value_matrix_bytes)
                        .ok_or_else(|| {
                            CudaDeviceRuntimeError::contract(
                                "CUDA block-FP8 scratch value offset overflows",
                            )
                        })?;
                    let scratch_pointer = regions[2]
                        .device_ptr()
                        .checked_add(scratch_offset)
                        .ok_or_else(|| {
                            CudaDeviceRuntimeError::contract(
                                "CUDA block-FP8 scratch value pointer overflows",
                            )
                        })?;
                    unsafe {
                        cudarc::driver::result::memcpy_htod_async(
                            scratch_pointer,
                            retained_sources[source_matrix].bytes(),
                            stream.cu_stream(),
                        )
                    }
                    .map_err(|error| {
                        CudaDeviceRuntimeError::driver("block-FP8 value upload", error)
                    })?;
                }
                let packed_offset = (output_matrix as u64)
                    .checked_mul(transform.packed_matrix_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA block-FP8 packed destination offset overflows",
                        )
                    })?;
                let packed_pointer = regions[0]
                    .device_ptr()
                    .checked_add(packed_offset)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA block-FP8 packed destination pointer overflows",
                        )
                    })?;
                unsafe {
                    super::vllm_marlin::launch_block_fp8_group128_repack(
                        stream,
                        regions[2].device_ptr(),
                        packed_pointer,
                        transform.size_k,
                        transform.size_n * transform.matrices_per_output as u64,
                    )
                }
                .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;

                for matrix_lane in 0..transform.matrices_per_output {
                    let source_matrix = output_matrix * transform.matrices_per_output + matrix_lane;
                    let scratch_offset = (matrix_lane as u64)
                        .checked_mul(transform.source_scale_matrix_bytes)
                        .ok_or_else(|| {
                            CudaDeviceRuntimeError::contract(
                                "CUDA block-FP8 scratch scale offset overflows",
                            )
                        })?;
                    let scratch_pointer = regions[2]
                        .device_ptr()
                        .checked_add(scratch_offset)
                        .ok_or_else(|| {
                            CudaDeviceRuntimeError::contract(
                                "CUDA block-FP8 scratch scale pointer overflows",
                            )
                        })?;
                    unsafe {
                        cudarc::driver::result::memcpy_htod_async(
                            scratch_pointer,
                            retained_sources[transform.source_matrix_count + source_matrix].bytes(),
                            stream.cu_stream(),
                        )
                    }
                    .map_err(|error| {
                        CudaDeviceRuntimeError::driver("block-FP8 scale upload", error)
                    })?;
                }
                let scales_offset = (output_matrix as u64)
                    .checked_mul(transform.scale_matrix_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA block-FP8 scale destination offset overflows",
                        )
                    })?;
                let scales_pointer = regions[1]
                    .device_ptr()
                    .checked_add(scales_offset)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA block-FP8 scale destination pointer overflows",
                        )
                    })?;
                unsafe {
                    super::vllm_marlin::launch_block_fp8_group128_scales(
                        stream,
                        regions[2].device_ptr(),
                        scales_pointer,
                        transform.size_k,
                        transform.size_n * transform.matrices_per_output as u64,
                    )
                }
                .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
            }
            Ok(())
        },
    )?;
    command.with_initialization_native_work(compute_dispatch_count, transfer_command_count)
}

#[cfg(feature = "vllm-marlin")]
fn encode_gpt_oss_mxfp4_static_transform(
    runtime: &CudaDeviceRuntime,
    request: StaticWeightTransformRequest<'_, '_, CudaDeviceBuffer>,
) -> Result<CudaDeviceCommand, CudaDeviceRuntimeError> {
    let (
        source_blocks_id,
        source_scales_id,
        packed_values_id,
        scales_id,
        logical_dimensions,
        execution_dimensions,
    ) = match request.plan() {
        StaticWeightTransformPlan::GptOssMxfp4ToMarlin {
            source_blocks_id,
            source_scales_id,
            packed_values_id,
            scales_id,
            logical_dimensions,
            execution_dimensions,
        } => (
            source_blocks_id,
            source_scales_id,
            packed_values_id,
            scales_id,
            logical_dimensions,
            execution_dimensions,
        ),
        StaticWeightTransformPlan::BlockFp8ToMarlinFp8Group128 { .. } => {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 encoder received a block-FP8 transform plan",
            ));
        }
    };
    let [expert_count, size_n_u64, logical_size_k_u64] = logical_dimensions.as_slice() else {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform requires exact [E,N,K] dimensions",
        ));
    };
    let [execution_expert_count, execution_size_n_u64, execution_size_k_u64] =
        execution_dimensions.as_slice()
    else {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform requires exact [E,N,K] execution dimensions",
        ));
    };
    let expert_count = *expert_count;
    let size_n_u64 = *size_n_u64;
    let logical_size_k_u64 = *logical_size_k_u64;
    let execution_size_k_u64 = *execution_size_k_u64;
    if expert_count == 0
        || size_n_u64 == 0
        || logical_size_k_u64 == 0
        || !size_n_u64.is_multiple_of(64)
        || !logical_size_k_u64.is_multiple_of(64)
        || execution_expert_count != &expert_count
        || execution_size_n_u64 != &size_n_u64
        || execution_size_k_u64 < logical_size_k_u64
        || !execution_size_k_u64.is_multiple_of(64)
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform requires matching logical/execution E,N and non-shrinking 64-aligned K",
        ));
    }
    let size_n = i32::try_from(size_n_u64)
        .map_err(|_| CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 N exceeds native i32"))?;
    let logical_size_k = i32::try_from(logical_size_k_u64).map_err(|_| {
        CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 logical K exceeds native i32")
    })?;
    let execution_size_k = i32::try_from(execution_size_k_u64).map_err(|_| {
        CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 execution K exceeds native i32")
    })?;
    let source_expert_packed_bytes = size_n_u64
        .checked_mul(logical_size_k_u64)
        .and_then(|elements| elements.checked_div(2))
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 source expert packed byte size overflows u64",
            )
        })?;
    let source_expert_scale_bytes =
        size_n_u64
            .checked_mul(logical_size_k_u64 / 32)
            .ok_or_else(|| {
                CudaDeviceRuntimeError::contract(
                    "CUDA GPT-OSS MXFP4 source expert scale byte size overflows u64",
                )
            })?;
    let execution_expert_packed_bytes = size_n_u64
        .checked_mul(execution_size_k_u64)
        .and_then(|elements| elements.checked_div(2))
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 execution expert packed byte size overflows u64",
            )
        })?;
    let execution_expert_scale_bytes = size_n_u64
        .checked_mul(execution_size_k_u64 / 32)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 execution expert scale byte size overflows u64",
            )
        })?;
    let source_packed_total_bytes = source_expert_packed_bytes
        .checked_mul(expert_count)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 source packed stack size overflows u64",
            )
        })?;
    let source_scales_total_bytes = source_expert_scale_bytes
        .checked_mul(expert_count)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 source scale stack size overflows u64",
            )
        })?;
    let execution_packed_total_bytes = execution_expert_packed_bytes
        .checked_mul(expert_count)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 execution packed stack size overflows u64",
            )
        })?;
    let execution_scales_total_bytes = execution_expert_scale_bytes
        .checked_mul(expert_count)
        .ok_or_else(|| {
            CudaDeviceRuntimeError::contract(
                "CUDA GPT-OSS MXFP4 execution scale stack size overflows u64",
            )
        })?;

    let sources = request.sources();
    let destinations = request.destinations();
    if sources.len() != 2
        || destinations.len() != 2
        || sources[0].component_id() != source_blocks_id
        || sources[1].component_id() != source_scales_id
        || destinations[0].component().id != *packed_values_id
        || destinations[1].component().id != *scales_id
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform source or destination identity/order differs from its plan",
        ));
    }
    let expected_source_blocks_dimensions = [expert_count, size_n_u64, logical_size_k_u64 / 32, 16];
    let expected_source_scales_dimensions = [expert_count, size_n_u64, logical_size_k_u64 / 32];
    let expected_execution_packed_dimensions = [expert_count, size_n_u64, execution_size_k_u64 / 2];
    let expected_execution_scales_dimensions =
        [expert_count, size_n_u64, execution_size_k_u64 / 32];
    if sources[0].dimensions() != expected_source_blocks_dimensions
        || sources[1].dimensions() != expected_source_scales_dimensions
        || destinations[0].component().dimensions != expected_execution_packed_dimensions
        || destinations[1].component().dimensions != expected_execution_scales_dimensions
        || sources[0].element_type() != ElementType::U8
        || sources[1].element_type() != ElementType::U8
        || destinations[0].component().physical_element_type() != ElementType::U8
        || destinations[1].component().physical_element_type() != ElementType::U8
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform shape or element type differs from the exact source/Marlin ABI",
        ));
    }
    if sources[0].total_bytes() != source_packed_total_bytes
        || sources[1].total_bytes() != source_scales_total_bytes
        || destinations[0]
            .component()
            .physical_bytes()
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?
            != execution_packed_total_bytes
        || destinations[1]
            .component()
            .physical_bytes()
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?
            != execution_scales_total_bytes
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform component byte extents differ from the exact ABI",
        ));
    }
    if sources[0].segments().len() != 1 || sources[1].segments().len() != 1 {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform requires one retained mmap segment per source tensor",
        ));
    }
    let block_segment = &sources[0].segments()[0];
    let scale_segment = &sources[1].segments()[0];
    let retained_blocks = block_segment.retained_host_memory().ok_or_else(|| {
        CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 blocks lack retained stable host memory",
        )
    })?;
    let retained_scales = scale_segment.retained_host_memory().ok_or_else(|| {
        CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 scales lack retained stable host memory",
        )
    })?;
    let packed_total_host_bytes = checked_usize(
        source_packed_total_bytes,
        "CUDA GPT-OSS MXFP4 packed source byte size",
    )?;
    let scales_total_host_bytes = checked_usize(
        source_scales_total_bytes,
        "CUDA GPT-OSS MXFP4 scale source byte size",
    )?;
    if block_segment.bytes().len() != packed_total_host_bytes
        || retained_blocks.length_bytes() != packed_total_host_bytes
        || !std::ptr::eq(
            block_segment.bytes().as_ptr(),
            retained_blocks.bytes().as_ptr(),
        )
        || scale_segment.bytes().len() != scales_total_host_bytes
        || retained_scales.length_bytes() != scales_total_host_bytes
        || !std::ptr::eq(
            scale_segment.bytes().as_ptr(),
            retained_scales.bytes().as_ptr(),
        )
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 source segments differ from their retained mmap ranges",
        ));
    }

    let packed_destination = &destinations[0];
    let scales_destination = &destinations[1];
    let scratch = request.scratch();
    runtime.validate_buffer(packed_destination.buffer())?;
    runtime.validate_buffer(scales_destination.buffer())?;
    runtime.validate_buffer(scratch)?;
    if packed_destination.buffer().descriptor.element_type != ElementType::U8
        || scales_destination.buffer().descriptor.element_type != ElementType::U8
        || scratch.descriptor.element_type != ElementType::U8
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 transform buffers must all use U8 storage",
        ));
    }
    let admitted_scratch_bytes = request
        .plan()
        .scratch_bytes()
        .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
    if admitted_scratch_bytes != execution_expert_packed_bytes
        || scratch.descriptor.size_bytes < admitted_scratch_bytes
    {
        return Err(CudaDeviceRuntimeError::contract(
            "CUDA GPT-OSS MXFP4 scratch differs from its one-expert bounded plan",
        ));
    }
    let packed_end = checked_end(
        packed_destination.destination_offset_bytes(),
        execution_packed_total_bytes,
        packed_destination.buffer().descriptor.size_bytes,
        "CUDA GPT-OSS MXFP4 packed destination",
    )?;
    let scales_end = checked_end(
        scales_destination.destination_offset_bytes(),
        execution_scales_total_bytes,
        scales_destination.buffer().descriptor.size_bytes,
        "CUDA GPT-OSS MXFP4 scales destination",
    )?;
    let packed_region = packed_destination
        .buffer()
        .region(packed_destination.destination_offset_bytes()..packed_end)?;
    let scales_region = scales_destination
        .buffer()
        .region(scales_destination.destination_offset_bytes()..scales_end)?;
    let scratch_region = scratch.region(0..admitted_scratch_bytes)?;
    validate_static_transform_regions(&packed_region, &scales_region, &scratch_region)?;

    let packed_word_count = execution_expert_packed_bytes / 4;
    let packed_grid = u32::try_from(packed_word_count.div_ceil(256)).map_err(|_| {
        CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 packed grid exceeds u32")
    })?;
    let scale_grid = u32::try_from(execution_expert_scale_bytes.div_ceil(256)).map_err(|_| {
        CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 scale grid exceeds u32")
    })?;
    let transform = GptOssMxfp4CudaTransform {
        expert_count,
        size_n,
        logical_size_k,
        execution_size_k,
        execution_expert_packed_bytes,
        execution_expert_scale_bytes,
        source_expert_packed_host_bytes: checked_usize(
            source_expert_packed_bytes,
            "CUDA GPT-OSS MXFP4 source expert packed byte size",
        )?,
        source_expert_scale_host_bytes: checked_usize(
            source_expert_scale_bytes,
            "CUDA GPT-OSS MXFP4 source expert scale byte size",
        )?,
        packed_grid,
        scale_grid,
    };
    let compute_dispatch_count = expert_count.checked_mul(3).ok_or_else(|| {
        CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 dispatch count overflows u64")
    })?;
    let transfer_command_count = expert_count.checked_mul(2).ok_or_else(|| {
        CudaDeviceRuntimeError::contract("CUDA GPT-OSS MXFP4 transfer count overflows u64")
    })?;
    let retained_blocks = retained_blocks.clone();
    let retained_scales = retained_scales.clone();
    let functions = runtime.mxfp4_marlin_prepare.clone();
    let command = CudaDeviceCommand::operation(
        GPT_OSS_MXFP4_STATIC_TRANSFORM_OPERATION,
        vec![packed_region, scales_region, scratch_region],
        move |stream, regions| {
            debug_assert_eq!(regions.len(), 3);
            for expert in 0..transform.expert_count {
                let packed_offset = expert
                    .checked_mul(transform.execution_expert_packed_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 expert packed offset overflows",
                        )
                    })?;
                let scale_offset = expert
                    .checked_mul(transform.execution_expert_scale_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 expert scale offset overflows",
                        )
                    })?;
                let packed_pointer = regions[0]
                    .device_ptr()
                    .checked_add(packed_offset)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 packed pointer overflows",
                        )
                    })?;
                let scale_pointer = regions[1]
                    .device_ptr()
                    .checked_add(scale_offset)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 scale pointer overflows",
                        )
                    })?;
                let expert_index = usize::try_from(expert).map_err(|_| {
                    CudaDeviceRuntimeError::contract(
                        "CUDA GPT-OSS MXFP4 expert index exceeds host address space",
                    )
                })?;
                let block_start = expert_index
                    .checked_mul(transform.source_expert_packed_host_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 host block offset overflows",
                        )
                    })?;
                let block_end = block_start
                    .checked_add(transform.source_expert_packed_host_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 host block end overflows",
                        )
                    })?;
                unsafe {
                    cudarc::driver::result::memcpy_htod_async(
                        packed_pointer,
                        &retained_blocks.bytes()[block_start..block_end],
                        stream.cu_stream(),
                    )
                }
                .map_err(|error| {
                    CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 block upload", error)
                })?;
                let scratch_pointer = regions[2].device_ptr();
                let mut transpose = stream.launch_builder(&functions.blocks_to_gptq_words);
                transpose.arg(&packed_pointer);
                transpose.arg(&scratch_pointer);
                transpose.arg(&transform.size_n);
                transpose.arg(&transform.logical_size_k);
                transpose.arg(&transform.execution_size_k);
                unsafe {
                    transpose.launch(LaunchConfig {
                        grid_dim: (transform.packed_grid, 1, 1),
                        block_dim: (256, 1, 1),
                        shared_mem_bytes: 0,
                    })
                }
                .map_err(|error| {
                    CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 block transpose", error)
                })?;
                unsafe {
                    super::vllm_marlin::vllm_gptq_marlin_repack_raw(
                        stream,
                        scratch_pointer,
                        packed_pointer,
                        transform.execution_size_k,
                        transform.size_n,
                    )
                }
                .map_err(|error| {
                    CudaDeviceRuntimeError::contract(format!(
                        "GPT-OSS MXFP4 native Marlin repack failed: {error}"
                    ))
                })?;

                let scale_start = expert_index
                    .checked_mul(transform.source_expert_scale_host_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 host scale offset overflows",
                        )
                    })?;
                let scale_end = scale_start
                    .checked_add(transform.source_expert_scale_host_bytes)
                    .ok_or_else(|| {
                        CudaDeviceRuntimeError::contract(
                            "CUDA GPT-OSS MXFP4 host scale end overflows",
                        )
                    })?;
                unsafe {
                    cudarc::driver::result::memcpy_htod_async(
                        scratch_pointer,
                        &retained_scales.bytes()[scale_start..scale_end],
                        stream.cu_stream(),
                    )
                }
                .map_err(|error| {
                    CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 scale upload", error)
                })?;
                let mut scales = stream.launch_builder(&functions.scales_to_marlin);
                scales.arg(&scratch_pointer);
                scales.arg(&scale_pointer);
                scales.arg(&transform.size_n);
                scales.arg(&transform.logical_size_k);
                scales.arg(&transform.execution_size_k);
                unsafe {
                    scales.launch(LaunchConfig {
                        grid_dim: (transform.scale_grid, 1, 1),
                        block_dim: (256, 1, 1),
                        shared_mem_bytes: 0,
                    })
                }
                .map_err(|error| {
                    CudaDeviceRuntimeError::driver("GPT-OSS MXFP4 scale prepare", error)
                })?;
            }
            Ok(())
        },
    )?;
    command.with_initialization_native_work(compute_dispatch_count, transfer_command_count)
}

fn checked_usize(value: u64, context: &'static str) -> Result<usize, CudaDeviceRuntimeError> {
    usize::try_from(value).map_err(|_| {
        CudaDeviceRuntimeError::contract(format!("{context} exceeds host address space"))
    })
}

fn checked_end(
    offset: u64,
    length: u64,
    capacity: u64,
    context: &'static str,
) -> Result<u64, CudaDeviceRuntimeError> {
    let end = offset
        .checked_add(length)
        .ok_or_else(|| CudaDeviceRuntimeError::contract(format!("{context} range overflows")))?;
    if length == 0 || end > capacity {
        return Err(CudaDeviceRuntimeError::contract(format!(
            "{context} range is empty or outside its buffer"
        )));
    }
    Ok(end)
}

impl DeviceRuntime for CudaDeviceRuntime {
    type Buffer = CudaDeviceBuffer;
    type Stream = CudaDeviceStream;
    type Command = CudaDeviceCommand;
    type Fence = CudaDeviceFence;
    type Error = CudaDeviceRuntimeError;

    fn descriptor(&self) -> &DeviceDescriptor {
        &self.descriptor
    }

    fn attention_execution_policy(&self) -> AttentionExecutionPolicy {
        self.attention_execution_policy
    }

    fn allocate(
        &self,
        permit: ferrum_interfaces::vnext::DeviceAllocationPermit<'_>,
    ) -> Result<Self::Buffer, Self::Error> {
        let request = permit.into_request();
        let extra_alignment = request
            .alignment_bytes()
            .checked_sub(1)
            .ok_or_else(|| CudaDeviceRuntimeError::contract("CUDA allocation alignment is zero"))?;
        let allocation_bytes = request
            .size_bytes()
            .checked_add(extra_alignment)
            .ok_or_else(|| CudaDeviceRuntimeError::contract("CUDA allocation size overflows"))?;
        let allocation_bytes = checked_usize(allocation_bytes, "CUDA allocation size")?;
        let base = unsafe { self.allocation_stream.alloc::<u8>(allocation_bytes) }
            .map_err(|error| CudaDeviceRuntimeError::driver("allocation", error))?;
        let (base_ptr, base_use) = base.device_ptr(&self.allocation_stream);
        drop(base_use);
        let alignment = request.alignment_bytes();
        let aligned_ptr = base_ptr
            .checked_add(alignment - 1)
            .map(|pointer| pointer & !(alignment - 1))
            .ok_or_else(|| CudaDeviceRuntimeError::contract("CUDA aligned pointer overflows"))?;
        self.allocation_stream
            .synchronize()
            .map_err(|error| CudaDeviceRuntimeError::driver("allocation synchronization", error))?;
        let descriptor = BufferDescriptor {
            resource_id: request.resource_id().clone(),
            size_bytes: request.size_bytes(),
            alignment_bytes: request.alignment_bytes(),
            usage: request.usage(),
            element_type: request.element_type(),
        };
        Ok(CudaDeviceBuffer {
            descriptor,
            runtime_instance: self.runtime_instance,
            allocation: Arc::new(CudaAllocation {
                _base: base,
                aligned_ptr,
                requested_bytes: request.size_bytes(),
            }),
        })
    }

    fn buffer_descriptor(&self, buffer: &Self::Buffer) -> BufferDescriptor {
        buffer.descriptor.clone()
    }

    fn encode_static_weight_transform(
        &self,
        request: StaticWeightTransformRequest<'_, '_, Self::Buffer>,
    ) -> Option<Result<Self::Command, Self::Error>> {
        #[cfg(feature = "vllm-marlin")]
        {
            Some(match request.plan() {
                StaticWeightTransformPlan::BlockFp8ToMarlinFp8Group128 { .. } => {
                    encode_block_fp8_group128_static_transform(self, request)
                }
                StaticWeightTransformPlan::GptOssMxfp4ToMarlin { .. } => {
                    encode_gpt_oss_mxfp4_static_transform(self, request)
                }
            })
        }
        #[cfg(not(feature = "vllm-marlin"))]
        {
            let _ = request;
            None
        }
    }

    fn create_stream(&self) -> Result<Self::Stream, Self::Error> {
        let id = NEXT_STREAM_INSTANCE
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                current.checked_add(1)
            })
            .map_err(|_| CudaDeviceRuntimeError::contract("CUDA stream identity exhausted"))?;
        let stream = self
            .context
            .new_stream()
            .map_err(|error| CudaDeviceRuntimeError::driver("stream creation", error))?;
        let blas = Arc::new(
            CudaBlas::new(Arc::clone(&stream))
                .map_err(|error| CudaDeviceRuntimeError::blas("cuBLAS handle creation", error))?,
        );
        Ok(CudaDeviceStream {
            id,
            runtime_instance: self.runtime_instance,
            stream,
            blas,
            state: Arc::new(CudaStreamState::new()),
            executable_cache: CudaExecutableCache::new(),
        })
    }

    fn stream_state(&self, stream: &Self::Stream) -> StreamState {
        if stream.runtime_instance != self.runtime_instance {
            return StreamState::Failed;
        }
        stream.state.snapshot()
    }

    fn configure_reusable_executables(
        &self,
        stream: &mut Self::Stream,
        plan: DeviceReusableExecutionPlan,
    ) -> Result<DeviceReusableExecutionPreparation, Self::Error> {
        self.validate_stream(stream)?;
        if !stream.state.is_quiescent() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA reusable executable preparation requires its quiescent owning stream",
            ));
        }
        stream
            .executable_cache
            .configure(plan)
            .map_err(CudaDeviceRuntimeError::contract)
    }

    fn seal_reusable_executables(
        &self,
        stream: &mut Self::Stream,
    ) -> Result<DeviceReusableExecutionPreparation, Self::Error> {
        self.validate_stream(stream)?;
        if !stream.state.is_quiescent() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA reusable executable sealing requires its quiescent owning stream",
            ));
        }
        stream
            .executable_cache
            .seal()
            .map_err(CudaDeviceRuntimeError::contract)
    }

    fn reusable_executable_preparation(
        &self,
        stream: &Self::Stream,
    ) -> Result<DeviceReusableExecutionPreparation, Self::Error> {
        self.validate_stream(stream)?;
        if !stream.state.is_quiescent() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA reusable executable inspection requires its quiescent owning stream",
            ));
        }
        stream
            .executable_cache
            .preparation()
            .map_err(CudaDeviceRuntimeError::contract)
    }

    fn reusable_execution_catalog(
        &self,
        stream: &Self::Stream,
    ) -> Result<Vec<DeviceReusableExecutionProgram>, Self::Error> {
        self.validate_stream(stream)?;
        if !stream.state.is_quiescent() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA reusable execution catalog requires its quiescent owning stream",
            ));
        }
        stream
            .executable_cache
            .catalog()
            .map_err(CudaDeviceRuntimeError::contract)
    }

    fn encode_reusable_execution(
        &self,
        invocation: DeviceReusableExecutionInvocation,
    ) -> Result<Option<Self::Command>, Self::Error> {
        if invocation.program_id().runtime_implementation_fingerprint()
            != self.descriptor.runtime_implementation_fingerprint
        {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA reusable execution reference targets another runtime implementation",
            ));
        }
        Ok(Some(CudaDeviceCommand::reusable_execution(
            self.runtime_instance,
            invocation,
        )))
    }

    fn trim_reusable_executables(
        &self,
        stream: &mut Self::Stream,
    ) -> Result<DeviceReusableExecutionTrim, Self::Error> {
        if stream.runtime_instance != self.runtime_instance || !stream.state.is_quiescent() {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA reusable executable trim requires its quiescent owning stream",
            ));
        }
        let (released_executables, released_rejections) = stream.executable_cache.trim_quiescent();
        Ok(DeviceReusableExecutionTrim::new(
            released_executables,
            released_rejections,
        ))
    }

    fn encode_copy(
        &self,
        source: &Self::Buffer,
        destination: &Self::Buffer,
        region: CopyRegion,
    ) -> Result<Self::Command, Self::Error> {
        self.validate_buffer(source)?;
        self.validate_buffer(destination)?;
        region
            .validate_bounds(&source.descriptor, &destination.descriptor)
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
        if source.descriptor.element_type != destination.descriptor.element_type {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA copy requires matching source and destination element types",
            ));
        }
        let source_region = source.region(
            region.source_offset_bytes()..region.source_offset_bytes() + region.length_bytes(),
        )?;
        let destination_region = destination.region(
            region.destination_offset_bytes()
                ..region.destination_offset_bytes() + region.length_bytes(),
        )?;
        let regions = vec![source_region, destination_region];
        Ok(CudaDeviceCommand::transfer(
            self.runtime_instance,
            DEVICE_COPY_NATIVE_OPERATION_ID.as_str(),
            regions,
            Vec::new(),
            Box::new(|stream, _blas, regions, _host_storage| {
                let bytes = checked_usize(regions[0].length_bytes, "CUDA copy length")?;
                unsafe {
                    cudarc::driver::result::memcpy_dtod_async(
                        regions[1].device_ptr,
                        regions[0].device_ptr,
                        bytes,
                        stream.cu_stream(),
                    )
                }
                .map_err(|error| CudaDeviceRuntimeError::driver("device copy", error))
            }),
        ))
    }

    fn encode_upload(
        &self,
        source: &[u8],
        source_layout: HostTransferLayout,
        destination: &Self::Buffer,
        destination_offset_bytes: u64,
    ) -> Result<Self::Command, Self::Error> {
        self.validate_buffer(destination)?;
        source_layout
            .validate_bytes(source.len())
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
        if source_layout.element_type() != destination.descriptor.element_type {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA upload layout differs from destination element type",
            ));
        }
        let source_bytes = u64::try_from(source.len())
            .map_err(|_| CudaDeviceRuntimeError::contract("CUDA upload size exceeds u64"))?;
        let destination_end = checked_end(
            destination_offset_bytes,
            source_bytes,
            destination.descriptor.size_bytes,
            "CUDA upload",
        )?;
        let destination_region = destination.region(destination_offset_bytes..destination_end)?;
        let host_storage = vec![source.to_vec().into_boxed_slice()];
        Ok(CudaDeviceCommand::transfer(
            self.runtime_instance,
            HOST_UPLOAD_NATIVE_OPERATION_ID.as_str(),
            vec![destination_region],
            host_storage,
            Box::new(|stream, _blas, regions, host_storage| {
                unsafe {
                    cudarc::driver::result::memcpy_htod_async(
                        regions[0].device_ptr,
                        host_storage[0].as_ref(),
                        stream.cu_stream(),
                    )
                }
                .map_err(|error| CudaDeviceRuntimeError::driver("host upload", error))
            }),
        ))
    }

    fn encode_zero(
        &self,
        destination: &Self::Buffer,
        destination_offset_bytes: u64,
        length_bytes: u64,
    ) -> Result<Self::Command, Self::Error> {
        self.validate_buffer(destination)?;
        let destination_end = checked_end(
            destination_offset_bytes,
            length_bytes,
            destination.descriptor.size_bytes,
            "CUDA zero",
        )?;
        let destination_region = destination.region(destination_offset_bytes..destination_end)?;
        Ok(CudaDeviceCommand::transfer(
            self.runtime_instance,
            DEVICE_ZERO_NATIVE_OPERATION_ID.as_str(),
            vec![destination_region],
            Vec::new(),
            Box::new(|stream, _blas, regions, _host_storage| {
                let bytes = checked_usize(regions[0].length_bytes, "CUDA zero length")?;
                unsafe {
                    cudarc::driver::result::memset_d8_async(
                        regions[0].device_ptr,
                        0,
                        bytes,
                        stream.cu_stream(),
                    )
                }
                .map_err(|error| CudaDeviceRuntimeError::driver("device zero", error))
            }),
        ))
    }

    fn coalesce_program_bindings(
        &self,
        commands: Vec<Self::Command>,
    ) -> Result<Vec<Self::Command>, Self::Error> {
        CudaDeviceCommand::coalesced_program_bindings(commands)
    }

    fn submit(
        &self,
        stream: &mut Self::Stream,
        commands: DeviceCommandBatch<Self::Command>,
    ) -> Result<Self::Fence, DefinitelyNotSubmitted<Self::Error>> {
        self.submit_with_timing(stream, commands, &DisabledDeviceSubmissionTimingSink)
    }

    fn submit_with_timing<S>(
        &self,
        stream: &mut Self::Stream,
        commands: DeviceCommandBatch<Self::Command>,
        timing_sink: &S,
    ) -> Result<Self::Fence, DefinitelyNotSubmitted<Self::Error>>
    where
        S: DeviceSubmissionTimingSink,
    {
        let validate_stage =
            CudaSubmissionStageTimer::start(timing_sink, DeviceSubmissionStage::ValidateAndPrepare);
        if let Err(error) = self.validate_stream(stream) {
            return Err(DefinitelyNotSubmitted::new(error));
        }
        if commands.is_empty() {
            return Err(DefinitelyNotSubmitted::new(
                CudaDeviceRuntimeError::contract("CUDA command batch is empty"),
            ));
        }
        let timing_mode = commands.timing_mode();
        let compute_path_requirement = commands.compute_path_requirement();
        let declared_eager_compute_node_indices = commands
            .declared_eager_compute_node_indices()
            .iter()
            .copied()
            .collect::<BTreeSet<_>>();
        let declared_eager_compute_node_count =
            commands.declared_eager_compute_node_indices().len();
        let logical_attribution = commands
            .attribution_requirement()
            .logical_execution_path_required();
        let reusable_execution_capture = commands.reusable_execution_capture().cloned();
        let entries = commands
            .into_entries()
            .into_iter()
            .map(|entry| {
                let (phase, node_index, logical_work, command) = entry.into_parts();
                let command = match logical_work {
                    Some(logical_work) => command.bind_core_logical_work(logical_work)?,
                    None => command,
                };
                Ok((phase, node_index, command))
            })
            .collect::<Result<Vec<_>, CudaDeviceRuntimeError>>()
            .map_err(DefinitelyNotSubmitted::new)?;
        let declaration_shape_matches = match compute_path_requirement {
            DeviceComputePathRequirement::ReplayedWithDeclaredEagerBoundaries => {
                !declared_eager_compute_node_indices.is_empty()
                    && declared_eager_compute_node_indices.len()
                        == declared_eager_compute_node_count
            }
            _ => declared_eager_compute_node_indices.is_empty(),
        };
        let mut compute_command_count = 0_usize;
        let mut direct_compute_command_count = 0_usize;
        let mut observed_eager_compute_node_indices = BTreeSet::new();
        let mut exact_boundary_shape = true;
        for (phase, node_index, command) in &entries {
            if *phase != DeviceCommandPhase::Compute {
                continue;
            }
            compute_command_count += 1;
            if let Some(invocation) = command.reusable_execution_invocation() {
                direct_compute_command_count += 1;
                if declared_eager_compute_node_indices
                    .iter()
                    .any(|node_index| invocation.segment().contains_node(*node_index))
                {
                    exact_boundary_shape = false;
                }
            } else if compute_path_requirement
                == DeviceComputePathRequirement::ReplayedWithDeclaredEagerBoundaries
            {
                exact_boundary_shape &= node_index.is_some_and(|node_index| {
                    declared_eager_compute_node_indices.contains(&node_index)
                        && observed_eager_compute_node_indices.insert(node_index)
                });
            }
        }
        let command_count = u32::try_from(entries.len()).map_err(|_| {
            DefinitelyNotSubmitted::new(CudaDeviceRuntimeError::contract(
                "CUDA command count exceeds u32",
            ))
        })?;
        let command_phases = entries
            .iter()
            .map(|(phase, _, _)| *phase)
            .collect::<Vec<_>>();
        let command_node_indices = (timing_mode.kernel_attribution_enabled()
            || logical_attribution
            || reusable_execution_capture.is_some())
        .then(|| {
            entries
                .iter()
                .map(|(_, node_index, _)| *node_index)
                .collect::<Vec<_>>()
        });
        let commands = entries
            .into_iter()
            .map(|(_, _, command)| command)
            .collect::<Vec<_>>();
        let physical_span_attribution = timing_mode.physical_span_attribution_enabled();
        let kernel_attribution = timing_mode.kernel_attribution_enabled();
        let native_attribution = kernel_attribution || logical_attribution;
        if kernel_attribution {
            vnext_tool_correlation::prepare();
        }
        let mut execution_paths =
            native_attribution.then(|| vec![DeviceExecutionPath::Eager; commands.len()]);
        let mut reusable_graph_node_counts = native_attribution.then(|| vec![None; commands.len()]);
        if commands
            .iter()
            .any(|command| command.runtime_instance != self.runtime_instance)
        {
            return Err(DefinitelyNotSubmitted::new(
                CudaDeviceRuntimeError::contract(
                    "CUDA command batch contains work from another runtime instance",
                ),
            ));
        }
        let contains_direct_execution = direct_compute_command_count != 0;
        let compute_path_matches = match compute_path_requirement {
            DeviceComputePathRequirement::Adaptive => true,
            DeviceComputePathRequirement::EagerOnly => direct_compute_command_count == 0,
            DeviceComputePathRequirement::ReplayedOnly => {
                compute_command_count > 0 && direct_compute_command_count == compute_command_count
            }
            DeviceComputePathRequirement::ReplayedWithDeclaredEagerBoundaries => {
                declaration_shape_matches
                    && exact_boundary_shape
                    && direct_compute_command_count > 0
                    && direct_compute_command_count < compute_command_count
                    && observed_eager_compute_node_indices == declared_eager_compute_node_indices
            }
        };
        if !compute_path_matches {
            return Err(DefinitelyNotSubmitted::new(
                CudaDeviceRuntimeError::contract(
                    "CUDA compute commands do not satisfy the required execution path",
                ),
            ));
        }
        if reusable_execution_capture.is_some() && contains_direct_execution {
            return Err(DefinitelyNotSubmitted::new(
                CudaDeviceRuntimeError::contract(
                    "CUDA reusable execution capture cannot contain direct program references",
                ),
            ));
        }
        if kernel_attribution && contains_direct_execution {
            return Err(DefinitelyNotSubmitted::new(
                CudaDeviceRuntimeError::contract(
                    "CUDA kernel attribution requires full logical command encoding",
                ),
            ));
        }
        if let (Some(command_node_indices), Some(execution_paths)) =
            (&command_node_indices, &execution_paths)
        {
            if let Err(error) = cuda_submission_attribution(
                &command_phases,
                command_node_indices,
                &commands,
                execution_paths,
                reusable_graph_node_counts.as_deref(),
                Vec::new(),
            ) {
                return Err(DefinitelyNotSubmitted::new(error));
            }
        }
        if let Err(error) = self.context.bind_to_thread() {
            return Err(DefinitelyNotSubmitted::new(CudaDeviceRuntimeError::driver(
                "submission context binding",
                error,
            )));
        }
        for invocation in commands
            .iter()
            .filter_map(CudaDeviceCommand::reusable_execution_invocation)
        {
            let resident = if logical_attribution {
                stream
                    .executable_cache
                    .contains_attributable_program_segment(invocation)
            } else {
                stream.executable_cache.contains_program_segment(invocation)
            };
            match resident {
                Ok(true) => {}
                Ok(false) => {
                    return Err(DefinitelyNotSubmitted::new(
                        CudaDeviceRuntimeError::contract(if logical_attribution {
                            "CUDA direct reusable execution lacks sealed logical attribution"
                        } else {
                            "CUDA direct reusable execution is not resident in the sealed catalog"
                        }),
                    ))
                }
                Err(error) => {
                    return Err(DefinitelyNotSubmitted::new(
                        CudaDeviceRuntimeError::contract(error.to_string()),
                    ))
                }
            }
        }
        let executable_candidates = match compute_path_requirement {
            DeviceComputePathRequirement::Adaptive => {
                let eager_boundary_node_indices = reusable_execution_capture
                    .as_ref()
                    .map(DeviceReusableExecutionCapture::eager_boundary_node_indices)
                    .unwrap_or_default();
                match cuda_executable_candidates(
                    &command_phases,
                    &commands,
                    command_node_indices.as_deref(),
                    eager_boundary_node_indices,
                ) {
                    Ok(candidates) => candidates,
                    Err(error) => return Err(DefinitelyNotSubmitted::new(error)),
                }
            }
            DeviceComputePathRequirement::EagerOnly
            | DeviceComputePathRequirement::ReplayedOnly
            | DeviceComputePathRequirement::ReplayedWithDeclaredEagerBoundaries => Vec::new(),
        };
        let capture_allowed = stream.state.is_quiescent();
        if let Err(error) = stream.state.begin_submission() {
            return Err(DefinitelyNotSubmitted::new(error));
        }
        let mut replay_observation = DeviceReusableExecutionObservation::default();
        if S::ENABLED {
            for _ in &executable_candidates {
                replay_observation.observe_candidate_segment();
            }
        }
        let preparation = match stream.executable_cache.prepare_all(
            &self.context,
            &stream.stream,
            &stream.blas,
            &commands,
            &executable_candidates,
            capture_allowed,
        ) {
            Ok(preparation) => preparation,
            Err(error) => {
                stream.state.fail();
                self.quarantine(stream, commands);
                panic!(
                    "CUDA submission became indeterminate while preparing reusable executables: {error}"
                );
            }
        };
        if S::ENABLED {
            for _ in 0..preparation.captured_segments() {
                replay_observation.observe_captured_segment();
            }
            for _ in 0..preparation.uploaded_segments() {
                replay_observation.observe_uploaded_segment();
            }
            for _ in 0..preparation.cache_hit_segments() {
                replay_observation.observe_cache_hit_segment();
            }
            for _ in 0..preparation.cached_rejected_segments() {
                replay_observation.observe_cached_rejected_segment();
            }
            for _ in 0..preparation.capture_rejected_segments() {
                replay_observation.observe_capture_rejection();
            }
            for _ in 0..preparation.quiescence_deferred_segments() {
                replay_observation.observe_quiescence_deferred_segment();
            }
            for _ in 0..preparation.capacity_deferred_segments() {
                replay_observation.observe_capacity_deferred_segment();
            }
            for _ in 0..preparation.outside_preparation_segments() {
                replay_observation.observe_outside_preparation_segment();
            }
            for _ in 0..preparation.evicted_segments() {
                replay_observation.observe_evicted_segment();
            }
        }
        if let Some(capture) = reusable_execution_capture.as_ref() {
            let command_node_indices = command_node_indices
                .as_deref()
                .expect("reusable execution capture retained node attribution");
            if let Err(error) = stream.executable_cache.register_program(
                capture,
                &executable_candidates,
                &command_phases,
                command_node_indices,
                &commands,
                &preparation,
            ) {
                stream.state.fail();
                self.quarantine(stream, commands);
                panic!(
                    "CUDA submission became indeterminate while registering a reusable program: {error}"
                );
            }
        }
        drop(validate_stage);

        let begin_timing_stage =
            CudaSubmissionStageTimer::start(timing_sink, DeviceSubmissionStage::BeginTiming);
        let timing = match timing_mode {
            DeviceTimingMode::Off => CudaFenceTiming::NotRequested,
            DeviceTimingMode::Completion
            | DeviceTimingMode::Replay
            | DeviceTimingMode::Kernel
            | DeviceTimingMode::Verification => {
                match stream
                    .stream
                    .record_event(Some(cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT))
                {
                    Ok(start) => CudaFenceTiming::Events { start },
                    Err(_) => CudaFenceTiming::Unavailable,
                }
            }
        };
        drop(begin_timing_stage);

        let enqueue_stage =
            CudaSubmissionStageTimer::start(timing_sink, DeviceSubmissionStage::EnqueueCommands);
        let mut command_spans =
            physical_span_attribution.then(|| Vec::with_capacity(commands.len()));
        let mut replayed_segments = logical_attribution.then(Vec::new);
        let mut index = 0;
        let mut executable_candidate_index = 0;
        while index < commands.len() {
            if let Some(invocation) = commands[index].reusable_execution_invocation() {
                let start = command_spans.as_ref().and_then(|_| {
                    stream
                        .stream
                        .record_event(Some(cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT))
                        .ok()
                });
                let launched = stream.executable_cache.launch_program_segment(
                    &stream.stream,
                    invocation,
                    timing_mode,
                    logical_attribution,
                );
                let end = command_spans.as_ref().and_then(|_| {
                    stream
                        .stream
                        .record_event(Some(cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT))
                        .ok()
                });
                match launched {
                    Ok(Some(launch)) => {
                        if let Some(replayed_segments) = replayed_segments.as_mut() {
                            let physical_command_index = u32::try_from(index).expect(
                                "CUDA direct replay command index was validated before submission",
                            );
                            let reusable_executable_fingerprint = launch
                                .reusable_executable_fingerprint()
                                .expect("attributable CUDA replay retained its fingerprint");
                            let logical_commands = launch
                                .replayed_logical_commands()
                                .expect("attributable CUDA replay retained its logical commands");
                            let reusable_graph_node_count =
                                logical_commands.iter().try_fold(0_u64, |total, command| {
                                    total.checked_add(command.reusable_graph_node_count())
                                });
                            let Some(reusable_graph_node_count) = reusable_graph_node_count else {
                                stream.state.fail();
                                self.quarantine(stream, commands);
                                panic!(
                                    "CUDA submission became indeterminate because replay graph attribution overflowed u64"
                                );
                            };
                            let replayed = DeviceReplayedSegmentAttribution::new(
                                physical_command_index,
                                invocation.program_id().clone(),
                                invocation.segment().clone(),
                                reusable_executable_fingerprint.to_string(),
                                logical_commands.as_ref().to_vec(),
                            );
                            let Some(replayed) = replayed else {
                                stream.state.fail();
                                self.quarantine(stream, commands);
                                panic!(
                                    "CUDA submission became indeterminate because sealed replay attribution drifted"
                                );
                            };
                            execution_paths
                                .as_mut()
                                .expect("logical CUDA attribution retained execution paths")
                                [index] = DeviceExecutionPath::Replayed;
                            reusable_graph_node_counts
                                .as_mut()
                                .expect("logical CUDA attribution retained graph counts")[index] =
                                Some(reusable_graph_node_count);
                            replayed_segments.push(replayed);
                        }
                        if let Some(command_spans) = command_spans.as_mut() {
                            command_spans.push(
                                CudaExecutionSpanEventTiming::new(
                                    index,
                                    index + 1,
                                    DeviceExecutionSpanKind::ReusableExecutable,
                                    DeviceExecutionIntervalKind::Compute,
                                    "cuda direct reusable executable",
                                    launch.reusable_executable_fingerprint(),
                                    start.zip(end),
                                )
                                .expect("CUDA direct replay index was validated as u32"),
                            );
                        }
                        if S::ENABLED {
                            replay_observation.observe_replayed_segment(
                                invocation.segment().logical_command_count() as usize,
                            );
                        }
                        index += 1;
                        continue;
                    }
                    Ok(None) => {
                        stream.state.fail();
                        self.quarantine(stream, commands);
                        panic!("CUDA reusable execution disappeared after pre-submit validation");
                    }
                    Err(error) => {
                        stream.state.fail();
                        self.quarantine(stream, commands);
                        panic!(
                            "CUDA submission became indeterminate while launching a reusable program: {error}"
                        );
                    }
                }
            }
            while executable_candidates
                .get(executable_candidate_index)
                .is_some_and(|candidate| candidate.start() < index)
            {
                executable_candidate_index += 1;
            }
            let replay_candidate = executable_candidates
                .get(executable_candidate_index)
                .filter(|candidate| candidate.start() == index);
            let replayed = match replay_candidate {
                Some(candidate)
                    if physical_span_attribution && stream.executable_cache.contains(candidate) =>
                {
                    let start = command_spans.as_ref().and_then(|_| {
                        stream
                            .stream
                            .record_event(Some(
                                cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT,
                            ))
                            .ok()
                    });
                    let launched =
                        stream
                            .executable_cache
                            .launch(&stream.stream, candidate, timing_mode);
                    let end = command_spans.as_ref().and_then(|_| {
                        stream
                            .stream
                            .record_event(Some(
                                cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT,
                            ))
                            .ok()
                    });
                    match launched {
                        Ok(Some(launch)) => Some(Ok((
                            candidate.end(),
                            start.zip(end),
                            launch.reusable_executable_fingerprint(),
                            launch.reusable_graph_node_counts(),
                        ))),
                        Ok(None) => None,
                        Err(error) => Some(Err(error)),
                    }
                }
                Some(candidate) if !physical_span_attribution => {
                    match stream
                        .executable_cache
                        .launch(&stream.stream, candidate, timing_mode)
                    {
                        Ok(Some(_)) => Some(Ok((candidate.end(), None, None, None))),
                        Ok(None) => None,
                        Err(error) => Some(Err(error)),
                    }
                }
                Some(_) | None => None,
            };
            match replayed {
                Some(Ok((
                    segment_end,
                    events,
                    reusable_executable_fingerprint,
                    graph_node_counts,
                ))) => {
                    if let Some(execution_paths) = execution_paths.as_mut() {
                        execution_paths[index..segment_end].fill(DeviceExecutionPath::Replayed);
                    }
                    if let (Some(target), Some(observed)) =
                        (reusable_graph_node_counts.as_mut(), graph_node_counts)
                    {
                        debug_assert_eq!(observed.len(), segment_end - index);
                        for (target, observed) in target[index..segment_end]
                            .iter_mut()
                            .zip(observed.iter().copied())
                        {
                            *target = Some(u64::from(observed));
                        }
                    }
                    if let Some(command_spans) = command_spans.as_mut() {
                        command_spans.push(
                            CudaExecutionSpanEventTiming::new(
                                index,
                                segment_end,
                                DeviceExecutionSpanKind::ReusableExecutable,
                                DeviceExecutionIntervalKind::Compute,
                                "cuda reusable executable",
                                reusable_executable_fingerprint,
                                events,
                            )
                            .expect("CUDA replay range was validated as u32"),
                        );
                    }
                    if S::ENABLED {
                        replay_observation.observe_replayed_segment(segment_end - index);
                    }
                    index = segment_end;
                    continue;
                }
                Some(Err(error)) => {
                    stream.state.fail();
                    self.quarantine(stream, commands);
                    panic!(
                        "CUDA submission became indeterminate while launching a reusable executable: {error}"
                    );
                }
                None => {}
            }
            let command_start = command_spans.as_ref().and_then(|_| {
                stream
                    .stream
                    .record_event(Some(cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT))
                    .ok()
            });
            if let Err(error) = commands[index].enqueue(&stream.stream, &stream.blas) {
                stream.state.fail();
                self.quarantine(stream, commands);
                panic!("CUDA submission became indeterminate while enqueueing its batch: {error}");
            }
            if let Some(command_spans) = command_spans.as_mut() {
                let command_end = stream
                    .stream
                    .record_event(Some(cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT))
                    .ok();
                let command = &commands[index];
                let interval_kind = if command.compute_dispatch_count > 0 {
                    DeviceExecutionIntervalKind::Compute
                } else {
                    DeviceExecutionIntervalKind::Transfer
                };
                command_spans.push(
                    CudaExecutionSpanEventTiming::new(
                        index,
                        index + 1,
                        DeviceExecutionSpanKind::EagerCommand,
                        interval_kind,
                        command.operation,
                        None,
                        command_start.zip(command_end),
                    )
                    .expect("CUDA eager command index was validated as u32"),
                );
            }
            if S::ENABLED {
                replay_observation.observe_eager_command();
            }
            index += 1;
        }
        drop(enqueue_stage);
        if S::ENABLED {
            timing_sink.record_reusable_execution(replay_observation);
        }
        let attribution = match command_node_indices
            .as_ref()
            .zip(execution_paths.as_ref())
            .map(|(command_node_indices, execution_paths)| {
                cuda_submission_attribution(
                    &command_phases,
                    command_node_indices,
                    &commands,
                    execution_paths,
                    reusable_graph_node_counts.as_deref(),
                    replayed_segments.unwrap_or_default(),
                )
            }) {
            None => None,
            Some(Ok(attribution)) => Some(attribution),
            Some(Err(error)) => {
                stream.state.fail();
                self.quarantine(stream, commands);
                panic!(
                    "CUDA submission became indeterminate while binding native attribution: {error}"
                );
            }
        };
        let command_timing = match timing_mode {
            DeviceTimingMode::Off | DeviceTimingMode::Completion => {
                CudaFenceCommandTiming::NotRequested
            }
            DeviceTimingMode::Replay
            | DeviceTimingMode::Kernel
            | DeviceTimingMode::Verification => command_spans.map_or(
                CudaFenceCommandTiming::Unavailable(
                    DeviceTimingUnavailableReason::BackendMeasurementFailed,
                ),
                |spans| CudaFenceCommandTiming::Spans {
                    command_count,
                    spans,
                },
            ),
        };

        let fence_stage = CudaSubmissionStageTimer::start(
            timing_sink,
            DeviceSubmissionStage::RecordFenceAndAccount,
        );
        let fence_flags = match timing_mode {
            DeviceTimingMode::Off => None,
            DeviceTimingMode::Completion
            | DeviceTimingMode::Replay
            | DeviceTimingMode::Kernel
            | DeviceTimingMode::Verification => {
                Some(cudarc::driver::sys::CUevent_flags::CU_EVENT_DEFAULT)
            }
        };
        let event = match stream.stream.record_event(fence_flags) {
            Ok(event) => event,
            Err(error) => {
                stream.state.fail();
                self.quarantine(stream, commands);
                panic!("CUDA submission became indeterminate while recording its fence: {error:?}");
            }
        };
        if let Err(error) = stream.state.submission_recorded() {
            stream.state.fail();
            self.quarantine(stream, commands);
            panic!("CUDA submission became indeterminate while accounting its fence: {error}");
        }
        let fence = CudaDeviceFence {
            event,
            timing,
            command_timing,
            attribution,
            stream_state: Arc::clone(&stream.state),
            terminal_accounted: AtomicBool::new(false),
            _stream: Arc::clone(&stream.stream),
            _blas: Arc::clone(&stream.blas),
            _commands: commands,
        };
        drop(fence_stage);
        Ok(fence)
    }

    fn submission_attribution(&self, fence: &Self::Fence) -> Option<DeviceSubmissionAttribution> {
        fence.attribution.clone()
    }

    fn query_fence(&self, fence: &Self::Fence) -> FenceQuery<Self::Error> {
        if let Err(error) = fence.event.context().bind_to_thread() {
            fence.stream_state.fail();
            return FenceQuery::Indeterminate(CudaDeviceRuntimeError::driver(
                "fence context binding",
                error,
            ));
        }
        match unsafe { cudarc::driver::result::event::query(fence.event.cu_event()) } {
            Ok(()) => {
                fence.mark_terminal();
                FenceQuery::Terminal(fence.terminal_receipt(DeviceTerminal::Succeeded))
            }
            Err(error) if error.0 == cudarc::driver::sys::CUresult::CUDA_ERROR_NOT_READY => {
                FenceQuery::Pending
            }
            Err(error) => {
                fence.stream_state.fail();
                FenceQuery::Indeterminate(CudaDeviceRuntimeError::driver("fence query", error))
            }
        }
    }

    fn wait_fence(
        &self,
        fence: &Self::Fence,
    ) -> Result<DeviceTerminalReceipt<Self::Error>, FenceIndeterminate<Self::Error>> {
        match fence.event.synchronize() {
            Ok(()) => {
                fence.mark_terminal();
                Ok(fence.terminal_receipt(DeviceTerminal::Succeeded))
            }
            Err(error) => {
                fence.stream_state.fail();
                Err(FenceIndeterminate::new(CudaDeviceRuntimeError::driver(
                    "fence wait",
                    error,
                )))
            }
        }
    }

    fn synchronize(&self, stream: &mut Self::Stream) -> Result<(), Self::Error> {
        self.validate_stream(stream)?;
        match stream.stream.synchronize() {
            Ok(()) => {
                self.release_quarantine(stream.id);
                stream.state.synchronized();
                Ok(())
            }
            Err(error) => {
                stream.state.fail();
                Err(CudaDeviceRuntimeError::driver(
                    "stream synchronization",
                    error,
                ))
            }
        }
    }

    fn readback(
        &self,
        stream: &mut Self::Stream,
        source: &Self::Buffer,
        region: CopyRegion,
        output_layout: HostTransferLayout,
    ) -> Result<Vec<u8>, Self::Error> {
        self.validate_stream(stream)?;
        self.validate_buffer(source)?;
        if output_layout.element_type() != source.descriptor.element_type {
            return Err(CudaDeviceRuntimeError::contract(
                "CUDA readback layout differs from source element type",
            ));
        }
        let output_bytes = output_layout
            .byte_len()
            .map_err(|error| CudaDeviceRuntimeError::contract(error.to_string()))?;
        let source_end = checked_end(
            region.source_offset_bytes(),
            region.length_bytes(),
            source.descriptor.size_bytes,
            "CUDA readback source",
        )?;
        let output_end = checked_end(
            region.destination_offset_bytes(),
            region.length_bytes(),
            output_bytes,
            "CUDA readback output",
        )?;
        self.synchronize(stream)?;
        let source_region = source.region(region.source_offset_bytes()..source_end)?;
        let mut output = vec![0_u8; checked_usize(output_bytes, "CUDA readback output")?];
        let output_start = checked_usize(
            region.destination_offset_bytes(),
            "CUDA readback output offset",
        )?;
        let output_end = checked_usize(output_end, "CUDA readback output end")?;
        unsafe {
            cudarc::driver::result::memcpy_dtoh_sync(
                &mut output[output_start..output_end],
                source_region.device_ptr,
            )
        }
        .map_err(|error| CudaDeviceRuntimeError::driver("host readback", error))?;
        Ok(output)
    }

    fn describe_error(&self, error: &Self::Error) -> Result<DeviceErrorReport, VNextError> {
        let (code, retryable) = match error {
            CudaDeviceRuntimeError::Blas { source, .. }
                if source.0 == cudarc::cublas::sys::cublasStatus_t::CUBLAS_STATUS_ALLOC_FAILED =>
            {
                ("cuda_blas_allocation_failed", true)
            }
            CudaDeviceRuntimeError::Blas { .. } => ("cuda_blas_error", false),
            _ => match error.driver_code() {
                Some(cudarc::driver::sys::CUresult::CUDA_ERROR_OUT_OF_MEMORY) => {
                    ("cuda_out_of_memory", true)
                }
                Some(code) => (
                    match code {
                        cudarc::driver::sys::CUresult::CUDA_ERROR_NOT_READY => "cuda_not_ready",
                        cudarc::driver::sys::CUresult::CUDA_ERROR_INVALID_CONTEXT => {
                            "cuda_invalid_context"
                        }
                        cudarc::driver::sys::CUresult::CUDA_ERROR_ILLEGAL_ADDRESS => {
                            "cuda_illegal_address"
                        }
                        _ => "cuda_driver_error",
                    },
                    false,
                ),
                None => ("cuda_runtime_contract", false),
            },
        };
        DeviceErrorReport::new(code, error.to_string(), retryable)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "vllm-marlin")]
    use crate::marlin_repack::repack_gptq_to_marlin;
    #[cfg(feature = "vllm-marlin")]
    use crate::mxfp4_marlin_materializer::{
        prepare_mxfp4_expert_scales_for_marlin, transpose_mxfp4_expert_blocks_to_gptq_words,
    };
    #[cfg(feature = "vllm-marlin")]
    use cudarc::driver::DevicePtrMut;
    use ferrum_interfaces::vnext::DeviceCommandPhase;

    fn program_binding_write(offset: u64, payload: Vec<u8>) -> CudaProgramBindingWrite {
        CudaProgramBindingWrite::new(offset, payload.into_boxed_slice()).unwrap()
    }

    #[test]
    #[ignore = "requires an sm89 CUDA host and the vLLM Marlin repack artifact"]
    #[cfg(feature = "vllm-marlin")]
    fn gpt_oss_mxfp4_runtime_materializer_two_expert_padding_matches_cpu_layout() {
        const EXPERTS: usize = 2;
        const N: usize = 2880;
        const LOGICAL_K: usize = 2880;
        const PHYSICAL_K: usize = 2944;

        let logical_packed = N * LOGICAL_K / 2;
        let physical_packed = N * PHYSICAL_K / 2;
        let logical_scales = N * LOGICAL_K / 32;
        let physical_scales = N * PHYSICAL_K / 32;
        let blocks = (0..EXPERTS * logical_packed)
            .map(|index| ((index * 13 + index / logical_packed * 97) & 0xff) as u8)
            .collect::<Vec<_>>();
        let scales = (0..EXPERTS * logical_scales)
            .map(|index| 119 + ((index * 3 + index / logical_scales * 11) % 17) as u8)
            .collect::<Vec<_>>();

        let context = CudaContext::new(0).unwrap();
        let stream = context.default_stream();
        let functions = Mxfp4MarlinPrepareFunctions::load(&context).unwrap();
        let mut packed_device: CudaSlice<u8> =
            stream.alloc_zeros(EXPERTS * physical_packed).unwrap();
        let mut scales_device: CudaSlice<u8> =
            stream.alloc_zeros(EXPERTS * physical_scales).unwrap();
        let mut scratch_device: CudaSlice<u8> = stream.alloc_zeros(physical_packed).unwrap();
        let n = N as i32;
        let logical_k = LOGICAL_K as i32;
        let physical_k = PHYSICAL_K as i32;
        {
            let (packed, _packed_guard) = packed_device.device_ptr_mut(&stream);
            let (prepared_scales, _scales_guard) = scales_device.device_ptr_mut(&stream);
            let (scratch, _scratch_guard) = scratch_device.device_ptr_mut(&stream);
            for expert in 0..EXPERTS {
                let expert_packed = packed + (expert * physical_packed) as u64;
                let expert_scales = prepared_scales + (expert * physical_scales) as u64;
                unsafe {
                    cudarc::driver::result::memcpy_htod_async(
                        expert_packed,
                        &blocks[expert * logical_packed..(expert + 1) * logical_packed],
                        stream.cu_stream(),
                    )
                }
                .unwrap();
                let mut transpose = stream.launch_builder(&functions.blocks_to_gptq_words);
                transpose.arg(&expert_packed);
                transpose.arg(&scratch);
                transpose.arg(&n);
                transpose.arg(&logical_k);
                transpose.arg(&physical_k);
                unsafe {
                    transpose.launch(LaunchConfig {
                        grid_dim: (((physical_packed / 4) as u32).div_ceil(256), 1, 1),
                        block_dim: (256, 1, 1),
                        shared_mem_bytes: 0,
                    })
                }
                .unwrap();
                unsafe {
                    crate::backend::cuda::vllm_marlin::vllm_gptq_marlin_repack_raw(
                        &stream,
                        scratch,
                        expert_packed,
                        physical_k,
                        n,
                    )
                }
                .unwrap();
                unsafe {
                    cudarc::driver::result::memcpy_htod_async(
                        scratch,
                        &scales[expert * logical_scales..(expert + 1) * logical_scales],
                        stream.cu_stream(),
                    )
                }
                .unwrap();
                let mut prepare = stream.launch_builder(&functions.scales_to_marlin);
                prepare.arg(&scratch);
                prepare.arg(&expert_scales);
                prepare.arg(&n);
                prepare.arg(&logical_k);
                prepare.arg(&physical_k);
                unsafe {
                    prepare.launch(LaunchConfig {
                        grid_dim: ((physical_scales as u32).div_ceil(256), 1, 1),
                        block_dim: (256, 1, 1),
                        shared_mem_bytes: 0,
                    })
                }
                .unwrap();
            }
            stream.synchronize().unwrap();
        }

        let actual_packed = stream.clone_dtoh(&packed_device).unwrap();
        let actual_scales = stream.clone_dtoh(&scales_device).unwrap();
        for expert in 0..EXPERTS {
            let mut padded_blocks = vec![0_u8; physical_packed];
            let mut padded_scales = vec![0_u8; physical_scales];
            for row in 0..N {
                padded_blocks[row * PHYSICAL_K / 2..row * PHYSICAL_K / 2 + LOGICAL_K / 2]
                    .copy_from_slice(
                        &blocks[expert * logical_packed + row * LOGICAL_K / 2
                            ..expert * logical_packed + (row + 1) * LOGICAL_K / 2],
                    );
                padded_scales[row * PHYSICAL_K / 32..row * PHYSICAL_K / 32 + LOGICAL_K / 32]
                    .copy_from_slice(
                        &scales[expert * logical_scales + row * LOGICAL_K / 32
                            ..expert * logical_scales + (row + 1) * LOGICAL_K / 32],
                    );
            }
            let words =
                transpose_mxfp4_expert_blocks_to_gptq_words(&padded_blocks, N, PHYSICAL_K).unwrap();
            let expected_packed = repack_gptq_to_marlin(&words, PHYSICAL_K, N)
                .into_iter()
                .flat_map(i32::to_le_bytes)
                .collect::<Vec<_>>();
            let expected_scales =
                prepare_mxfp4_expert_scales_for_marlin(&padded_scales, N, PHYSICAL_K).unwrap();
            assert_eq!(
                &actual_packed[expert * physical_packed..(expert + 1) * physical_packed],
                expected_packed.as_slice()
            );
            assert_eq!(
                &actual_scales[expert * physical_scales..(expert + 1) * physical_scales],
                expected_scales.as_slice()
            );
        }
    }

    #[test]
    fn sparse_program_binding_transfers_preserve_live_bytes_and_destination_offsets() {
        let transfers = coalesce_program_binding_transfers(
            vec![
                program_binding_write(16, vec![9, 10]),
                program_binding_write(2, vec![3]),
                program_binding_write(0, vec![1, 2]),
            ],
            32,
        )
        .unwrap();

        assert_eq!(transfers.len(), 2);
        assert_eq!(transfers[0].destination_offset_bytes, 0);
        assert_eq!(transfers[0].destination_stride_bytes, 3);
        assert_eq!(transfers[0].row_bytes, 3);
        assert_eq!(transfers[0].row_count, 1);
        assert_eq!(transfers[0].payload.as_ref(), &[1, 2, 3]);
        assert_eq!(transfers[1].destination_offset_bytes, 16);
        assert_eq!(transfers[1].payload.as_ref(), &[9, 10]);
        assert_eq!(
            transfers
                .iter()
                .map(|transfer| transfer.payload.len())
                .sum::<usize>(),
            5,
            "sparse planning must not materialize the unwritten arena gap",
        );
    }

    #[test]
    fn sparse_program_binding_transfers_reject_overlap_and_arena_overflow() {
        let overlap = coalesce_program_binding_transfers(
            vec![
                program_binding_write(0, vec![1, 2, 3, 4]),
                program_binding_write(3, vec![5, 6]),
            ],
            8,
        );
        assert!(matches!(overlap, Err(CudaDeviceRuntimeError::Contract(_))));

        let overflow =
            coalesce_program_binding_transfers(vec![program_binding_write(7, vec![1, 2])], 8);
        assert!(matches!(overflow, Err(CudaDeviceRuntimeError::Contract(_))));
    }

    #[test]
    fn sparse_program_binding_transfers_pack_thirty_two_fixed_stride_rows() {
        let row_bytes = 80_usize;
        let stride = 131_088_u64;
        let writes = (0_u8..32)
            .map(|row| program_binding_write(128 + u64::from(row) * stride, vec![row; row_bytes]))
            .collect();
        let transfers = coalesce_program_binding_transfers(writes, 5_000_000).unwrap();

        assert_eq!(transfers.len(), 1);
        let transfer = &transfers[0];
        assert_eq!(transfer.destination_offset_bytes, 128);
        assert_eq!(transfer.destination_stride_bytes, stride);
        assert_eq!(transfer.row_bytes, row_bytes);
        assert_eq!(transfer.row_count, 32);
        assert_eq!(transfer.payload.len(), 32 * row_bytes);
        for row in 0_u8..32 {
            let start = usize::from(row) * row_bytes;
            assert!(transfer.payload[start..start + row_bytes]
                .iter()
                .all(|byte| *byte == row));
        }
    }

    #[test]
    fn sparse_program_binding_transfers_split_when_row_length_changes() {
        let transfers = coalesce_program_binding_transfers(
            vec![
                program_binding_write(0, vec![1; 8]),
                program_binding_write(64, vec![2; 8]),
                program_binding_write(128, vec![3; 16]),
                program_binding_write(256, vec![4; 16]),
                program_binding_write(384, vec![5; 8]),
            ],
            512,
        )
        .unwrap();

        assert_eq!(transfers.len(), 3);
        assert_eq!(
            transfers
                .iter()
                .map(|transfer| (transfer.row_bytes, transfer.row_count))
                .collect::<Vec<_>>(),
            vec![(8, 2), (16, 2), (8, 1)],
        );
        assert_eq!(
            transfers
                .iter()
                .map(|transfer| transfer.destination_stride_bytes)
                .collect::<Vec<_>>(),
            vec![64, 128, 8],
        );
    }

    #[test]
    fn qwen_max_context_sixty_four_patches_keep_only_live_binding_payload() {
        const PARTICIPANTS: u64 = 32;
        const RECURRENT_ROW_BYTES: u64 = 16;
        const CAUSAL_ROW_BYTES: usize = 80;
        const MAXIMUM_CONTEXT_TOKENS: u64 = 262_144;
        const PAGE_TOKENS: u64 = 16;
        const ADDRESS_BYTES: u64 = 8;
        const CONTROL_BYTES: u64 = 16;

        let causal_row_capacity =
            CONTROL_BYTES + MAXIMUM_CONTEXT_TOKENS.div_ceil(PAGE_TOKENS) * ADDRESS_BYTES;
        let recurrent_slot_capacity = PARTICIPANTS * RECURRENT_ROW_BYTES;
        let causal_slot_capacity = PARTICIPANTS * causal_row_capacity;
        let group_capacity = 3 * recurrent_slot_capacity + causal_slot_capacity;
        let arena_size = 16 * group_capacity;
        assert_eq!(arena_size, 67_141_632);

        let mut logical_patches = Vec::with_capacity(64);
        for group in 0_u64..16 {
            let group_offset = group * group_capacity;
            for recurrent in 0_u64..3 {
                let slot_offset = group_offset + recurrent * recurrent_slot_capacity;
                logical_patches.push(
                    (0_u64..PARTICIPANTS)
                        .map(|participant| {
                            program_binding_write(
                                slot_offset + participant * RECURRENT_ROW_BYTES,
                                vec![
                                    u8::try_from(recurrent).unwrap();
                                    usize::try_from(RECURRENT_ROW_BYTES).unwrap()
                                ],
                            )
                        })
                        .collect::<Vec<_>>(),
                );
            }
            let causal_slot_offset = group_offset + 3 * recurrent_slot_capacity;
            logical_patches.push(
                (0_u64..PARTICIPANTS)
                    .map(|participant| {
                        program_binding_write(
                            causal_slot_offset + participant * causal_row_capacity,
                            vec![u8::try_from(group).unwrap(); CAUSAL_ROW_BYTES],
                        )
                    })
                    .collect::<Vec<_>>(),
            );
        }
        assert_eq!(logical_patches.len(), 64);

        let transfers = coalesce_program_binding_transfers(
            logical_patches.into_iter().flatten().collect(),
            arena_size,
        )
        .unwrap();
        let live_payload_bytes = transfers
            .iter()
            .map(|transfer| transfer.payload.len())
            .sum::<usize>();
        assert_eq!(live_payload_bytes, 65_536);
        assert_eq!(transfers.len(), 32);
        assert_eq!(transfers[0].destination_offset_bytes, 0);
        assert_eq!(transfers[0].row_bytes, 1_616);
        assert_eq!(transfers[0].row_count, 1);
        assert_eq!(
            transfers[1].destination_offset_bytes,
            3 * recurrent_slot_capacity + causal_row_capacity,
        );
        assert_eq!(transfers[1].destination_stride_bytes, causal_row_capacity);
        assert_eq!(transfers[1].row_bytes, CAUSAL_ROW_BYTES);
        assert_eq!(transfers[1].row_count, 31);
        assert_eq!(transfers[2].destination_offset_bytes, group_capacity);
    }

    fn command(operation: &'static str) -> CudaDeviceCommand {
        CudaDeviceCommand {
            runtime_instance: 1,
            operation,
            batching_form: DeviceBatchingForm::Scalar,
            participant_start: 0,
            participant_count: 1,
            token_count: 1,
            compute_dispatch_count: 1,
            transfer_command_count: 0,
            executable: Some(Arc::new(CudaCommandExecutable {
                regions: Vec::new(),
                host_storage: Vec::new(),
                enqueue: Mutex::new(Box::new(|_, _, _, _| Ok(()))),
            })),
            fence_dependencies: Vec::new(),
            replay_key: None,
            reusable_address_scope: None,
            replay_gap_reason: None,
            program_binding_patch: None,
            reusable_execution: None,
        }
    }

    #[test]
    fn kernel_attribution_retains_core_identity_and_cuda_work_shape() {
        let compute = command("test_compute")
            .with_work_attribution(DeviceBatchingForm::Packed, 2, 8, 3, 0)
            .unwrap();
        let binding = command("test_binding")
            .with_work_attribution(DeviceBatchingForm::ParticipantLoop, 2, 8, 0, 2)
            .unwrap();
        let attribution = cuda_submission_attribution(
            &[
                DeviceCommandPhase::Compute,
                DeviceCommandPhase::DynamicBinding,
            ],
            &[Some(0), Some(0)],
            &[compute, binding],
            &[DeviceExecutionPath::Eager, DeviceExecutionPath::Replayed],
            Some(&[None, Some(2)]),
            Vec::new(),
        )
        .unwrap();

        let [compute, binding] = attribution.commands() else {
            panic!("expected two CUDA attribution rows")
        };
        assert_eq!(compute.command_index(), 0);
        assert_eq!(compute.node_index(), Some(0));
        assert_eq!(compute.command_phase(), DeviceCommandPhase::Compute);
        assert_eq!(compute.native_op_id(), "test_compute");
        assert_eq!(compute.execution_path(), DeviceExecutionPath::Eager);
        assert_eq!(compute.batching_form(), DeviceBatchingForm::Packed);
        assert_eq!(compute.participant_count(), 2);
        assert_eq!(compute.token_count(), 8);
        assert_eq!(compute.compute_dispatch_count(), 3);
        assert_eq!(compute.transfer_command_count(), 0);

        assert_eq!(binding.command_index(), 1);
        assert_eq!(binding.command_phase(), DeviceCommandPhase::DynamicBinding);
        assert_eq!(binding.execution_path(), DeviceExecutionPath::Replayed);
        assert_eq!(binding.reusable_graph_node_count(), Some(2));
        assert_eq!(binding.compute_dispatch_count(), 0);
        assert_eq!(binding.transfer_command_count(), 2);
    }

    #[test]
    fn core_logical_work_binds_node_workspace_zero_attribution() {
        let zero = || {
            CudaDeviceCommand::transfer(
                1,
                DEVICE_ZERO_NATIVE_OPERATION_ID.as_str(),
                Vec::new(),
                Vec::new(),
                Box::new(|_, _, _, _| Ok(())),
            )
        };
        let error = cuda_submission_attribution(
            &[DeviceCommandPhase::Initialization],
            &[Some(0)],
            &[zero()],
            &[DeviceExecutionPath::Eager],
            Some(&[None]),
            Vec::new(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("invalid native work metadata"));

        let logical_work =
            DeviceCommandLogicalWork::new(DeviceBatchingForm::Packed, 1, 164).unwrap();
        let bound = zero().bind_core_logical_work(logical_work).unwrap();
        let attribution = cuda_submission_attribution(
            &[DeviceCommandPhase::Initialization],
            &[Some(0)],
            &[bound],
            &[DeviceExecutionPath::Eager],
            Some(&[None]),
            Vec::new(),
        )
        .unwrap();
        let [command] = attribution.commands() else {
            panic!("expected one node workspace initialization row")
        };
        assert_eq!(command.node_index(), Some(0));
        assert_eq!(command.command_phase(), DeviceCommandPhase::Initialization);
        assert_eq!(command.batching_form(), DeviceBatchingForm::Packed);
        assert_eq!(command.participant_count(), 1);
        assert_eq!(command.token_count(), 164);
        assert_eq!(command.compute_dispatch_count(), 0);
        assert_eq!(command.transfer_command_count(), 1);
    }

    #[test]
    fn cuda_work_attribution_rejects_empty_native_work() {
        let error = command("test_invalid")
            .with_work_attribution(DeviceBatchingForm::Scalar, 1, 1, 0, 0)
            .unwrap_err();
        assert!(error.to_string().contains("no participants or native work"));
    }

    #[test]
    fn cuda_work_attribution_rejects_non_portable_native_operation_identity() {
        let invalid = command("human readable label")
            .with_work_attribution(DeviceBatchingForm::Scalar, 1, 1, 1, 0)
            .unwrap();
        let error = cuda_submission_attribution(
            &[DeviceCommandPhase::Compute],
            &[Some(0)],
            &[invalid],
            &[DeviceExecutionPath::Eager],
            Some(&[None]),
            Vec::new(),
        )
        .unwrap_err();
        assert!(error
            .to_string()
            .contains("non-portable native operation identity"));
    }
}