stwo-gpu 2.0.0

GPU-accelerated Circle STARK prover and verifier — ObelyZK fork of STWO with CUDA/Metal backend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
//! CUDA FFT Executor - Runtime integration for GPU-accelerated FFT.
//!
//! This module provides the actual CUDA execution layer for the GPU FFT kernels.
//! It handles:
//! - Device initialization and management
//! - Kernel compilation via NVRTC
//! - Memory allocation and transfers
//! - Kernel execution and synchronization
//!
//! # Requirements
//!
//! - CUDA Toolkit 11.0+ installed
//! - NVIDIA GPU with compute capability 7.0+ (Volta or newer recommended)
//! - `gpu` feature enabled in Cargo.toml

#[cfg(feature = "cuda-runtime")]
use std::sync::{Arc, OnceLock};

#[cfg(feature = "cuda-runtime")]
use cudarc::driver::{CudaDevice, CudaFunction, CudaSlice, LaunchAsync, LaunchConfig};

#[cfg(feature = "cuda-runtime")]
use super::fft::CIRCLE_FFT_CUDA_KERNEL;
#[allow(unused_imports)]
#[cfg(feature = "cuda-runtime")]
use super::fft::{GPU_FFT_THRESHOLD_LOG_SIZE, M31_PRIME};

// =============================================================================
// Global CUDA Context
// =============================================================================

#[cfg(feature = "cuda-runtime")]
static CUDA_FFT_EXECUTOR: OnceLock<Result<CudaFftExecutor, CudaFftError>> = OnceLock::new();

#[cfg(feature = "cuda-runtime")]
use std::sync::Mutex;

#[cfg(feature = "cuda-runtime")]
use std::collections::HashMap;

/// Multi-GPU executor pool for true parallel GPU execution.
///
/// This replaces the global singleton pattern with a pool that supports:
/// - One executor per GPU device
/// - Thread-safe access via Arc<Mutex<>>
/// - Lazy initialization per device
#[cfg(feature = "cuda-runtime")]
static CUDA_EXECUTOR_POOL: OnceLock<Mutex<HashMap<usize, Arc<CudaFftExecutor>>>> = OnceLock::new();

/// Get or create an executor for a specific GPU device.
///
/// This is the preferred method for multi-GPU workloads.
/// Each device gets its own executor with compiled kernels.
///
/// # Arguments
/// * `device_id` - The GPU device ID (0, 1, 2, etc.)
///
/// # Returns
/// An Arc-wrapped executor that can be shared across threads.
#[cfg(feature = "cuda-runtime")]
pub fn get_executor_for_device(device_id: usize) -> Result<Arc<CudaFftExecutor>, CudaFftError> {
    let pool = CUDA_EXECUTOR_POOL.get_or_init(|| Mutex::new(HashMap::new()));

    let mut pool_guard = pool
        .lock()
        .map_err(|_| CudaFftError::DriverInit("Failed to acquire executor pool lock".into()))?;

    // Return cached executor if available
    if let Some(executor) = pool_guard.get(&device_id) {
        return Ok(Arc::clone(executor));
    }

    // Create new executor for this device
    tracing::info!("Creating new CUDA executor for device {}", device_id);
    let executor = CudaFftExecutor::new_on_device(device_id)?;
    let executor_arc = Arc::new(executor);

    pool_guard.insert(device_id, Arc::clone(&executor_arc));

    Ok(executor_arc)
}

/// Get executors for all available GPUs.
///
/// Useful for distributing work across all GPUs.
#[cfg(feature = "cuda-runtime")]
pub fn get_all_executors() -> Result<Vec<(usize, Arc<CudaFftExecutor>)>, CudaFftError> {
    let mut executors = Vec::new();

    // Probe for available GPUs (up to 16)
    for device_id in 0..16 {
        match get_executor_for_device(device_id) {
            Ok(executor) => executors.push((device_id, executor)),
            Err(CudaFftError::NoDevice) => break,
            Err(CudaFftError::DriverInit(_)) => break, // No more GPUs
            Err(e) => return Err(e),
        }
    }

    if executors.is_empty() {
        return Err(CudaFftError::NoDevice);
    }

    Ok(executors)
}

/// Get the number of available CUDA devices.
#[cfg(feature = "cuda-runtime")]
pub fn get_device_count() -> usize {
    let mut count = 0;
    for i in 0..16 {
        if CudaDevice::new(i).is_ok() {
            count = i + 1;
        } else {
            break;
        }
    }
    count
}

/// Get the global CUDA FFT executor instance.
///
/// This lazily initializes the CUDA context on first call.
///
/// **Note:** For multi-GPU workloads, prefer `get_executor_for_device()`.
#[cfg(feature = "cuda-runtime")]
pub fn get_cuda_executor() -> Result<&'static CudaFftExecutor, &'static CudaFftError> {
    CUDA_FFT_EXECUTOR
        .get_or_init(|| CudaFftExecutor::new())
        .as_ref()
}

/// Check if CUDA is available and initialized.
#[cfg(feature = "cuda-runtime")]
pub fn is_cuda_available() -> bool {
    get_cuda_executor().is_ok()
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn is_cuda_available() -> bool {
    false
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn get_device_count() -> usize {
    0
}

// =============================================================================
// Error Types
// =============================================================================

/// Errors that can occur during CUDA FFT execution.
#[derive(Debug, Clone)]
pub enum CudaFftError {
    /// No CUDA device found
    NoDevice,
    /// CUDA driver initialization failed
    DriverInit(String),
    /// Kernel compilation failed
    KernelCompilation(String),
    /// Memory allocation failed
    MemoryAllocation(String),
    /// Memory transfer failed
    MemoryTransfer(String),
    /// Kernel execution failed
    KernelExecution(String),
    /// Invalid input size
    InvalidSize(String),
    /// Kernel launch failed
    KernelLaunch(String),
}

impl std::fmt::Display for CudaFftError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CudaFftError::NoDevice => write!(f, "No CUDA device found"),
            CudaFftError::DriverInit(s) => write!(f, "CUDA driver init failed: {}", s),
            CudaFftError::KernelCompilation(s) => write!(f, "Kernel compilation failed: {}", s),
            CudaFftError::MemoryAllocation(s) => write!(f, "Memory allocation failed: {}", s),
            CudaFftError::MemoryTransfer(s) => write!(f, "Memory transfer failed: {}", s),
            CudaFftError::KernelExecution(s) => write!(f, "Kernel execution failed: {}", s),
            CudaFftError::InvalidSize(s) => write!(f, "Invalid size: {}", s),
            CudaFftError::KernelLaunch(s) => write!(f, "Kernel launch failed: {}", s),
        }
    }
}

impl std::error::Error for CudaFftError {}

// =============================================================================
// Memory Pressure Management
// =============================================================================

/// Memory usage statistics for a CUDA device.
#[derive(Debug, Clone)]
pub struct GpuMemoryStats {
    /// Total device memory in bytes
    pub total_bytes: usize,
    /// Free device memory in bytes
    pub free_bytes: usize,
    /// Used device memory in bytes
    pub used_bytes: usize,
    /// Utilization percentage (0-100)
    pub utilization_percent: f32,
}

/// Strategy for handling memory pressure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryPressureStrategy {
    /// Fail immediately with an error
    FailFast,
    /// Fallback to CPU (SIMD) processing
    FallbackToCpu,
    /// Wait and retry (with exponential backoff)
    WaitAndRetry {
        max_retries: u32,
        base_delay_ms: u64,
    },
}

impl Default for MemoryPressureStrategy {
    fn default() -> Self {
        // Default to CPU fallback for robustness
        MemoryPressureStrategy::FallbackToCpu
    }
}

/// Query current GPU memory usage.
#[cfg(feature = "cuda-runtime")]
pub fn get_memory_stats() -> Result<GpuMemoryStats, CudaFftError> {
    use super::compat;

    let (free, total) = compat::mem_get_info().map_err(|e| CudaFftError::DriverInit(e))?;

    let used = total - free;
    let utilization = if total > 0 {
        (used as f32 / total as f32) * 100.0
    } else {
        0.0
    };

    Ok(GpuMemoryStats {
        total_bytes: total,
        free_bytes: free,
        used_bytes: used,
        utilization_percent: utilization,
    })
}

/// Check if there's enough GPU memory for a given allocation.
///
/// Returns `Ok(true)` if sufficient memory is available,
/// `Ok(false)` if not, and `Err` on query failure.
#[cfg(feature = "cuda-runtime")]
pub fn check_memory_available(
    required_bytes: usize,
    safety_margin: f32,
) -> Result<bool, CudaFftError> {
    let stats = get_memory_stats()?;

    // Apply safety margin (e.g., 0.1 = keep 10% free)
    let required_with_margin = (required_bytes as f32 * (1.0 + safety_margin)) as usize;

    Ok(stats.free_bytes >= required_with_margin)
}

/// Calculate memory requirements for proof generation.
///
/// Returns the estimated GPU memory needed for a proof with the given parameters.
pub fn estimate_proof_memory(log_size: u32, num_polynomials: usize) -> usize {
    let n = 1usize << log_size;

    // Base polynomial storage: n * 4 bytes per polynomial
    let poly_storage = n * 4 * num_polynomials;

    // Twiddle factors: approximately 2 * n * 4 bytes
    let twiddle_storage = n * 8;

    // Working buffers: 2-3x polynomial storage for FFT/FRI
    let working_buffers = poly_storage * 3;

    // Merkle tree buffers: roughly 2 * n * 32 bytes for leaves + nodes
    let merkle_storage = n * 64;

    // Add 20% overhead for fragmentation and kernel scratch space
    let total = poly_storage + twiddle_storage + working_buffers + merkle_storage;
    (total as f32 * 1.2) as usize
}

/// Execute with memory pressure handling.
///
/// This wrapper tries GPU execution first, then falls back to CPU if needed.
#[cfg(feature = "cuda-runtime")]
pub fn with_memory_fallback<T, GpuFn, CpuFn>(
    strategy: MemoryPressureStrategy,
    required_bytes: usize,
    mut gpu_fn: GpuFn,
    cpu_fn: CpuFn,
) -> Result<T, CudaFftError>
where
    GpuFn: FnMut() -> Result<T, CudaFftError>,
    CpuFn: FnOnce() -> T,
{
    match strategy {
        MemoryPressureStrategy::FailFast => {
            // Check memory before attempting GPU execution
            if !check_memory_available(required_bytes, 0.1)? {
                let stats = get_memory_stats()?;
                return Err(CudaFftError::MemoryAllocation(format!(
                    "Insufficient GPU memory: need {} MB, only {} MB free",
                    required_bytes / (1024 * 1024),
                    stats.free_bytes / (1024 * 1024)
                )));
            }
            gpu_fn()
        }

        MemoryPressureStrategy::FallbackToCpu => {
            // Check memory first
            if !check_memory_available(required_bytes, 0.1).unwrap_or(false) {
                tracing::warn!(
                    "GPU memory pressure detected ({} MB required), falling back to CPU",
                    required_bytes / (1024 * 1024)
                );
                return Ok(cpu_fn());
            }

            // Try GPU, fallback on error
            match gpu_fn() {
                Ok(result) => Ok(result),
                Err(CudaFftError::MemoryAllocation(_)) => {
                    tracing::warn!("GPU allocation failed, falling back to CPU");
                    Ok(cpu_fn())
                }
                Err(e) => Err(e),
            }
        }

        MemoryPressureStrategy::WaitAndRetry {
            max_retries,
            base_delay_ms,
        } => {
            let mut retries = 0;

            loop {
                if check_memory_available(required_bytes, 0.1)? {
                    match gpu_fn() {
                        Ok(result) => return Ok(result),
                        Err(CudaFftError::MemoryAllocation(msg)) => {
                            if retries >= max_retries {
                                return Err(CudaFftError::MemoryAllocation(format!(
                                    "Out of GPU memory after {} retries: {}",
                                    max_retries, msg
                                )));
                            }
                            retries += 1;
                        }
                        Err(e) => return Err(e),
                    }
                } else if retries >= max_retries {
                    let stats = get_memory_stats()?;
                    return Err(CudaFftError::MemoryAllocation(format!(
                        "Timeout waiting for GPU memory: need {} MB, only {} MB free",
                        required_bytes / (1024 * 1024),
                        stats.free_bytes / (1024 * 1024)
                    )));
                }

                // Exponential backoff
                let delay = base_delay_ms * (1 << retries.min(5));
                tracing::debug!(
                    "Waiting for GPU memory (retry {}/{}), sleeping {} ms",
                    retries + 1,
                    max_retries,
                    delay
                );
                std::thread::sleep(std::time::Duration::from_millis(delay));
                retries += 1;
            }
        }
    }
}

// Non-cuda-runtime stub
#[cfg(not(feature = "cuda-runtime"))]
pub fn get_memory_stats() -> Result<GpuMemoryStats, CudaFftError> {
    Err(CudaFftError::NoDevice)
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn check_memory_available(
    _required_bytes: usize,
    _safety_margin: f32,
) -> Result<bool, CudaFftError> {
    Ok(false)
}

// =============================================================================
// CUDA FFT Executor
// =============================================================================

/// CUDA FFT Executor - manages GPU resources for FFT operations.
#[cfg(feature = "cuda-runtime")]
pub struct CudaFftExecutor {
    /// CUDA device handle (public for memory management)
    pub device: Arc<CudaDevice>,
    /// Compiled kernels (public for pipeline access)
    pub kernels: CompiledKernels,
    /// Device info
    pub device_info: DeviceInfo,
    /// Dedicated compute stream for kernel execution (optional)
    /// When set, kernels are launched on this stream instead of the default stream.
    /// This allows overlapping transfers with computation.
    compute_stream: Option<cudarc::driver::CudaStream>,
    /// Transfer stream for H2D/D2H operations
    transfer_stream: Option<cudarc::driver::CudaStream>,
}

// SAFETY: CudaFftExecutor is Send+Sync because:
// - CudaDevice is already Send+Sync (Arc-wrapped)
// - CudaStream contains a raw CUDA stream handle that is safe to send between threads
//   as long as we don't use it concurrently (we don't - access is serialized)
// - CompiledKernels contains CudaFunction handles that are thread-safe
// This is required for OnceLock<Result<CudaFftExecutor, _>> and the executor pool statics.
#[cfg(feature = "cuda-runtime")]
unsafe impl Send for CudaFftExecutor {}
#[cfg(feature = "cuda-runtime")]
unsafe impl Sync for CudaFftExecutor {}

/// Compiled CUDA kernels for proof operations.
#[cfg(feature = "cuda-runtime")]
pub struct CompiledKernels {
    // FFT kernels
    pub bit_reverse: CudaFunction,
    pub ifft_layer: CudaFunction,
    pub fft_layer: CudaFunction,
    // Optimized shared memory FFT kernel
    pub ifft_shared_mem: CudaFunction,
    // Denormalization kernels (fused post-FFT operation)
    pub denormalize: CudaFunction,
    pub denormalize_vec4: CudaFunction,
    // FRI folding kernels
    pub fold_line: CudaFunction,
    pub fold_circle_into_line: CudaFunction,
    pub deinterleave_aos_to_soa: CudaFunction,
    // Quotient accumulation kernels
    pub accumulate_quotients: CudaFunction,
    pub eval_point_accumulate: CudaFunction,
    pub copy_column: CudaFunction, // GPU-resident column copy
    // MLE (GKR) operations kernels
    pub mle_fold_base_to_secure: CudaFunction,
    pub mle_fold_secure: CudaFunction,
    pub gen_eq_evals: CudaFunction,
    // Merkle hashing kernel (Blake2s)
    pub merkle_layer: CudaFunction,
    // Poseidon252 Merkle hashing kernel
    pub poseidon252_merkle_layer: CudaFunction,
    // Poseidon252 chunked hash_many kernel (weight commitments)
    pub poseidon252_hash_many_chunked: CudaFunction,
    // Poseidon252 chunked hash_many kernel over raw M31 inputs (GPU packing)
    pub poseidon252_hash_many_chunked_m31: CudaFunction,
}

/// GPU-resident Poseidon252 Merkle tree layers.
///
/// Stores internal hash layers (not raw leaves):
/// - `layers[0]` has `n_leaf_hashes` hashes (hash of leaf pairs)
/// - `layers[1]` has `n_leaf_hashes/2` hashes
/// - ...
/// - `layers[last]` has 1 hash (root)
#[cfg(feature = "cuda-runtime")]
pub struct Poseidon252MerkleGpuTree {
    device: Arc<CudaDevice>,
    layers: Vec<CudaSlice<u64>>,
    layer_hash_counts: Vec<usize>,
}

#[cfg(feature = "cuda-runtime")]
impl Poseidon252MerkleGpuTree {
    /// Number of internal hash layers (includes root layer).
    pub fn num_layers(&self) -> usize {
        self.layers.len()
    }

    /// Number of hashes in a given internal layer.
    pub fn layer_hash_count(&self, layer_idx: usize) -> usize {
        self.layer_hash_counts[layer_idx]
    }

    /// Download one hash node (4 u64 limbs) from an internal layer.
    pub fn node_u64(&self, layer_idx: usize, hash_idx: usize) -> Result<[u64; 4], CudaFftError> {
        if layer_idx >= self.layers.len() {
            return Err(CudaFftError::InvalidSize(format!(
                "layer index out of bounds: {} (layers={})",
                layer_idx,
                self.layers.len()
            )));
        }
        let n = self.layer_hash_counts[layer_idx];
        if hash_idx >= n {
            return Err(CudaFftError::InvalidSize(format!(
                "hash index out of bounds: {} (layer={}, hashes={})",
                hash_idx, layer_idx, n
            )));
        }
        let start = hash_idx * 4;
        let end = start + 4;
        let mut out = [0u64; 4];
        self.device
            .dtoh_sync_copy_into(&self.layers[layer_idx].slice(start..end), &mut out)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
        Ok(out)
    }

    /// Download the Merkle root hash (4 u64 limbs).
    pub fn root_u64(&self) -> Result<[u64; 4], CudaFftError> {
        if self.layers.is_empty() {
            return Err(CudaFftError::InvalidSize(
                "cannot read root of empty GPU merkle tree".into(),
            ));
        }
        self.node_u64(self.layers.len() - 1, 0)
    }
}

/// Information about the CUDA device.
#[derive(Debug, Clone)]
pub struct DeviceInfo {
    pub name: String,
    pub compute_capability: (u32, u32),
    pub total_memory_bytes: usize,
    pub multiprocessor_count: u32,
    pub max_threads_per_block: u32,
}

#[cfg(feature = "cuda-runtime")]
impl CudaFftExecutor {
    /// Create a new CUDA FFT executor on GPU 0.
    ///
    /// This initializes the CUDA context and compiles all FFT kernels.
    pub fn new() -> Result<Self, CudaFftError> {
        Self::new_on_device(0)
    }

    /// Create a new CUDA FFT executor on a specific GPU.
    ///
    /// # Arguments
    /// * `device_id` - The GPU device ID (0, 1, 2, etc.)
    pub fn new_on_device(device_id: usize) -> Result<Self, CudaFftError> {
        // Initialize CUDA device (returns Arc<CudaDevice>)
        let device = CudaDevice::new(device_id)
            .map_err(|e| CudaFftError::DriverInit(format!("GPU {}: {:?}", device_id, e)))?;

        // Get device info
        let device_info = Self::get_device_info(&device)?;

        tracing::info!(
            "CUDA device initialized: {} (SM {}.{}, {} MB)",
            device_info.name,
            device_info.compute_capability.0,
            device_info.compute_capability.1,
            device_info.total_memory_bytes / (1024 * 1024)
        );

        // Compile kernels
        let kernels = Self::compile_kernels(&device)?;

        // Create dedicated streams for overlapped execution
        let compute_stream = device
            .fork_default_stream()
            .map_err(|e| CudaFftError::DriverInit(format!("Compute stream: {:?}", e)))
            .ok();

        let transfer_stream = device
            .fork_default_stream()
            .map_err(|e| CudaFftError::DriverInit(format!("Transfer stream: {:?}", e)))
            .ok();

        if compute_stream.is_some() {
            tracing::info!("CUDA streams enabled for overlapped execution");
        }

        tracing::info!("CUDA FFT kernels compiled successfully");

        Ok(Self {
            device,
            kernels,
            device_info,
            compute_stream,
            transfer_stream,
        })
    }

    // =========================================================================
    // Stream Access Methods
    // =========================================================================

    /// Get the compute stream for kernel execution.
    ///
    /// When a compute stream is available, kernels should be launched on it
    /// to enable overlapped execution with transfers.
    pub fn compute_stream(&self) -> Option<&cudarc::driver::CudaStream> {
        self.compute_stream.as_ref()
    }

    /// Get the transfer stream for H2D/D2H operations.
    pub fn transfer_stream(&self) -> Option<&cudarc::driver::CudaStream> {
        self.transfer_stream.as_ref()
    }

    /// Check if stream-based execution is enabled.
    pub fn has_streams(&self) -> bool {
        self.compute_stream.is_some()
    }

    /// Synchronize the compute stream (wait for all kernels to complete).
    pub fn sync_compute(&self) -> Result<(), CudaFftError> {
        if let Some(stream) = &self.compute_stream {
            self.device.wait_for(stream).map_err(|e| {
                CudaFftError::KernelExecution(format!("Compute stream sync: {:?}", e))
            })?;
        }
        Ok(())
    }

    /// Synchronize the transfer stream (wait for all transfers to complete).
    pub fn sync_transfer(&self) -> Result<(), CudaFftError> {
        if let Some(stream) = &self.transfer_stream {
            self.device.wait_for(stream).map_err(|e| {
                CudaFftError::KernelExecution(format!("Transfer stream sync: {:?}", e))
            })?;
        }
        Ok(())
    }

    /// Synchronize all streams.
    pub fn sync_all(&self) -> Result<(), CudaFftError> {
        self.sync_compute()?;
        self.sync_transfer()?;
        Ok(())
    }

    fn get_device_info(device: &Arc<CudaDevice>) -> Result<DeviceInfo, CudaFftError> {
        use super::compat;
        use cudarc::driver::sys::CUdevice_attribute;

        let cu_device = device.cu_device();

        // Query compute capability
        let major = compat::device_get_attribute(
            *cu_device,
            CUdevice_attribute::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR,
        )
        .map_err(|e| CudaFftError::DriverInit(e))? as u32;

        let minor = compat::device_get_attribute(
            *cu_device,
            CUdevice_attribute::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR,
        )
        .map_err(|e| CudaFftError::DriverInit(e))? as u32;

        // Query device name
        let name = compat::device_get_name(*cu_device).unwrap_or_else(|_| "NVIDIA GPU".to_string());

        // Query total memory
        let total_memory_bytes =
            compat::device_total_mem(*cu_device).unwrap_or(8 * 1024 * 1024 * 1024);

        // Query SM count
        let multiprocessor_count = compat::device_get_attribute(
            *cu_device,
            CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT,
        )
        .map_err(|e| CudaFftError::DriverInit(e))? as u32;

        // Query max threads per block
        let max_threads_per_block = compat::device_get_attribute(
            *cu_device,
            CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
        )
        .map_err(|e| CudaFftError::DriverInit(e))? as u32;

        Ok(DeviceInfo {
            name,
            compute_capability: (major, minor),
            total_memory_bytes,
            multiprocessor_count,
            max_threads_per_block,
        })
    }

    // =========================================================================
    // PTX Caching for Faster Startup
    // =========================================================================

    /// Get the PTX cache directory path.
    ///
    /// Default: `~/.cache/stwo-prover/ptx/`
    fn get_cache_dir() -> Option<std::path::PathBuf> {
        // Try standard cache locations
        if let Some(home) = std::env::var_os("HOME") {
            let cache_dir = std::path::PathBuf::from(home)
                .join(".cache")
                .join("stwo-prover")
                .join("ptx");
            return Some(cache_dir);
        }

        // Fallback to temp directory
        Some(std::env::temp_dir().join("stwo-prover-ptx"))
    }

    /// Compute a hash of the kernel source for cache invalidation.
    ///
    /// Uses blake3 for fast hashing of potentially large kernel sources.
    fn compute_source_hash(source: &str) -> String {
        use blake3::Hasher;

        let mut hasher = Hasher::new();
        hasher.update(source.as_bytes());
        // Include library version for invalidation on updates
        hasher.update(env!("CARGO_PKG_VERSION").as_bytes());

        let hash = hasher.finalize();
        // Use first 16 bytes (32 hex chars) for reasonable uniqueness
        hex::encode(&hash.as_bytes()[..16])
    }

    /// Try to load pre-compiled PTX, fall back to runtime compilation.
    ///
    /// PTX loading priority:
    /// 1. Build-time compiled PTX (from OUT_DIR via build.rs)
    /// 2. User-provided PTX files (STWO_PTX_DIR environment variable)
    /// 3. Cached PTX markers (for tracking source changes)
    /// 4. Runtime NVRTC compilation (fallback)
    ///
    /// # Note on cudarc Limitations
    ///
    /// cudarc's `Ptx` type is opaque and doesn't expose construction from bytes.
    /// The current implementation uses NVRTC runtime compilation as the primary
    /// path, with cache markers to track compilation state.
    ///
    /// # Arguments
    /// * `kernel_name` - Human-readable kernel name for logging
    /// * `source` - CUDA C++ source code
    ///
    /// # Returns
    /// Compiled PTX (either from cache or freshly compiled)
    fn compile_or_load_cached(
        kernel_name: &str,
        source: &str,
    ) -> Result<cudarc::nvrtc::Ptx, CudaFftError> {
        // Check for build-time PTX directory
        if let Ok(ptx_dir) = std::env::var("STWO_PTX_BUILD_DIR") {
            let marker_path =
                std::path::PathBuf::from(&ptx_dir).join(format!("{}.marker", kernel_name));

            if marker_path.exists() {
                tracing::debug!(
                    "Found build-time PTX marker for {} at {:?}",
                    kernel_name,
                    marker_path
                );
            }
        }

        // Check for user-provided PTX files
        if let Ok(ptx_dir) = std::env::var("STWO_PTX_DIR") {
            let ptx_path = std::path::PathBuf::from(&ptx_dir).join(format!("{}.ptx", kernel_name));

            if ptx_path.exists() {
                tracing::info!(
                    "Loading pre-compiled PTX for {} from {:?}",
                    kernel_name,
                    ptx_path
                );
                // Note: cudarc doesn't support loading PTX from file directly
                // Would need to use CUDA driver API (cuModuleLoad)
            }
        }
        let source_hash = Self::compute_source_hash(source);

        // Check if we have a valid cache marker
        if let Some(cache_dir) = Self::get_cache_dir() {
            let marker_file = cache_dir.join(format!("{}_{}.marker", kernel_name, source_hash));

            if marker_file.exists() {
                // Source hasn't changed since last compilation
                // Still need to recompile due to cudarc limitations, but this is fast
                // as NVRTC uses its own internal caching
                tracing::debug!(
                    "{} source unchanged (hash: {}), recompiling with NVRTC cache",
                    kernel_name,
                    &source_hash[..8]
                );
            } else {
                tracing::info!(
                    "{} source changed or first compile (hash: {})",
                    kernel_name,
                    &source_hash[..8]
                );
            }

            // Compile and update marker
            return Self::compile_and_mark(kernel_name, source, &marker_file, &source_hash);
        }

        // No cache directory available - just compile
        tracing::debug!("PTX caching disabled (no cache directory)");
        Self::compile_with_timing(kernel_name, source)
    }

    /// Compile PTX and save marker file.
    fn compile_and_mark(
        kernel_name: &str,
        source: &str,
        marker_file: &std::path::Path,
        source_hash: &str,
    ) -> Result<cudarc::nvrtc::Ptx, CudaFftError> {
        let ptx = Self::compile_with_timing(kernel_name, source)?;

        // Create marker file for cache validation
        if let Some(parent) = marker_file.parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                tracing::debug!("Failed to create cache directory: {}", e);
            } else {
                // Write marker with hash and timestamp
                let marker_content = format!(
                    "{}\n{}\n",
                    source_hash,
                    std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs()
                );

                if let Err(e) = std::fs::write(marker_file, marker_content) {
                    tracing::debug!("Failed to write cache marker: {}", e);
                }
            }
        }

        Ok(ptx)
    }

    /// Compile PTX with timing instrumentation.
    fn compile_with_timing(
        kernel_name: &str,
        source: &str,
    ) -> Result<cudarc::nvrtc::Ptx, CudaFftError> {
        let start = std::time::Instant::now();

        let ptx = cudarc::nvrtc::compile_ptx(source).map_err(|e| {
            CudaFftError::KernelCompilation(format!("{} kernel: {:?}", kernel_name, e))
        })?;

        let compile_time = start.elapsed();
        tracing::info!("Compiled {} PTX in {:?}", kernel_name, compile_time);

        Ok(ptx)
    }

    /// Clear the PTX cache.
    ///
    /// Useful when kernel sources have been modified during development.
    pub fn clear_ptx_cache() -> Result<(), std::io::Error> {
        if let Some(cache_dir) = Self::get_cache_dir() {
            if cache_dir.exists() {
                std::fs::remove_dir_all(&cache_dir)?;
                tracing::info!("Cleared PTX cache at {:?}", cache_dir);
            }
        }
        Ok(())
    }

    // =========================================================================
    // Kernel Compilation
    // =========================================================================

    fn compile_kernels(device: &Arc<CudaDevice>) -> Result<CompiledKernels, CudaFftError> {
        // Compile or load cached FFT PTX
        let fft_ptx = Self::compile_or_load_cached("circle_fft", CIRCLE_FFT_CUDA_KERNEL)?;

        // Load FFT PTX into device
        device
            .load_ptx(
                fft_ptx,
                "circle_fft",
                &[
                    "bit_reverse_kernel",
                    "ifft_layer_kernel",
                    "fft_layer_kernel",
                    "ifft_shared_mem_kernel",
                    "denormalize_kernel",
                    "denormalize_vec4_kernel",
                ],
            )
            .map_err(|e| CudaFftError::KernelCompilation(format!("FFT load: {:?}", e)))?;

        // Compile or load cached FRI PTX
        use super::fft::FRI_FOLDING_CUDA_KERNEL;
        let fri_ptx = Self::compile_or_load_cached("fri_folding", FRI_FOLDING_CUDA_KERNEL)?;

        // Load FRI PTX into device
        device
            .load_ptx(
                fri_ptx,
                "fri_folding",
                &[
                    "fold_line_kernel",
                    "fold_circle_into_line_kernel",
                    "deinterleave_aos_to_soa_kernel",
                ],
            )
            .map_err(|e| CudaFftError::KernelCompilation(format!("FRI load: {:?}", e)))?;

        // Compile or load cached Quotient PTX
        use super::fft::QUOTIENT_CUDA_KERNEL;
        let quotient_ptx = Self::compile_or_load_cached("quotient", QUOTIENT_CUDA_KERNEL)?;

        // Load Quotient PTX into device (includes buffer gather and MLE kernels)
        device
            .load_ptx(
                quotient_ptx,
                "quotient",
                &[
                    "accumulate_quotients_kernel",
                    "eval_point_accumulate_kernel",
                    "copy_column_kernel",             // GPU-resident column copy
                    "gather_buffers_kernel",          // GPU-resident buffer gathering
                    "mle_fold_base_to_secure_kernel", // MLE fold: BaseField -> SecureField
                    "mle_fold_secure_kernel",         // MLE fold: SecureField -> SecureField
                    "gen_eq_evals_kernel",            // Generate equality evaluations for GKR
                ],
            )
            .map_err(|e| CudaFftError::KernelCompilation(format!("Quotient load: {:?}", e)))?;

        // Get FFT function handles
        let bit_reverse = device
            .get_func("circle_fft", "bit_reverse_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("bit_reverse_kernel not found".into())
            })?;

        let ifft_layer = device
            .get_func("circle_fft", "ifft_layer_kernel")
            .ok_or_else(|| CudaFftError::KernelCompilation("ifft_layer_kernel not found".into()))?;

        let fft_layer = device
            .get_func("circle_fft", "fft_layer_kernel")
            .ok_or_else(|| CudaFftError::KernelCompilation("fft_layer_kernel not found".into()))?;

        let ifft_shared_mem = device
            .get_func("circle_fft", "ifft_shared_mem_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("ifft_shared_mem_kernel not found".into())
            })?;

        // Get denormalization function handles
        let denormalize = device
            .get_func("circle_fft", "denormalize_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("denormalize_kernel not found".into())
            })?;

        let denormalize_vec4 = device
            .get_func("circle_fft", "denormalize_vec4_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("denormalize_vec4_kernel not found".into())
            })?;

        // Get FRI function handles
        let fold_line = device
            .get_func("fri_folding", "fold_line_kernel")
            .ok_or_else(|| CudaFftError::KernelCompilation("fold_line_kernel not found".into()))?;

        let fold_circle_into_line = device
            .get_func("fri_folding", "fold_circle_into_line_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("fold_circle_into_line_kernel not found".into())
            })?;

        let deinterleave_aos_to_soa = device
            .get_func("fri_folding", "deinterleave_aos_to_soa_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("deinterleave_aos_to_soa_kernel not found".into())
            })?;

        // Get Quotient function handle
        let accumulate_quotients = device
            .get_func("quotient", "accumulate_quotients_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("accumulate_quotients_kernel not found".into())
            })?;

        let eval_point_accumulate = device
            .get_func("quotient", "eval_point_accumulate_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("eval_point_accumulate_kernel not found".into())
            })?;

        // Get copy_column kernel for GPU-resident column gathering
        let copy_column = device
            .get_func("quotient", "copy_column_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("copy_column_kernel not found".into())
            })?;

        // Get MLE kernels for GKR operations
        let mle_fold_base_to_secure = device
            .get_func("quotient", "mle_fold_base_to_secure_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("mle_fold_base_to_secure_kernel not found".into())
            })?;

        let mle_fold_secure = device
            .get_func("quotient", "mle_fold_secure_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("mle_fold_secure_kernel not found".into())
            })?;

        let gen_eq_evals = device
            .get_func("quotient", "gen_eq_evals_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("gen_eq_evals_kernel not found".into())
            })?;

        // Compile or load cached Blake2s Merkle PTX
        use super::fft::BLAKE2S_MERKLE_CUDA_KERNEL;
        let merkle_ptx =
            Self::compile_or_load_cached("merkle_blake2s", BLAKE2S_MERKLE_CUDA_KERNEL)?;

        // Load Merkle PTX into device
        device
            .load_ptx(merkle_ptx, "merkle", &["merkle_layer_kernel"])
            .map_err(|e| CudaFftError::KernelCompilation(format!("Merkle load: {:?}", e)))?;

        // Get Merkle function handle
        let merkle_layer = device
            .get_func("merkle", "merkle_layer_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("merkle_layer_kernel not found".into())
            })?;

        // Compile or load cached Poseidon252 Merkle PTX
        use super::fft::POSEIDON252_MERKLE_CUDA_KERNEL;
        let poseidon_ptx =
            Self::compile_or_load_cached("merkle_poseidon252", POSEIDON252_MERKLE_CUDA_KERNEL)?;

        // Load Poseidon252 Merkle PTX into device
        device
            .load_ptx(
                poseidon_ptx,
                "merkle_poseidon252",
                &[
                    "poseidon252_merkle_layer_kernel",
                    "poseidon252_hash_many_chunked_kernel",
                    "poseidon252_hash_many_chunked_m31_kernel",
                ],
            )
            .map_err(|e| {
                CudaFftError::KernelCompilation(format!("Poseidon252 Merkle load: {:?}", e))
            })?;

        // Get Poseidon252 Merkle function handle
        let poseidon252_merkle_layer = device
            .get_func("merkle_poseidon252", "poseidon252_merkle_layer_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation("poseidon252_merkle_layer_kernel not found".into())
            })?;
        let poseidon252_hash_many_chunked = device
            .get_func("merkle_poseidon252", "poseidon252_hash_many_chunked_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation(
                    "poseidon252_hash_many_chunked_kernel not found".into(),
                )
            })?;
        let poseidon252_hash_many_chunked_m31 = device
            .get_func("merkle_poseidon252", "poseidon252_hash_many_chunked_m31_kernel")
            .ok_or_else(|| {
                CudaFftError::KernelCompilation(
                    "poseidon252_hash_many_chunked_m31_kernel not found".into(),
                )
            })?;

        tracing::info!(
            "Compiled FFT, FRI, Quotient, Merkle, and Poseidon252 Merkle kernels successfully"
        );

        Ok(CompiledKernels {
            bit_reverse,
            ifft_layer,
            fft_layer,
            ifft_shared_mem,
            denormalize,
            denormalize_vec4,
            fold_line,
            fold_circle_into_line,
            deinterleave_aos_to_soa,
            accumulate_quotients,
            eval_point_accumulate,
            copy_column,
            mle_fold_base_to_secure,
            mle_fold_secure,
            gen_eq_evals,
            merkle_layer,
            poseidon252_merkle_layer,
            poseidon252_hash_many_chunked,
            poseidon252_hash_many_chunked_m31,
        })
    }

    /// Execute inverse FFT on GPU.
    ///
    /// # Arguments
    /// * `data` - Input/output data (modified in place)
    /// * `twiddles_dbl` - Doubled twiddle factors for each layer
    /// * `log_size` - log2 of the data size
    ///
    /// # Returns
    /// The modified data after IFFT
    pub fn execute_ifft(
        &self,
        data: &mut [u32],
        twiddles_dbl: &[Vec<u32>],
        log_size: u32,
    ) -> Result<(), CudaFftError> {
        let n = 1usize << log_size;

        if data.len() != n {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} elements, got {}",
                n,
                data.len()
            )));
        }

        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA IFFT", log_size = log_size).entered();

        // Allocate device memory
        let mut d_data = self
            .device
            .htod_sync_copy(data)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Flatten twiddles and copy to device
        let flat_twiddles: Vec<u32> = twiddles_dbl.iter().flatten().copied().collect();
        let d_twiddles = self
            .device
            .htod_sync_copy(&flat_twiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Execute IFFT layers
        self.execute_ifft_layers(&mut d_data, &d_twiddles, log_size, twiddles_dbl)?;

        // Copy results back
        self.device
            .dtoh_sync_copy_into(&d_data, data)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        Ok(())
    }

    fn execute_ifft_layers(
        &self,
        d_data: &mut CudaSlice<u32>,
        d_twiddles: &CudaSlice<u32>,
        log_size: u32,
        twiddles_dbl: &[Vec<u32>],
    ) -> Result<(), CudaFftError> {
        let block_size = 256u32;
        let num_layers = twiddles_dbl.len();

        // Validate we have the expected number of twiddle layers
        if num_layers != log_size as usize {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} twiddle layers for log_size={}, got {}",
                log_size, log_size, num_layers
            )));
        }

        // Calculate twiddle offsets (as u32 for GPU)
        let mut twiddle_offsets: Vec<u32> = Vec::new();
        let mut offset = 0u32;
        for tw in twiddles_dbl {
            twiddle_offsets.push(offset);
            offset += tw.len() as u32;
        }

        // Shared memory kernel configuration:
        // - SHMEM_ELEMENTS = 1024 elements per block
        // - SHMEM_BLOCK_SIZE = 256 threads per block
        // - Can process up to 10 layers in shared memory (log2(1024) = 10)
        const SHMEM_ELEMENTS: u32 = 1024;
        const SHMEM_LOG_ELEMENTS: u32 = 10;
        const SHMEM_BLOCK_SIZE: u32 = 256;

        // Determine how many layers we can process in shared memory
        // We can process min(log_size, SHMEM_LOG_ELEMENTS) layers
        let shared_mem_layers = std::cmp::min(log_size, SHMEM_LOG_ELEMENTS);
        let n = 1u32 << log_size;

        if shared_mem_layers > 0 && n >= SHMEM_ELEMENTS {
            // Copy twiddle offsets to device
            let d_twiddle_offsets = self
                .device
                .htod_sync_copy(&twiddle_offsets)
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

            // Launch shared memory kernel for first layers
            let num_blocks = n / SHMEM_ELEMENTS;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks, 1, 1),
                block_dim: (SHMEM_BLOCK_SIZE, 1, 1),
                shared_mem_bytes: SHMEM_ELEMENTS * 4, // 4 bytes per u32
            };

            unsafe {
                self.kernels
                    .ifft_shared_mem
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut *d_data,
                            d_twiddles,
                            &d_twiddle_offsets,
                            shared_mem_layers,
                            log_size,
                        ),
                    )
                    .map_err(|e| {
                        CudaFftError::KernelExecution(format!("Shared mem kernel: {:?}", e))
                    })?;
            }

            // Sync after shared memory kernel
            self.device
                .synchronize()
                .map_err(|e| CudaFftError::KernelExecution(format!("Shared mem sync: {:?}", e)))?;

            // Process remaining layers with per-layer kernels
            for layer in (shared_mem_layers as usize)..num_layers {
                let n_twiddles = twiddles_dbl[layer].len() as u32;
                let butterflies_per_twiddle = 1u32 << layer;
                let total_butterflies = n_twiddles * butterflies_per_twiddle;
                let grid_size = (total_butterflies + block_size - 1) / block_size;

                let twiddle_offset = twiddle_offsets[layer] as usize;

                let cfg = LaunchConfig {
                    grid_dim: (grid_size, 1, 1),
                    block_dim: (block_size, 1, 1),
                    shared_mem_bytes: 0,
                };

                let twiddle_view = d_twiddles.slice(twiddle_offset..);

                unsafe {
                    self.kernels
                        .ifft_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut *d_data,
                                &twiddle_view,
                                layer as u32,
                                log_size,
                                n_twiddles,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        } else {
            // Small FFT: use per-layer kernels only
            for layer in 0..num_layers {
                let n_twiddles = twiddles_dbl[layer].len() as u32;
                let butterflies_per_twiddle = 1u32 << layer;
                let total_butterflies = n_twiddles * butterflies_per_twiddle;
                let grid_size = (total_butterflies + block_size - 1) / block_size;

                let twiddle_offset = twiddle_offsets[layer] as usize;

                let cfg = LaunchConfig {
                    grid_dim: (grid_size, 1, 1),
                    block_dim: (block_size, 1, 1),
                    shared_mem_bytes: 0,
                };

                let twiddle_view = d_twiddles.slice(twiddle_offset..);

                unsafe {
                    self.kernels
                        .ifft_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut *d_data,
                                &twiddle_view,
                                layer as u32,
                                log_size,
                                n_twiddles,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        }

        // Final sync
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Final sync failed: {:?}", e)))?;

        Ok(())
    }

    /// Execute IFFT on GPU memory that's already allocated.
    ///
    /// This is the high-performance path for persistent GPU memory.
    /// Data stays on GPU between calls, avoiding transfer overhead.
    ///
    /// # Arguments
    /// * `d_data` - Device memory containing the data (modified in place)
    /// * `d_twiddles` - Device memory containing flattened twiddles
    /// * `d_twiddle_offsets` - Device memory containing twiddle offsets per layer
    /// * `twiddles_dbl` - CPU twiddles (for layer size info)
    /// * `log_size` - log2 of data size
    pub fn execute_ifft_on_device(
        &self,
        d_data: &mut CudaSlice<u32>,
        d_twiddles: &CudaSlice<u32>,
        d_twiddle_offsets: &CudaSlice<u32>,
        twiddles_dbl: &[Vec<u32>],
        log_size: u32,
    ) -> Result<(), CudaFftError> {
        self.execute_ifft_layers_with_offsets(
            d_data,
            d_twiddles,
            d_twiddle_offsets,
            log_size,
            twiddles_dbl,
        )
    }

    fn execute_ifft_layers_with_offsets(
        &self,
        d_data: &mut CudaSlice<u32>,
        d_twiddles: &CudaSlice<u32>,
        d_twiddle_offsets: &CudaSlice<u32>,
        log_size: u32,
        twiddles_dbl: &[Vec<u32>],
    ) -> Result<(), CudaFftError> {
        let block_size = 256u32;
        let num_layers = twiddles_dbl.len();

        // Shared memory kernel configuration
        const SHMEM_ELEMENTS: u32 = 1024;
        const SHMEM_LOG_ELEMENTS: u32 = 10;
        const SHMEM_BLOCK_SIZE: u32 = 256;

        let shared_mem_layers = std::cmp::min(log_size, SHMEM_LOG_ELEMENTS);
        let n = 1u32 << log_size;

        // Calculate twiddle offsets for per-layer kernels
        let mut twiddle_offsets_cpu: Vec<u32> = Vec::new();
        let mut offset = 0u32;
        for tw in twiddles_dbl {
            twiddle_offsets_cpu.push(offset);
            offset += tw.len() as u32;
        }

        if shared_mem_layers > 0 && n >= SHMEM_ELEMENTS {
            // Launch shared memory kernel for first layers
            let num_blocks = n / SHMEM_ELEMENTS;

            let cfg = LaunchConfig {
                grid_dim: (num_blocks, 1, 1),
                block_dim: (SHMEM_BLOCK_SIZE, 1, 1),
                shared_mem_bytes: SHMEM_ELEMENTS * 4,
            };

            unsafe {
                self.kernels
                    .ifft_shared_mem
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut *d_data,
                            d_twiddles,
                            d_twiddle_offsets,
                            shared_mem_layers,
                            log_size,
                        ),
                    )
                    .map_err(|e| {
                        CudaFftError::KernelExecution(format!("Shared mem kernel: {:?}", e))
                    })?;
            }

            // Process remaining layers with per-layer kernels
            for layer in (shared_mem_layers as usize)..num_layers {
                let n_twiddles = twiddles_dbl[layer].len() as u32;
                let butterflies_per_twiddle = 1u32 << layer;
                let total_butterflies = n_twiddles * butterflies_per_twiddle;
                let grid_size = (total_butterflies + block_size - 1) / block_size;

                let twiddle_offset = twiddle_offsets_cpu[layer] as usize;

                let cfg = LaunchConfig {
                    grid_dim: (grid_size, 1, 1),
                    block_dim: (block_size, 1, 1),
                    shared_mem_bytes: 0,
                };

                let twiddle_view = d_twiddles.slice(twiddle_offset..);

                unsafe {
                    self.kernels
                        .ifft_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut *d_data,
                                &twiddle_view,
                                layer as u32,
                                log_size,
                                n_twiddles,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        } else {
            // Small FFT: use per-layer kernels only
            for layer in 0..num_layers {
                let n_twiddles = twiddles_dbl[layer].len() as u32;
                let butterflies_per_twiddle = 1u32 << layer;
                let total_butterflies = n_twiddles * butterflies_per_twiddle;
                let grid_size = (total_butterflies + block_size - 1) / block_size;

                let twiddle_offset = twiddle_offsets_cpu[layer] as usize;

                let cfg = LaunchConfig {
                    grid_dim: (grid_size, 1, 1),
                    block_dim: (block_size, 1, 1),
                    shared_mem_bytes: 0,
                };

                let twiddle_view = d_twiddles.slice(twiddle_offset..);

                unsafe {
                    self.kernels
                        .ifft_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut *d_data,
                                &twiddle_view,
                                layer as u32,
                                log_size,
                                n_twiddles,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        }

        // Sync at the end
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Final sync failed: {:?}", e)))?;

        Ok(())
    }

    /// Execute forward FFT on GPU.
    pub fn execute_fft(
        &self,
        data: &mut [u32],
        twiddles: &[Vec<u32>],
        log_size: u32,
    ) -> Result<(), CudaFftError> {
        let n = 1usize << log_size;

        if data.len() != n {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} elements, got {}",
                n,
                data.len()
            )));
        }

        let _span = tracing::span!(tracing::Level::INFO, "CUDA FFT", log_size = log_size).entered();

        // Allocate device memory
        let mut d_data = self
            .device
            .htod_sync_copy(data)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Flatten twiddles and copy to device
        let flat_twiddles: Vec<u32> = twiddles.iter().flatten().copied().collect();
        let d_twiddles = self
            .device
            .htod_sync_copy(&flat_twiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Execute FFT layers (reverse order of IFFT)
        self.execute_fft_layers(&mut d_data, &d_twiddles, log_size, twiddles)?;

        // Copy results back
        self.device
            .dtoh_sync_copy_into(&d_data, data)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        Ok(())
    }

    fn execute_fft_layers(
        &self,
        d_data: &mut CudaSlice<u32>,
        d_twiddles: &CudaSlice<u32>,
        log_size: u32,
        twiddles: &[Vec<u32>],
    ) -> Result<(), CudaFftError> {
        let block_size = 256u32;
        let num_layers = twiddles.len();

        // Validate we have the expected number of twiddle layers
        if num_layers != log_size as usize {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} twiddle layers for log_size={}, got {}",
                log_size, log_size, num_layers
            )));
        }

        // Calculate twiddle offsets
        let mut twiddle_offsets: Vec<usize> = Vec::new();
        let mut offset = 0usize;
        for tw in twiddles {
            twiddle_offsets.push(offset);
            offset += tw.len();
        }

        // Execute layers in reverse order for forward FFT
        // Layer 0 is circle layer, layers 1+ are line layers
        for layer in (0..num_layers).rev() {
            let n_twiddles = twiddles[layer].len() as u32;
            let butterflies_per_twiddle = 1u32 << layer;
            let total_butterflies = n_twiddles * butterflies_per_twiddle;
            let grid_size = (total_butterflies + block_size - 1) / block_size;

            let twiddle_offset = twiddle_offsets[layer];

            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            // Create a twiddle view for this layer
            let twiddle_view = d_twiddles.slice(twiddle_offset..);

            unsafe {
                // Reborrow d_data each iteration to avoid move in loop
                self.kernels
                    .fft_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut *d_data,
                            &twiddle_view,
                            layer as u32,
                            log_size,
                            n_twiddles,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }
        }

        // Synchronize
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        Ok(())
    }

    /// Execute bit reversal permutation on GPU.
    pub fn bit_reverse(&self, data: &mut [u32], log_size: u32) -> Result<(), CudaFftError> {
        let n = 1usize << log_size;

        if data.len() != n {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} elements, got {}",
                n,
                data.len()
            )));
        }

        // Allocate and copy
        let mut d_data = self
            .device
            .htod_sync_copy(data)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch bit reverse kernel
        let block_size = 256u32;
        let grid_size = ((n as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .bit_reverse
                .clone()
                .launch(cfg, (&mut d_data, log_size))
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        self.device
            .dtoh_sync_copy_into(&d_data, data)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        Ok(())
    }

    /// Get device memory info.
    pub fn memory_info(&self) -> (usize, usize) {
        // (free, total) - cudarc doesn't expose this directly
        (
            self.device_info.total_memory_bytes / 2, // Estimate
            self.device_info.total_memory_bytes,
        )
    }

    // =========================================================================
    // Denormalization Operations
    // =========================================================================

    /// Execute denormalization on GPU memory.
    ///
    /// After IFFT, we need to divide by the domain size to get correct coefficients.
    /// This multiplies each element by the precomputed inverse of the domain size.
    ///
    /// # Arguments
    /// * `d_data` - Device memory containing the data (modified in place)
    /// * `denorm_factor` - Precomputed 1/n mod P
    /// * `n` - Number of elements
    pub fn execute_denormalize_on_device(
        &self,
        d_data: &mut CudaSlice<u32>,
        denorm_factor: u32,
        n: u32,
    ) -> Result<(), CudaFftError> {
        let _span = tracing::span!(tracing::Level::DEBUG, "CUDA denormalize", n = n).entered();

        // Use vectorized kernel for large sizes (must be multiple of 4)
        if n >= 1024 && n % 4 == 0 {
            let block_size = 256u32;
            let grid_size = (n / 4 + block_size - 1) / block_size;

            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                self.kernels
                    .denormalize_vec4
                    .clone()
                    .launch(cfg, (&mut *d_data, denorm_factor, n))
                    .map_err(|e| {
                        CudaFftError::KernelExecution(format!("Denormalize vec4: {:?}", e))
                    })?;
            }
        } else {
            // Fall back to scalar kernel for small sizes or non-multiple-of-4
            let block_size = 256u32;
            let grid_size = (n + block_size - 1) / block_size;

            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                self.kernels
                    .denormalize
                    .clone()
                    .launch(cfg, (&mut *d_data, denorm_factor, n))
                    .map_err(|e| CudaFftError::KernelExecution(format!("Denormalize: {:?}", e)))?;
            }
        }

        Ok(())
    }

    /// Execute denormalization on CPU data (transfers to/from GPU).
    pub fn execute_denormalize(
        &self,
        data: &mut [u32],
        denorm_factor: u32,
    ) -> Result<(), CudaFftError> {
        let n = data.len() as u32;

        // Allocate and copy
        let mut d_data = self
            .device
            .htod_sync_copy(data)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Execute on device
        self.execute_denormalize_on_device(&mut d_data, denorm_factor, n)?;

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        self.device
            .dtoh_sync_copy_into(&d_data, data)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        Ok(())
    }

    // =========================================================================
    // FRI Folding Operations
    // =========================================================================

    /// Execute FRI fold_line on GPU.
    ///
    /// Folds a line evaluation by factor of 2 using the FRI protocol.
    pub fn execute_fold_line(
        &self,
        input: &[u32],
        itwiddles: &[u32],
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<Vec<u32>, CudaFftError> {
        // Validate input
        if input.len() != n * 4 {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} u32 values, got {}",
                n * 4,
                input.len()
            )));
        }
        if itwiddles.len() < n / 2 {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected at least {} twiddles, got {}",
                n / 2,
                itwiddles.len()
            )));
        }

        let _span = tracing::span!(tracing::Level::INFO, "CUDA fold_line", n = n).entered();

        let n_output = n / 2;

        // Allocate device memory
        let d_input = self
            .device
            .htod_sync_copy(input)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_itwiddles = self
            .device
            .htod_sync_copy(itwiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n_output * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_output as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_line
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        &d_input,
                        &d_itwiddles,
                        &d_alpha,
                        n as u32,
                        log_n,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u32; n_output * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!("GPU fold_line completed: {} -> {} elements", n, n_output);

        Ok(output)
    }

    /// Execute FRI fold_circle_into_line on GPU.
    ///
    /// Folds circle evaluation into line evaluation (accumulated).
    pub fn execute_fold_circle_into_line(
        &self,
        dst: &mut [u32],
        src: &[u32],
        itwiddles: &[u32],
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<(), CudaFftError> {
        // Validate input
        if src.len() != n * 4 {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} u32 values in src, got {}",
                n * 4,
                src.len()
            )));
        }
        let n_dst = n / 2;
        if dst.len() != n_dst * 4 {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} u32 values in dst, got {}",
                n_dst * 4,
                dst.len()
            )));
        }
        if itwiddles.len() < n_dst {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected at least {} twiddles, got {}",
                n_dst,
                itwiddles.len()
            )));
        }

        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA fold_circle_into_line", n = n).entered();

        // Allocate device memory
        let d_src = self
            .device
            .htod_sync_copy(src)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_dst = self
            .device
            .htod_sync_copy(dst)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_itwiddles = self
            .device
            .htod_sync_copy(itwiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_dst as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_circle_into_line
                .clone()
                .launch(
                    cfg,
                    (&mut d_dst, &d_src, &d_itwiddles, &d_alpha, n as u32, log_n),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        self.device
            .dtoh_sync_copy_into(&d_dst, dst)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU fold_circle_into_line completed: {} -> {} elements",
            n,
            n_dst
        );

        Ok(())
    }

    // =========================================================================
    // GPU-Resident FRI Folding Operations
    // =========================================================================

    /// Execute FRI fold_line with GPU-resident input.
    ///
    /// Unlike `execute_fold_line`, this accepts a `CudaSlice<u32>` that is
    /// already on the GPU (from a previous fold round), eliminating the H2D
    /// transfer. Returns both the GPU-resident output (for caching) and a
    /// CPU copy (for decommitment).
    pub fn execute_fold_line_resident(
        &self,
        d_input: &CudaSlice<u32>,
        itwiddles: &[u32],
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<(CudaSlice<u32>, Vec<u32>), CudaFftError> {
        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA fold_line_resident", n = n).entered();

        let n_output = n / 2;

        // Twiddles and alpha still come from CPU (small, ~n/2 u32s)
        let d_itwiddles = self
            .device
            .htod_sync_copy(itwiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n_output * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_output as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_line
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        d_input,
                        &d_itwiddles,
                        &d_alpha,
                        n as u32,
                        log_n,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and D2H copy (needed for decommitment)
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut cpu_output = vec![0u32; n_output * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut cpu_output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU fold_line_resident completed: {} -> {} elements (0 H2D)",
            n,
            n_output
        );

        Ok((d_output, cpu_output))
    }

    /// Like `execute_fold_line_resident` but accepts pre-uploaded twiddles on GPU,
    /// eliminating the per-round twiddle H2D transfer.
    pub fn execute_fold_line_resident_preloaded(
        &self,
        d_input: &CudaSlice<u32>,
        d_itwiddles: &CudaSlice<u32>,
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<(CudaSlice<u32>, Vec<u32>), CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA fold_line_resident_preloaded",
            n = n
        )
        .entered();

        let n_output = n / 2;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n_output * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_output as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_line
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        d_input,
                        d_itwiddles,
                        &d_alpha,
                        n as u32,
                        log_n,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // dtoh_sync_copy_into implicitly waits for kernel completion
        let mut cpu_output = vec![0u32; n_output * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut cpu_output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU fold_line_resident_preloaded completed: {} -> {} elements",
            n,
            n_output
        );

        Ok((d_output, cpu_output))
    }

    /// Execute FRI fold_line keeping output GPU-resident only (no D2H transfer).
    ///
    /// Returns just the `CudaSlice<u32>` output on GPU. The caller is responsible
    /// for deferring the D2H download until the CPU data is actually needed
    /// (e.g., during decommit). This avoids the synchronous D2H that
    /// `execute_fold_line_resident_preloaded` performs every round.
    pub fn execute_fold_line_gpu_only(
        &self,
        d_input: &CudaSlice<u32>,
        d_itwiddles: &CudaSlice<u32>,
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA fold_line_gpu_only", n = n).entered();

        let n_output = n / 2;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n_output * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_output as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_line
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        d_input,
                        d_itwiddles,
                        &d_alpha,
                        n as u32,
                        log_n,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize to ensure kernel completion without downloading data
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("sync: {:?}", e)))?;

        tracing::info!(
            "GPU fold_line_gpu_only completed: {} -> {} elements (no D2H)",
            n,
            n_output
        );

        Ok(d_output)
    }

    /// Execute FRI fold_circle_into_line with GPU-resident output caching.
    ///
    /// This performs the fold and returns the GPU-resident output `CudaSlice`
    /// alongside the CPU result, so the next `fold_line` can skip H2D.
    pub fn execute_fold_circle_into_line_resident(
        &self,
        dst: &mut [u32],
        src: &[u32],
        itwiddles: &[u32],
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n_dst = n / 2;

        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA fold_circle_into_line_resident",
            n = n
        )
        .entered();

        // All inputs come from CPU for fold_circle_into_line (first fold)
        let d_src = self
            .device
            .htod_sync_copy(src)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Allocate dst on GPU — kernel overwrites all output, no need to upload CPU data
        let mut d_dst: CudaSlice<u32> = unsafe { self.device.alloc::<u32>(n_dst * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_itwiddles = self
            .device
            .htod_sync_copy(itwiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_dst as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_circle_into_line
                .clone()
                .launch(
                    cfg,
                    (&mut d_dst, &d_src, &d_itwiddles, &d_alpha, n as u32, log_n),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and D2H copy
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        self.device
            .dtoh_sync_copy_into(&d_dst, dst)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU fold_circle_into_line_resident completed: {} -> {} elements",
            n,
            n_dst
        );

        Ok(d_dst)
    }

    /// Like `execute_fold_circle_into_line_resident` but accepts pre-uploaded
    /// twiddles on GPU, eliminating the twiddle H2D transfer.
    pub fn execute_fold_circle_into_line_resident_preloaded(
        &self,
        dst: &mut [u32],
        src: &[u32],
        d_itwiddles: &CudaSlice<u32>,
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n_dst = n / 2;

        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA fold_circle_into_line_resident_preloaded",
            n = n
        )
        .entered();

        let d_src = self
            .device
            .htod_sync_copy(src)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Allocate dst on GPU zeroed — kernel reads dst (dst = dst*alpha_sq + f_prime)
        let mut d_dst: CudaSlice<u32> = self
            .device
            .alloc_zeros::<u32>(n_dst * 4)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_dst as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_circle_into_line
                .clone()
                .launch(
                    cfg,
                    (&mut d_dst, &d_src, d_itwiddles, &d_alpha, n as u32, log_n),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        self.device
            .dtoh_sync_copy_into(&d_dst, dst)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU fold_circle_into_line_resident_preloaded completed: {} -> {} elements",
            n,
            n_dst
        );

        Ok(d_dst)
    }

    /// Like `execute_fold_circle_into_line_resident_preloaded`, but takes
    /// a GPU-resident source (`d_src`) instead of a CPU slice. Avoids the
    /// H2D transfer for `src` when the data is already on the device.
    pub fn execute_fold_circle_into_line_from_gpu(
        &self,
        dst: &mut [u32],
        d_src: &CudaSlice<u32>,
        d_itwiddles: &CudaSlice<u32>,
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n_dst = n / 2;

        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA fold_circle_into_line_from_gpu",
            n = n
        )
        .entered();

        // Allocate dst on GPU zeroed — kernel reads dst (dst = dst*alpha_sq + f_prime)
        let mut d_dst: CudaSlice<u32> = self
            .device
            .alloc_zeros::<u32>(n_dst * 4)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_dst as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_circle_into_line
                .clone()
                .launch(
                    cfg,
                    (&mut d_dst, d_src, d_itwiddles, &d_alpha, n as u32, log_n),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        self.device
            .dtoh_sync_copy_into(&d_dst, dst)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU fold_circle_into_line_from_gpu completed: {} -> {} elements",
            n,
            n_dst
        );

        Ok(d_dst)
    }

    /// GPU-only fold_circle_into_line: src on GPU, dst allocated on GPU (no upload),
    /// no D2H. Returns GPU-resident output. Eliminates the wasted H2D of dst
    /// (kernel overwrites all output) and defers D2H to caller.
    pub fn execute_fold_circle_into_line_gpu_only(
        &self,
        d_src: &CudaSlice<u32>,
        d_itwiddles: &CudaSlice<u32>,
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n_dst = n / 2;

        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA fold_circle_into_line_gpu_only",
            n = n
        )
        .entered();

        // Allocate dst on GPU — no need to upload CPU data since kernel overwrites all output
        let mut d_dst: CudaSlice<u32> = unsafe { self.device.alloc::<u32>(n_dst * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_dst as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_circle_into_line
                .clone()
                .launch(
                    cfg,
                    (&mut d_dst, d_src, d_itwiddles, &d_alpha, n as u32, log_n),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("sync: {:?}", e)))?;

        tracing::info!(
            "GPU fold_circle_into_line_gpu_only completed: {} -> {} elements (no D2H)",
            n,
            n_dst
        );

        Ok(d_dst)
    }

    /// Fully GPU-resident fold_circle_into_line: both dst and src on GPU, no D2H.
    /// Used when dst already has GPU-cached data from a prior fold_line (GPU-resident pipeline).
    pub fn execute_fold_circle_into_line_fully_gpu(
        &self,
        d_dst: &CudaSlice<u32>,
        d_src: &CudaSlice<u32>,
        d_itwiddles: &CudaSlice<u32>,
        alpha: &[u32; 4],
        n: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n_dst = n / 2;

        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA fold_circle_into_line_fully_gpu",
            n = n
        )
        .entered();

        // Copy dst to mutable output (kernel accumulates: dst = dst * alpha^2 + fold_result)
        let mut d_output: CudaSlice<u32> = unsafe { self.device.alloc::<u32>(n_dst * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        self.device
            .dtod_copy(d_dst, &mut d_output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("dtod: {:?}", e)))?;

        let d_alpha = self
            .device
            .htod_sync_copy(alpha)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_dst as u32) + block_size - 1) / block_size;
        let log_n = n.ilog2();

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .fold_circle_into_line
                .clone()
                .launch(
                    cfg,
                    (&mut d_output, d_src, d_itwiddles, &d_alpha, n as u32, log_n),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("sync: {:?}", e)))?;

        tracing::info!(
            "GPU fold_circle_into_line_fully_gpu completed: {} -> {} elements (no D2H)",
            n,
            n_dst
        );

        Ok(d_output)
    }

    /// De-interleave AoS GPU buffer into 4 SoA column CudaSlices on GPU.
    /// Input: [c0,c1,c2,c3, c0,c1,c2,c3, ...] (n*4 u32s)
    /// Output: 4 CudaSlices each of length n
    pub fn execute_deinterleave_aos_to_soa(
        &self,
        d_aos: &CudaSlice<u32>,
        n: usize,
    ) -> Result<[CudaSlice<u32>; 4], CudaFftError> {
        let mut d_col0 = unsafe { self.device.alloc::<u32>(n) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let mut d_col1 = unsafe { self.device.alloc::<u32>(n) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let mut d_col2 = unsafe { self.device.alloc::<u32>(n) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let mut d_col3 = unsafe { self.device.alloc::<u32>(n) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .deinterleave_aos_to_soa
                .clone()
                .launch(
                    cfg,
                    (
                        d_aos,
                        &mut d_col0,
                        &mut d_col1,
                        &mut d_col2,
                        &mut d_col3,
                        n as u32,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        Ok([d_col0, d_col1, d_col2, d_col3])
    }

    // =========================================================================
    // Quotient Accumulation Operations
    // =========================================================================

    /// Evaluate one OODS point directly from polynomial coefficients on GPU.
    ///
    /// `coeffs` are M31 coefficients in FFT basis order.
    /// `twiddles_aos` are per-coefficient QM31 twiddles packed as AoS:
    /// `[t0.a0,t0.a1,t0.a2,t0.a3, t1.a0,...]`.
    pub fn execute_eval_point_from_coeffs(
        &self,
        coeffs: &[u32],
        twiddles_aos: &[u32],
    ) -> Result<[u32; 4], CudaFftError> {
        let n_coeffs = coeffs.len();
        if twiddles_aos.len() != n_coeffs * 4 {
            return Err(CudaFftError::InvalidSize(format!(
                "twiddles length mismatch: expected {}, got {}",
                n_coeffs * 4,
                twiddles_aos.len()
            )));
        }
        if n_coeffs == 0 {
            return Ok([0; 4]);
        }

        let d_coeffs = self
            .device
            .htod_sync_copy(coeffs)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let d_twiddles = self
            .device
            .htod_sync_copy(twiddles_aos)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let mut d_accum = self
            .device
            .alloc_zeros::<u64>(4)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_coeffs as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .eval_point_accumulate
                .clone()
                .launch(cfg, (&d_coeffs, &d_twiddles, &mut d_accum, n_coeffs as u32))
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let accum = self
            .device
            .dtoh_sync_copy(&d_accum)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        Ok([
            crate::core::fields::m31::M31::reduce(accum[0]).0,
            crate::core::fields::m31::M31::reduce(accum[1]).0,
            crate::core::fields::m31::M31::reduce(accum[2]).0,
            crate::core::fields::m31::M31::reduce(accum[3]).0,
        ])
    }

    /// Upload quotient columns once and return a reusable device buffer.
    pub fn upload_accumulate_columns(
        &self,
        columns: &[Vec<u32>],
        n_points: usize,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n_columns = columns.len();

        // Flatten columns (interleave by point, not by column)
        // Layout: col0[0], col1[0], col2[0], ..., col0[1], col1[1], ...
        let mut flat_columns: Vec<u32> = Vec::with_capacity(n_columns * n_points);
        for col in columns {
            flat_columns.extend_from_slice(col);
        }

        self.device
            .htod_sync_copy(&flat_columns)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))
    }

    /// Execute quotient accumulation on GPU using pre-uploaded columns.
    pub fn execute_accumulate_quotients_with_device_columns(
        &self,
        d_columns: &CudaSlice<u32>,
        n_columns: usize,
        line_coeffs: &[[u32; 12]],
        denom_inv: &[u32],
        batch_sizes: &[usize],
        col_indices: &[usize],
        n_points: usize,
    ) -> Result<Vec<u32>, CudaFftError> {
        let n_batches = batch_sizes.len();

        // Flatten line coefficients
        let flat_line_coeffs: Vec<u32> = line_coeffs
            .iter()
            .flat_map(|coeffs| coeffs.iter().copied())
            .collect();

        // Convert batch_sizes and col_indices to u32
        let batch_sizes_u32: Vec<u32> = batch_sizes.iter().map(|&s| s as u32).collect();
        let col_indices_u32: Vec<u32> = col_indices.iter().map(|&i| i as u32).collect();

        let d_line_coeffs = self
            .device
            .htod_sync_copy(&flat_line_coeffs)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_denom_inv = self
            .device
            .htod_sync_copy(denom_inv)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_batch_sizes = self
            .device
            .htod_sync_copy(&batch_sizes_u32)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_col_indices = self
            .device
            .htod_sync_copy(&col_indices_u32)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n_points * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_points as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .accumulate_quotients
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        d_columns,
                        &d_line_coeffs,
                        &d_denom_inv,
                        &d_batch_sizes,
                        &d_col_indices,
                        n_batches as u32,
                        n_points as u32,
                        n_columns as u32,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u32; n_points * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        Ok(output)
    }

    /// Execute quotient accumulation on GPU.
    pub fn execute_accumulate_quotients(
        &self,
        columns: &[Vec<u32>],
        line_coeffs: &[[u32; 12]],
        denom_inv: &[u32],
        batch_sizes: &[usize],
        col_indices: &[usize],
        n_points: usize,
    ) -> Result<Vec<u32>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA accumulate_quotients",
            n_points = n_points
        )
        .entered();

        let n_columns = columns.len();
        let n_batches = batch_sizes.len();

        let d_columns = self.upload_accumulate_columns(columns, n_points)?;
        let output = self.execute_accumulate_quotients_with_device_columns(
            &d_columns,
            n_columns,
            line_coeffs,
            denom_inv,
            batch_sizes,
            col_indices,
            n_points,
        )?;

        tracing::info!(
            "GPU accumulate_quotients completed: {} points, {} batches",
            n_points,
            n_batches
        );

        Ok(output)
    }

    // =========================================================================
    // Merkle Hashing Operations
    // =========================================================================

    /// Execute Blake2s Merkle hashing on GPU.
    pub fn execute_blake2s_merkle(
        &self,
        columns: &[Vec<u32>],
        prev_layer: Option<&[u8]>,
        n_hashes: usize,
    ) -> Result<Vec<u8>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA blake2s_merkle",
            n_hashes = n_hashes
        )
        .entered();

        let n_columns = columns.len();

        // Flatten columns
        let flat_columns: Vec<u32> = columns.iter().flat_map(|col| col.iter().copied()).collect();

        // Allocate device memory for columns (if any)
        let d_columns = if n_columns > 0 {
            Some(
                self.device
                    .htod_sync_copy(&flat_columns)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        // Allocate device memory for previous layer (if any)
        let d_prev_layer = if let Some(prev) = prev_layer {
            Some(
                self.device
                    .htod_sync_copy(prev)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        // Allocate output (32 bytes per hash)
        let mut d_output = unsafe { self.device.alloc::<u8>(n_hashes * 32) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_hashes as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        let has_prev_layer = if prev_layer.is_some() { 1u32 } else { 0u32 };

        unsafe {
            // We need to handle the optional parameters carefully
            // If columns is None, pass a null-like slice
            // If prev_layer is None, pass a null-like slice

            match (&d_columns, &d_prev_layer) {
                (Some(cols), Some(prev)) => {
                    self.kernels
                        .merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                cols,
                                prev,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev_layer,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (Some(cols), None) => {
                    // Need a dummy buffer for prev_layer
                    let dummy_prev = self
                        .device
                        .alloc::<u8>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                cols,
                                &dummy_prev,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev_layer,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (None, Some(prev)) => {
                    // Need a dummy buffer for columns
                    let dummy_cols = self
                        .device
                        .alloc::<u32>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                &dummy_cols,
                                prev,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev_layer,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (None, None) => {
                    return Err(CudaFftError::InvalidSize(
                        "Merkle hashing requires either columns or prev_layer".to_string(),
                    ));
                }
            }
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u8; n_hashes * 32];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!("GPU blake2s_merkle completed: {} hashes", n_hashes);

        Ok(output)
    }

    // =========================================================================
    // Poseidon252 Merkle GPU Kernel
    // =========================================================================

    /// Execute Poseidon252 Merkle layer hashing on GPU.
    ///
    /// # Arguments
    /// * `columns` - Column data (each column is a Vec<u32> of M31 values)
    /// * `prev_layer` - Previous layer hashes (32 bytes / 4×u64 per node), or None for leaves
    /// * `n_hashes` - Number of hash nodes to compute
    /// * `d_round_constants` - Device buffer with 107 compressed Poseidon252 round constants (4×u64 each)
    pub fn execute_poseidon252_merkle(
        &self,
        columns: &[Vec<u32>],
        prev_layer: Option<&[u64]>,
        n_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<Vec<u64>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_merkle",
            n_hashes = n_hashes
        )
        .entered();

        let n_columns = columns.len();
        let col_stride = n_hashes as u32;

        // Flatten columns (column-major: col0[0..n], col1[0..n], ...)
        let flat_columns: Vec<u32> = columns.iter().flat_map(|col| col.iter().copied()).collect();

        // Upload columns
        let d_columns = if n_columns > 0 {
            Some(
                self.device
                    .htod_sync_copy(&flat_columns)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        // Upload prev_layer (4 u64s per node, 2*n_hashes nodes)
        let d_prev_layer = if let Some(prev) = prev_layer {
            Some(
                self.device
                    .htod_sync_copy(prev)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        // Output: 4 u64s per hash node
        let mut d_output = unsafe { self.device.alloc::<u64>(n_hashes * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_hashes as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        let has_prev: u32 = if prev_layer.is_some() { 1 } else { 0 };

        unsafe {
            match (&d_columns, &d_prev_layer) {
                (Some(cols), Some(prev)) => {
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                cols,
                                prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (Some(cols), None) => {
                    let dummy_prev = self
                        .device
                        .alloc::<u64>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                cols,
                                &dummy_prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (None, Some(prev)) => {
                    let dummy_cols = self
                        .device
                        .alloc::<u32>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                &dummy_cols,
                                prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (None, None) => {
                    return Err(CudaFftError::InvalidSize(
                        "Poseidon252 Merkle hashing requires either columns or prev_layer"
                            .to_string(),
                    ));
                }
            }
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u64; n_hashes * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!("GPU poseidon252_merkle completed: {} hashes", n_hashes);
        Ok(output)
    }

    /// Execute chunked Poseidon252 hash_many for many independent segments.
    ///
    /// Each segment `i` is described by `offsets[i]` and `lengths[i]` over `inputs`
    /// (where `inputs` is flattened felt252 data in 4x u64 limbs per element).
    /// The kernel computes:
    ///   running = 0
    ///   for each chunk:
    ///     running = poseidon_hash_many([running] + chunk)
    ///
    /// Output is one felt252 hash per segment (4x u64 limbs each).
    pub fn execute_poseidon252_hash_many_chunked(
        &self,
        inputs: &[u64],
        offsets: &[u32],
        lengths: &[u32],
        chunk_size: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<Vec<u64>, CudaFftError> {
        if offsets.len() != lengths.len() {
            return Err(CudaFftError::InvalidSize(format!(
                "offsets/lengths mismatch: {} vs {}",
                offsets.len(),
                lengths.len()
            )));
        }
        if inputs.len() % 4 != 0 {
            return Err(CudaFftError::InvalidSize(format!(
                "inputs must be packed felt252 limbs (len % 4 == 0), got {}",
                inputs.len()
            )));
        }
        if chunk_size == 0 {
            return Err(CudaFftError::InvalidSize(
                "chunk_size must be > 0".to_string(),
            ));
        }

        let n_segments = offsets.len();
        if n_segments == 0 {
            return Ok(Vec::new());
        }

        let d_inputs = if inputs.is_empty() {
            None
        } else {
            Some(
                self.device
                    .htod_sync_copy(inputs)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        };
        let d_offsets = self
            .device
            .htod_sync_copy(offsets)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let d_lengths = self
            .device
            .htod_sync_copy(lengths)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u64>(n_segments * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_segments as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            if let Some(d_inputs) = &d_inputs {
                self.kernels
                    .poseidon252_hash_many_chunked
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_output,
                            d_inputs,
                            &d_offsets,
                            &d_lengths,
                            d_round_constants,
                            n_segments as u32,
                            chunk_size as u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            } else {
                // No felt inputs: segments are empty, so kernel should return 0 per segment.
                let dummy_inputs = self
                    .device
                    .alloc::<u64>(4)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                self.kernels
                    .poseidon252_hash_many_chunked
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_output,
                            &dummy_inputs,
                            &d_offsets,
                            &d_lengths,
                            d_round_constants,
                            n_segments as u32,
                            chunk_size as u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u64; n_segments * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
        Ok(output)
    }

    /// Execute chunked Poseidon252 hash_many for many independent segments over raw M31 inputs.
    ///
    /// Each segment `i` is described by `offsets[i]` and `lengths[i]` over `inputs_m31`.
    /// M31 values are packed on GPU in base-2^31 groups of 7 (same semantics as CPU packing),
    /// then hashed as:
    ///   running = 0
    ///   for each packed chunk:
    ///     running = poseidon_hash_many([running] + chunk)
    pub fn execute_poseidon252_hash_many_chunked_m31(
        &self,
        inputs_m31: &[u32],
        offsets: &[u32],
        lengths: &[u32],
        chunk_size: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<Vec<u64>, CudaFftError> {
        if offsets.len() != lengths.len() {
            return Err(CudaFftError::InvalidSize(format!(
                "offsets/lengths mismatch: {} vs {}",
                offsets.len(),
                lengths.len()
            )));
        }
        if chunk_size == 0 {
            return Err(CudaFftError::InvalidSize(
                "chunk_size must be > 0".to_string(),
            ));
        }

        let n_segments = offsets.len();
        if n_segments == 0 {
            return Ok(Vec::new());
        }

        let d_inputs = if inputs_m31.is_empty() {
            None
        } else {
            Some(
                self.device
                    .htod_sync_copy(inputs_m31)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        };
        let d_offsets = self
            .device
            .htod_sync_copy(offsets)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
        let d_lengths = self
            .device
            .htod_sync_copy(lengths)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u64>(n_segments * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_segments as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            if let Some(d_inputs) = &d_inputs {
                self.kernels
                    .poseidon252_hash_many_chunked_m31
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_output,
                            d_inputs,
                            &d_offsets,
                            &d_lengths,
                            d_round_constants,
                            n_segments as u32,
                            chunk_size as u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            } else {
                let dummy_inputs = self
                    .device
                    .alloc::<u32>(1)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                self.kernels
                    .poseidon252_hash_many_chunked_m31
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_output,
                            &dummy_inputs,
                            &d_offsets,
                            &d_lengths,
                            d_round_constants,
                            n_segments as u32,
                            chunk_size as u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u64; n_segments * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
        Ok(output)
    }

    /// Execute Poseidon252 Merkle layer hashing with pre-uploaded GPU column data.
    ///
    /// Like `execute_poseidon252_merkle`, but accepts a `CudaSlice<u32>` that is
    /// already on GPU in column-major SoA layout, eliminating the H2D transfer.
    pub fn execute_poseidon252_merkle_from_gpu(
        &self,
        d_columns: &CudaSlice<u32>,
        n_columns: usize,
        prev_layer: Option<&[u64]>,
        n_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<Vec<u64>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_merkle_from_gpu",
            n_hashes = n_hashes
        )
        .entered();

        let col_stride = n_hashes as u32;

        let d_prev_layer = if let Some(prev) = prev_layer {
            Some(
                self.device
                    .htod_sync_copy(prev)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        let mut d_output = unsafe { self.device.alloc::<u64>(n_hashes * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_hashes as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        let has_prev: u32 = if prev_layer.is_some() { 1 } else { 0 };

        unsafe {
            match &d_prev_layer {
                Some(prev) => {
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                d_columns,
                                prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                None => {
                    let dummy_prev = self
                        .device
                        .alloc::<u64>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                d_columns,
                                &dummy_prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u64; n_hashes * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU poseidon252_merkle_from_gpu completed: {} hashes (no column H2D)",
            n_hashes
        );
        Ok(output)
    }

    /// Execute Poseidon252 Merkle layer with GPU-resident prev_layer.
    ///
    /// Takes `d_prev_layer` as an already-uploaded `CudaSlice<u64>` instead of
    /// a CPU slice, eliminating the prev_layer serialize + H2D per layer.
    /// Returns `(Vec<u64>, CudaSlice<u64>)` — both CPU output (for trait) and
    /// GPU output (to cache for next layer).
    pub fn execute_poseidon252_merkle_gpu_prev(
        &self,
        columns: &[Vec<u32>],
        d_prev_layer: Option<&CudaSlice<u64>>,
        n_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<(Vec<u64>, CudaSlice<u64>), CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_merkle_gpu_prev",
            n_hashes = n_hashes
        )
        .entered();

        let n_columns = columns.len();
        let col_stride = n_hashes as u32;

        // Upload columns (if any)
        let d_columns = if n_columns > 0 {
            let flat_columns: Vec<u32> =
                columns.iter().flat_map(|col| col.iter().copied()).collect();
            Some(
                self.device
                    .htod_sync_copy(&flat_columns)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        let mut d_output = unsafe { self.device.alloc::<u64>(n_hashes * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_hashes as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        let has_prev: u32 = if d_prev_layer.is_some() { 1 } else { 0 };

        unsafe {
            match (&d_columns, d_prev_layer) {
                (Some(cols), Some(prev)) => {
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                cols,
                                prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (Some(cols), None) => {
                    let dummy_prev = self
                        .device
                        .alloc::<u64>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                cols,
                                &dummy_prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (None, Some(prev)) => {
                    let dummy_cols = self
                        .device
                        .alloc::<u32>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                &dummy_cols,
                                prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                (None, None) => {
                    return Err(CudaFftError::InvalidSize(
                        "Poseidon252 Merkle requires columns or prev_layer".into(),
                    ));
                }
            }
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

        let mut output = vec![0u64; n_hashes * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::debug!(
            "GPU poseidon252_merkle_gpu_prev: {} hashes (prev on GPU)",
            n_hashes
        );
        Ok((output, d_output))
    }

    /// Execute Poseidon252 Merkle layer with BOTH columns and prev_layer on GPU.
    ///
    /// Fully GPU-resident path: no H2D at all. Returns both CPU and GPU output.
    pub fn execute_poseidon252_merkle_fully_resident(
        &self,
        d_columns: &CudaSlice<u32>,
        n_columns: usize,
        d_prev_layer: Option<&CudaSlice<u64>>,
        n_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<(Vec<u64>, CudaSlice<u64>), CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_merkle_fully_resident",
            n_hashes = n_hashes
        )
        .entered();

        let col_stride = n_hashes as u32;

        let mut d_output = unsafe { self.device.alloc::<u64>(n_hashes * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let block_size = 256u32;
        let grid_size = ((n_hashes as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        let has_prev: u32 = if d_prev_layer.is_some() { 1 } else { 0 };

        unsafe {
            match d_prev_layer {
                Some(prev) => {
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                d_columns,
                                prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                None => {
                    let dummy_prev = self
                        .device
                        .alloc::<u64>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .poseidon252_merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                d_columns,
                                &dummy_prev,
                                d_round_constants,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev,
                                col_stride,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

        let mut output = vec![0u64; n_hashes * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::debug!(
            "GPU poseidon252_merkle_fully_resident: {} hashes (fully GPU)",
            n_hashes
        );
        Ok((output, d_output))
    }

    // =========================================================================
    // Full Poseidon252 Merkle Tree (all layers, one GPU pass)
    // =========================================================================

    /// Build an entire Poseidon252 Merkle tree on GPU in one pass.
    ///
    /// Launches all layer kernels sequentially on the same CUDA stream (implicit
    /// ordering) with NO sync between layers. One final sync + bulk D2H.
    ///
    /// Returns `Vec<Vec<u64>>` where index 0 = leaf layer (n_hashes elements × 4 u64),
    /// index 1 = n_hashes/2, etc. down to the root layer (1 element × 4 u64).
    ///
    /// `d_columns` and `n_columns` describe the leaf data (column-major SoA on GPU).
    /// If `d_prev_leaf` is Some, it's incorporated into the leaf hash.
    pub fn execute_poseidon252_merkle_full_tree(
        &self,
        d_columns: &CudaSlice<u32>,
        n_columns: usize,
        d_prev_leaf: Option<&CudaSlice<u64>>,
        n_leaf_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<Vec<Vec<u64>>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_full_tree",
            n_leaf_hashes = n_leaf_hashes
        )
        .entered();

        if n_leaf_hashes == 0 {
            return Ok(vec![]);
        }

        let block_size = 256u32;

        // Count total layers
        let n_layers = (n_leaf_hashes as f64).log2() as usize + 1;

        // Allocate all output buffers upfront (no reallocation during kernel launches)
        let mut d_layers: Vec<CudaSlice<u64>> = Vec::with_capacity(n_layers);

        // Layer 0: leaf layer
        let mut current_n = n_leaf_hashes;
        for _ in 0..n_layers {
            let d_buf = unsafe { self.device.alloc::<u64>(current_n * 4) }
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
            d_layers.push(d_buf);
            current_n = (current_n + 1) / 2; // ceiling division for odd sizes
        }

        // Launch leaf layer kernel
        {
            let n = n_leaf_hashes;
            let grid_size = ((n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };
            let has_prev: u32 = if d_prev_leaf.is_some() { 1 } else { 0 };
            let col_stride = n as u32;

            unsafe {
                match d_prev_leaf {
                    Some(prev) => {
                        self.kernels
                            .poseidon252_merkle_layer
                            .clone()
                            .launch(
                                cfg,
                                (
                                    &mut d_layers[0],
                                    d_columns,
                                    prev,
                                    d_round_constants,
                                    n_columns as u32,
                                    n as u32,
                                    has_prev,
                                    col_stride,
                                ),
                            )
                            .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                    }
                    None => {
                        let dummy_prev = self
                            .device
                            .alloc::<u64>(1)
                            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                        self.kernels
                            .poseidon252_merkle_layer
                            .clone()
                            .launch(
                                cfg,
                                (
                                    &mut d_layers[0],
                                    d_columns,
                                    &dummy_prev,
                                    d_round_constants,
                                    n_columns as u32,
                                    n as u32,
                                    has_prev,
                                    col_stride,
                                ),
                            )
                            .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                    }
                }
            }
        }

        // Launch all subsequent layers (no columns, just hash pairs)
        let dummy_cols = unsafe { self.device.alloc::<u32>(1) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        current_n = n_leaf_hashes;
        for layer_idx in 1..n_layers {
            let next_n = current_n / 2;
            if next_n == 0 {
                break;
            }

            let grid_size = ((next_n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            // SAFETY: we read from d_layers[layer_idx-1] and write to d_layers[layer_idx].
            // These are distinct allocations. We need to split the borrow.
            let (prev_slice, rest) = d_layers.split_at_mut(layer_idx);
            let d_prev = &prev_slice[layer_idx - 1];
            let d_out = &mut rest[0];

            unsafe {
                self.kernels
                    .poseidon252_merkle_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            d_out,
                            &dummy_cols,
                            d_prev,
                            d_round_constants,
                            0u32,
                            next_n as u32,
                            1u32,
                            0u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }

            current_n = next_n;
        }

        // ONE sync for all layers
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

        // Bulk D2H: download all layers
        let mut results = Vec::with_capacity(n_layers);
        current_n = n_leaf_hashes;
        for layer_idx in 0..n_layers {
            let layer_size = current_n * 4;
            let mut cpu_data = vec![0u64; layer_size];
            self.device
                .dtoh_sync_copy_into(&d_layers[layer_idx].slice(0..layer_size), &mut cpu_data)
                .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
            results.push(cpu_data);
            current_n = current_n / 2;
            if current_n == 0 {
                break;
            }
        }

        tracing::info!(
            "GPU poseidon252_full_tree: {} layers, {} leaf hashes (1 sync, 1 bulk D2H)",
            results.len(),
            n_leaf_hashes
        );
        Ok(results)
    }

    /// Build an entire Poseidon252 Merkle tree on GPU and keep internal layers
    /// resident on device memory.
    ///
    /// Unlike `execute_poseidon252_merkle_full_tree`, this method does NOT bulk
    /// download layers. It returns a handle that can fetch only requested nodes
    /// (for Merkle authentication paths), avoiding large D2H transfers.
    pub fn execute_poseidon252_merkle_full_tree_gpu_layers(
        &self,
        d_columns: &CudaSlice<u32>,
        n_columns: usize,
        d_prev_leaf: Option<&CudaSlice<u64>>,
        n_leaf_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
    ) -> Result<Poseidon252MerkleGpuTree, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_full_tree_gpu_layers",
            n_leaf_hashes = n_leaf_hashes
        )
        .entered();

        if n_leaf_hashes == 0 {
            return Err(CudaFftError::InvalidSize(
                "n_leaf_hashes must be > 0".into(),
            ));
        }

        let block_size = 256u32;
        let n_layers = (n_leaf_hashes as f64).log2() as usize + 1;

        let mut d_layers: Vec<CudaSlice<u64>> = Vec::with_capacity(n_layers);
        let mut layer_hash_counts: Vec<usize> = Vec::with_capacity(n_layers);

        let mut current_n = n_leaf_hashes;
        for _ in 0..n_layers {
            let d_buf = unsafe { self.device.alloc::<u64>(current_n * 4) }
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
            d_layers.push(d_buf);
            layer_hash_counts.push(current_n);
            current_n = (current_n + 1) / 2;
        }

        {
            let n = n_leaf_hashes;
            let grid_size = ((n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };
            let has_prev: u32 = if d_prev_leaf.is_some() { 1 } else { 0 };
            let col_stride = n as u32;

            unsafe {
                match d_prev_leaf {
                    Some(prev) => {
                        self.kernels
                            .poseidon252_merkle_layer
                            .clone()
                            .launch(
                                cfg,
                                (
                                    &mut d_layers[0],
                                    d_columns,
                                    prev,
                                    d_round_constants,
                                    n_columns as u32,
                                    n as u32,
                                    has_prev,
                                    col_stride,
                                ),
                            )
                            .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                    }
                    None => {
                        let dummy_prev = self
                            .device
                            .alloc::<u64>(1)
                            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                        self.kernels
                            .poseidon252_merkle_layer
                            .clone()
                            .launch(
                                cfg,
                                (
                                    &mut d_layers[0],
                                    d_columns,
                                    &dummy_prev,
                                    d_round_constants,
                                    n_columns as u32,
                                    n as u32,
                                    has_prev,
                                    col_stride,
                                ),
                            )
                            .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                    }
                }
            }
        }

        let dummy_cols = unsafe { self.device.alloc::<u32>(1) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        current_n = n_leaf_hashes;
        for layer_idx in 1..n_layers {
            let next_n = current_n / 2;
            if next_n == 0 {
                break;
            }

            let grid_size = ((next_n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            let (prev_slice, rest) = d_layers.split_at_mut(layer_idx);
            let d_prev = &prev_slice[layer_idx - 1];
            let d_out = &mut rest[0];

            unsafe {
                self.kernels
                    .poseidon252_merkle_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            d_out,
                            &dummy_cols,
                            d_prev,
                            d_round_constants,
                            0u32,
                            next_n as u32,
                            1u32,
                            0u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }

            current_n = next_n;
        }

        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

        tracing::info!(
            "GPU poseidon252_full_tree_gpu_layers: {} layers, {} leaf hashes (GPU-resident)",
            d_layers.len(),
            n_leaf_hashes
        );

        Ok(Poseidon252MerkleGpuTree {
            device: Arc::clone(&self.device),
            layers: d_layers,
            layer_hash_counts,
        })
    }

    /// Build Poseidon252 Merkle tree level-by-level on GPU, keeping only 2 levels
    /// in VRAM at a time. Extracts only the sibling nodes needed for query
    /// authentication paths — avoids allocating the full tree.
    ///
    /// Peak VRAM: ~2× one tree level (vs full tree which stores all levels).
    /// For a 128M-leaf tree: ~12.8 GB peak vs ~20.5 GB for full tree.
    ///
    /// Returns `(root_limbs, per_query_auth_path_siblings)` where each auth path
    /// is a vector of sibling `[u64; 4]` limbs from leaf level to root.
    pub fn execute_poseidon252_merkle_streaming_auth_paths(
        &self,
        d_leaf_limbs: &CudaSlice<u64>,
        n_leaf_hashes: usize,
        d_round_constants: &CudaSlice<u64>,
        query_leaf_indices: &[usize],
    ) -> Result<([u64; 4], Vec<Vec<[u64; 4]>>), CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA poseidon252_streaming_auth_paths",
            n_leaf_hashes = n_leaf_hashes,
            n_queries = query_leaf_indices.len(),
        )
        .entered();

        if n_leaf_hashes == 0 {
            return Err(CudaFftError::InvalidSize(
                "n_leaf_hashes must be > 0".into(),
            ));
        }

        let n_queries = query_leaf_indices.len();
        let block_size = 256u32;
        let n_levels = (n_leaf_hashes as f64).log2().ceil() as usize + 1;

        // Per-query auth path storage: siblings[query][level]
        let mut auth_paths: Vec<Vec<[u64; 4]>> = vec![Vec::with_capacity(n_levels); n_queries];

        // Track node indices per query at the current level
        let mut query_node_indices: Vec<usize> = query_leaf_indices
            .iter()
            .map(|&leaf_idx| leaf_idx / 2)
            .collect();

        // Dummy column buffer for internal levels (no column data, only prev layer)
        let dummy_cols = unsafe { self.device.alloc::<u32>(1) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Level 0: hash leaf pairs from d_leaf_limbs
        let mut d_current = {
            let mut d_out = unsafe { self.device.alloc::<u64>(n_leaf_hashes * 4) }
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

            let grid_size = ((n_leaf_hashes as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                self.kernels
                    .poseidon252_merkle_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_out,
                            &dummy_cols,
                            d_leaf_limbs,
                            d_round_constants,
                            0u32,             // n_columns (0 = no column data)
                            n_leaf_hashes as u32,
                            1u32,             // has_prev = 1 (leaf limbs are the "prev" layer)
                            0u32,             // col_stride
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }
            self.device
                .synchronize()
                .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

            d_out
        };
        let mut current_n = n_leaf_hashes;

        // Extract level-0 sibling hashes for each query
        for q in 0..n_queries {
            let sib_idx = query_node_indices[q] ^ 1;
            if sib_idx < current_n {
                let start = sib_idx * 4;
                let end = start + 4;
                let mut out = [0u64; 4];
                self.device
                    .dtoh_sync_copy_into(&d_current.slice(start..end), &mut out)
                    .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
                auth_paths[q].push(out);
            } else {
                // Edge case: sibling out of bounds (odd tree), push zeroes
                auth_paths[q].push([0u64; 4]);
            }
        }

        // Upper levels: build from previous level, extract siblings, free old level
        for _level in 1..n_levels {
            let next_n = (current_n + 1) / 2;
            if next_n == 0 {
                break;
            }

            // Advance query node indices to parent level
            for idx in query_node_indices.iter_mut() {
                *idx >>= 1;
            }

            let mut d_next = unsafe { self.device.alloc::<u64>(next_n * 4) }
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

            let grid_size = ((next_n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            unsafe {
                self.kernels
                    .poseidon252_merkle_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_next,
                            &dummy_cols,
                            &d_current,
                            d_round_constants,
                            0u32,
                            next_n as u32,
                            1u32,
                            0u32,
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }
            self.device
                .synchronize()
                .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

            // Free the previous level before extracting (saves VRAM)
            drop(d_current);

            // Extract sibling hashes at this level
            if next_n > 1 {
                for q in 0..n_queries {
                    let sib_idx = query_node_indices[q] ^ 1;
                    if sib_idx < next_n {
                        let start = sib_idx * 4;
                        let end = start + 4;
                        let mut out = [0u64; 4];
                        self.device
                            .dtoh_sync_copy_into(&d_next.slice(start..end), &mut out)
                            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
                        auth_paths[q].push(out);
                    } else {
                        auth_paths[q].push([0u64; 4]);
                    }
                }
            }

            d_current = d_next;
            current_n = next_n;
        }

        // Download root
        let mut root = [0u64; 4];
        self.device
            .dtoh_sync_copy_into(&d_current.slice(0..4), &mut root)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU poseidon252_streaming_auth_paths: {} leaf hashes, {} queries, {} levels",
            n_leaf_hashes,
            n_queries,
            n_levels,
        );

        Ok((root, auth_paths))
    }

    // =========================================================================
    // GPU-Resident Column Operations (eliminate PCIe round-trips)
    // =========================================================================

    /// IFFT that takes CPU data and returns the GPU-resident result.
    ///
    /// Uploads data once, runs IFFT kernels, and returns the `CudaSlice`
    /// without downloading back to CPU. The caller is responsible for
    /// caching the returned slice via `cache_column_gpu`.
    pub fn execute_ifft_to_gpu(
        &self,
        data: &[u32],
        twiddles_dbl: &[Vec<u32>],
        log_size: u32,
    ) -> Result<CudaSlice<u32>, CudaFftError> {
        let n = 1usize << log_size;
        if data.len() != n {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} elements, got {}",
                n,
                data.len()
            )));
        }

        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA IFFT→GPU", log_size = log_size).entered();

        // H2D: data + twiddles
        let mut d_data = self
            .device
            .htod_sync_copy(data)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let flat_twiddles: Vec<u32> = twiddles_dbl.iter().flatten().copied().collect();
        let d_twiddles = self
            .device
            .htod_sync_copy(&flat_twiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Run IFFT layers (all on GPU)
        self.execute_ifft_layers(&mut d_data, &d_twiddles, log_size, twiddles_dbl)?;

        // NO dtoh — return GPU-resident result
        tracing::debug!("IFFT→GPU: {} elements kept on device", n);
        Ok(d_data)
    }

    /// FFT that operates on a GPU-resident input in-place.
    ///
    /// Uploads only twiddle factors (small), runs FFT layers on the
    /// already-resident data, and leaves the result on GPU.
    pub fn execute_fft_on_gpu(
        &self,
        d_data: &mut CudaSlice<u32>,
        twiddles: &[Vec<u32>],
        log_size: u32,
    ) -> Result<(), CudaFftError> {
        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA FFT on GPU", log_size = log_size).entered();

        // H2D: twiddles only
        let flat_twiddles: Vec<u32> = twiddles.iter().flatten().copied().collect();
        let d_twiddles = self
            .device
            .htod_sync_copy(&flat_twiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Run FFT layers in-place
        self.execute_fft_layers(d_data, &d_twiddles, log_size, twiddles)?;

        // NO dtoh — result stays on GPU
        tracing::debug!(
            "FFT on GPU: {} elements, no PCIe round-trip",
            1u64 << log_size
        );
        Ok(())
    }

    /// Batch IFFT: upload twiddles once, process multiple columns, return GPU-resident results.
    ///
    /// Returns (cpu_results, gpu_slices) — CPU data for polynomial representation,
    /// GPU slices for caching (evaluate can reuse them).
    pub fn execute_batch_ifft_to_gpu(
        &self,
        columns: &[Vec<u32>],
        twiddles_dbl: &[Vec<u32>],
        log_size: u32,
        denorm_val: u32,
    ) -> Result<(Vec<Vec<u32>>, Vec<CudaSlice<u32>>), CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA batch_IFFT→GPU",
            num_cols = columns.len(),
            log_size = log_size
        )
        .entered();

        // Upload twiddles ONCE (shared across all columns)
        let flat_twiddles: Vec<u32> = twiddles_dbl.iter().flatten().copied().collect();
        let d_twiddles = self
            .device
            .htod_sync_copy(&flat_twiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut cpu_results = Vec::with_capacity(columns.len());
        let mut gpu_slices = Vec::with_capacity(columns.len());

        for col_data in columns {
            // Upload column
            let mut d_data = self
                .device
                .htod_sync_copy(col_data)
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

            // IFFT in-place
            self.execute_ifft_layers(&mut d_data, &d_twiddles, log_size, twiddles_dbl)?;

            // Denormalize on GPU
            self.execute_denormalize_on_device(&mut d_data, denorm_val, 1u32 << log_size)?;
            self.device
                .synchronize()
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;

            // Download to CPU
            let cpu_data = self
                .device
                .dtoh_sync_copy(&d_data)
                .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

            cpu_results.push(cpu_data);
            gpu_slices.push(d_data);
        }

        tracing::info!(
            "Batch IFFT: {} columns × {} elements, twiddles uploaded once",
            columns.len(),
            1u64 << log_size
        );
        Ok((cpu_results, gpu_slices))
    }

    /// Batch FFT: upload twiddles once, process multiple GPU-resident columns.
    ///
    /// Columns must already be on GPU. Returns CPU results + keeps GPU slices for Merkle.
    pub fn execute_batch_fft_on_gpu(
        &self,
        d_columns: &mut [CudaSlice<u32>],
        twiddles: &[Vec<u32>],
        log_size: u32,
    ) -> Result<Vec<Vec<u32>>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA batch_FFT on GPU",
            num_cols = d_columns.len(),
            log_size = log_size
        )
        .entered();

        // Upload twiddles ONCE
        let flat_twiddles: Vec<u32> = twiddles.iter().flatten().copied().collect();
        let d_twiddles = self
            .device
            .htod_sync_copy(&flat_twiddles)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut cpu_results = Vec::with_capacity(d_columns.len());

        for d_data in d_columns.iter_mut() {
            // FFT in-place
            self.execute_fft_layers(d_data, &d_twiddles, log_size, twiddles)?;

            // Download to CPU
            let cpu_data = self
                .device
                .dtoh_sync_copy(d_data)
                .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
            cpu_results.push(cpu_data);
        }

        tracing::info!(
            "Batch FFT: {} columns × {} elements, twiddles uploaded once",
            cpu_results.len(),
            1u64 << log_size
        );
        Ok(cpu_results)
    }

    /// Merkle hashing that takes GPU-resident column data.
    ///
    /// Columns are already on GPU so no H2D is needed for column data.
    /// Only the previous layer hashes (small) are uploaded if present.
    /// Returns hashes to CPU (32 bytes × n_hashes — tiny).
    pub fn execute_blake2s_merkle_from_gpu(
        &self,
        d_columns: &[&CudaSlice<u32>],
        col_lengths: &[usize],
        prev_layer: Option<&[u8]>,
        n_hashes: usize,
    ) -> Result<Vec<u8>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA merkle_from_gpu",
            n_hashes = n_hashes
        )
        .entered();

        let n_columns = d_columns.len();

        // Flatten GPU columns into a single contiguous buffer
        // We need to gather them since the kernel expects contiguous column data
        let total_elements: usize = col_lengths.iter().sum();
        let mut d_flat_columns = unsafe { self.device.alloc::<u32>(total_elements) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Copy each GPU column into the flat buffer using device-to-device copy
        let mut offset = 0usize;
        for (i, d_col) in d_columns.iter().enumerate() {
            let len = col_lengths[i];
            let block_size = 256u32;
            let grid_size = ((len as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };
            unsafe {
                self.kernels
                    .copy_column
                    .clone()
                    .launch(
                        cfg,
                        (&mut d_flat_columns, *d_col, offset as u32, len as u32),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("copy_column: {:?}", e)))?;
            }
            offset += len;
        }

        // Upload previous layer (small) if present
        let d_prev_layer = if let Some(prev) = prev_layer {
            Some(
                self.device
                    .htod_sync_copy(prev)
                    .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?,
            )
        } else {
            None
        };

        // Allocate output
        let mut d_output = unsafe { self.device.alloc::<u8>(n_hashes * 32) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n_hashes as u32) + block_size - 1) / block_size;
        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        let has_prev_layer = if prev_layer.is_some() { 1u32 } else { 0u32 };

        unsafe {
            match &d_prev_layer {
                Some(prev) => {
                    self.kernels
                        .merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                &d_flat_columns,
                                prev,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev_layer,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
                None => {
                    let dummy_prev = self
                        .device
                        .alloc::<u8>(1)
                        .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
                    self.kernels
                        .merkle_layer
                        .clone()
                        .launch(
                            cfg,
                            (
                                &mut d_output,
                                &d_flat_columns,
                                &dummy_prev,
                                n_columns as u32,
                                n_hashes as u32,
                                has_prev_layer,
                            ),
                        )
                        .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
                }
            }
        }

        // Sync + D2H (tiny: 32 bytes × n_hashes)
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u8; n_hashes * 32];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!("GPU merkle_from_gpu: {} hashes (0 column H2D)", n_hashes);
        Ok(output)
    }

    /// Build an entire Blake2s Merkle tree in one GPU pass (no per-layer sync/D2H).
    ///
    /// Mirrors `execute_poseidon252_merkle_full_tree` but for Blake2s:
    /// 1. Leaf layer: hash columns using existing Blake2s kernel
    /// 2. All subsequent layers: hash pairs from previous layer (no columns)
    /// 3. All kernels on same CUDA stream (implicit ordering, no sync between layers)
    /// 4. ONE sync + bulk D2H at end
    /// 5. Returns `Vec<Vec<u8>>` (each layer is n_hashes × 32 bytes)
    pub fn execute_blake2s_merkle_full_tree(
        &self,
        d_columns: &[&CudaSlice<u32>],
        col_lengths: &[usize],
        n_leaf_hashes: usize,
    ) -> Result<Vec<Vec<u8>>, CudaFftError> {
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA blake2s_full_tree",
            n_leaf_hashes = n_leaf_hashes
        )
        .entered();

        if n_leaf_hashes == 0 {
            return Ok(vec![]);
        }

        let n_columns = d_columns.len();
        let block_size = 256u32;

        // Count total layers
        let n_layers = (n_leaf_hashes as f64).log2() as usize + 1;

        // Flatten GPU columns into a single contiguous buffer
        let total_elements: usize = col_lengths.iter().sum();
        let mut d_flat_columns = unsafe { self.device.alloc::<u32>(total_elements) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut offset = 0usize;
        for (i, d_col) in d_columns.iter().enumerate() {
            let len = col_lengths[i];
            let grid_size = ((len as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };
            unsafe {
                self.kernels
                    .copy_column
                    .clone()
                    .launch(
                        cfg,
                        (&mut d_flat_columns, *d_col, offset as u32, len as u32),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("copy_column: {:?}", e)))?;
            }
            offset += len;
        }

        // Allocate all output buffers upfront
        let mut d_layers: Vec<CudaSlice<u8>> = Vec::with_capacity(n_layers);
        let mut current_n = n_leaf_hashes;
        for _ in 0..n_layers {
            let d_buf = unsafe { self.device.alloc::<u8>(current_n * 32) }
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
            d_layers.push(d_buf);
            current_n = (current_n + 1) / 2;
        }

        // Launch leaf layer kernel (columns present, no prev_layer)
        {
            let n = n_leaf_hashes;
            let grid_size = ((n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };
            let dummy_prev = unsafe { self.device.alloc::<u8>(1) }
                .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;
            unsafe {
                self.kernels
                    .merkle_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            &mut d_layers[0],
                            &d_flat_columns,
                            &dummy_prev,
                            n_columns as u32,
                            n as u32,
                            0u32, // has_prev_layer = false
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }
        }

        // Launch all subsequent layers (no columns, hash pairs from previous layer)
        let dummy_cols = unsafe { self.device.alloc::<u32>(1) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        current_n = n_leaf_hashes;
        for layer_idx in 1..n_layers {
            let next_n = current_n / 2;
            if next_n == 0 {
                break;
            }

            let grid_size = ((next_n as u32) + block_size - 1) / block_size;
            let cfg = LaunchConfig {
                grid_dim: (grid_size, 1, 1),
                block_dim: (block_size, 1, 1),
                shared_mem_bytes: 0,
            };

            // Split borrow: read from d_layers[layer_idx-1], write to d_layers[layer_idx]
            let (prev_slice, rest) = d_layers.split_at_mut(layer_idx);
            let d_prev = &prev_slice[layer_idx - 1];
            let d_out = &mut rest[0];

            unsafe {
                self.kernels
                    .merkle_layer
                    .clone()
                    .launch(
                        cfg,
                        (
                            d_out,
                            &dummy_cols,
                            d_prev,
                            0u32, // n_columns = 0
                            next_n as u32,
                            1u32, // has_prev_layer = true
                        ),
                    )
                    .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
            }

            current_n = next_n;
        }

        // ONE sync for all layers
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync: {:?}", e)))?;

        // Bulk D2H: download all layers
        let mut results = Vec::with_capacity(n_layers);
        current_n = n_leaf_hashes;
        for layer_idx in 0..n_layers {
            let layer_size = current_n * 32;
            let mut cpu_data = vec![0u8; layer_size];
            self.device
                .dtoh_sync_copy_into(&d_layers[layer_idx].slice(0..layer_size), &mut cpu_data)
                .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;
            results.push(cpu_data);
            current_n = current_n / 2;
            if current_n == 0 {
                break;
            }
        }

        tracing::info!(
            "GPU blake2s_full_tree: {} layers, {} leaf hashes (1 sync, 1 bulk D2H)",
            results.len(),
            n_leaf_hashes
        );
        Ok(results)
    }

    // =========================================================================
    // MLE (GKR) Operations
    // =========================================================================

    /// Execute MLE fold operation: BaseField -> SecureField
    ///
    /// Computes: result[i] = lhs[i] * (1 - assignment) + rhs[i] * assignment
    ///
    /// # Arguments
    /// * `lhs` - Left half values (M31, single u32 per element)
    /// * `rhs` - Right half values (M31, single u32 per element)
    /// * `assignment` - QM31 assignment value (4 u32)
    /// * `n` - Number of output elements
    pub fn mle_fold_base_to_secure(
        &self,
        lhs: &[u32],
        rhs: &[u32],
        assignment: &[u32; 4],
        n: usize,
    ) -> Result<Vec<u32>, CudaFftError> {
        let _span =
            tracing::span!(tracing::Level::INFO, "CUDA mle_fold_base_to_secure", n = n).entered();

        if lhs.len() != n || rhs.len() != n {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} elements for lhs and rhs, got {} and {}",
                n,
                lhs.len(),
                rhs.len()
            )));
        }

        // Allocate device memory
        let d_lhs = self
            .device
            .htod_sync_copy(lhs)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_rhs = self
            .device
            .htod_sync_copy(rhs)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .mle_fold_base_to_secure
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        &d_lhs,
                        &d_rhs,
                        assignment[0],
                        assignment[1],
                        assignment[2],
                        assignment[3],
                        n as u32,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u32; n * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!("GPU mle_fold_base_to_secure completed: {} elements", n);

        Ok(output)
    }

    /// Execute MLE fold operation: SecureField -> SecureField
    ///
    /// Computes: result[i] = lhs[i] * (1 - assignment) + rhs[i] * assignment
    ///
    /// # Arguments
    /// * `lhs` - Left half values (QM31, 4 u32 per element)
    /// * `rhs` - Right half values (QM31, 4 u32 per element)
    /// * `assignment` - QM31 assignment value (4 u32)
    /// * `n` - Number of output elements
    pub fn mle_fold_secure(
        &self,
        lhs: &[u32],
        rhs: &[u32],
        assignment: &[u32; 4],
        n: usize,
    ) -> Result<Vec<u32>, CudaFftError> {
        let _span = tracing::span!(tracing::Level::INFO, "CUDA mle_fold_secure", n = n).entered();

        if lhs.len() != n * 4 || rhs.len() != n * 4 {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} u32 values for lhs and rhs, got {} and {}",
                n * 4,
                lhs.len(),
                rhs.len()
            )));
        }

        // Allocate device memory
        let d_lhs = self
            .device
            .htod_sync_copy(lhs)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let d_rhs = self
            .device
            .htod_sync_copy(rhs)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(n * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((n as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .mle_fold_secure
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        &d_lhs,
                        &d_rhs,
                        assignment[0],
                        assignment[1],
                        assignment[2],
                        assignment[3],
                        n as u32,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u32; n * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!("GPU mle_fold_secure completed: {} elements", n);

        Ok(output)
    }

    /// Execute gen_eq_evals for GKR.
    ///
    /// Computes: eq_evals[i] = v * prod_j((1 - y[j]) + y[j] * bit_j(i))
    ///
    /// # Arguments
    /// * `y` - QM31 y values (4 u32 per element, n_variables elements)
    /// * `v` - Initial QM31 value (4 u32)
    /// * `n_variables` - Number of variables
    pub fn gen_eq_evals(
        &self,
        y: &[u32],
        v: &[u32; 4],
        n_variables: usize,
    ) -> Result<Vec<u32>, CudaFftError> {
        let output_size = 1usize << n_variables;
        let _span = tracing::span!(
            tracing::Level::INFO,
            "CUDA gen_eq_evals",
            n_variables = n_variables,
            output_size = output_size
        )
        .entered();

        if y.len() != n_variables * 4 {
            return Err(CudaFftError::InvalidSize(format!(
                "Expected {} u32 values for y, got {}",
                n_variables * 4,
                y.len()
            )));
        }

        // Allocate device memory
        let d_y = self
            .device
            .htod_sync_copy(y)
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        let mut d_output = unsafe { self.device.alloc::<u32>(output_size * 4) }
            .map_err(|e| CudaFftError::MemoryAllocation(format!("{:?}", e)))?;

        // Launch kernel
        let block_size = 256u32;
        let grid_size = ((output_size as u32) + block_size - 1) / block_size;

        let cfg = LaunchConfig {
            grid_dim: (grid_size, 1, 1),
            block_dim: (block_size, 1, 1),
            shared_mem_bytes: 0,
        };

        unsafe {
            self.kernels
                .gen_eq_evals
                .clone()
                .launch(
                    cfg,
                    (
                        &mut d_output,
                        &d_y,
                        v[0],
                        v[1],
                        v[2],
                        v[3],
                        n_variables as u32,
                        output_size as u32,
                    ),
                )
                .map_err(|e| CudaFftError::KernelExecution(format!("{:?}", e)))?;
        }

        // Synchronize and copy back
        self.device
            .synchronize()
            .map_err(|e| CudaFftError::KernelExecution(format!("Sync failed: {:?}", e)))?;

        let mut output = vec![0u32; output_size * 4];
        self.device
            .dtoh_sync_copy_into(&d_output, &mut output)
            .map_err(|e| CudaFftError::MemoryTransfer(format!("{:?}", e)))?;

        tracing::info!(
            "GPU gen_eq_evals completed: {} output elements",
            output_size
        );

        Ok(output)
    }
}

// =============================================================================
// High-Level FFT Interface
// =============================================================================

/// Execute IFFT using CUDA if available, otherwise return error.
#[cfg(feature = "cuda-runtime")]
pub fn cuda_ifft(
    data: &mut [u32],
    twiddles_dbl: &[Vec<u32>],
    log_size: u32,
) -> Result<(), CudaFftError> {
    let executor = get_cuda_executor().map_err(|e| e.clone())?;
    executor.execute_ifft(data, twiddles_dbl, log_size)
}

/// Execute FFT using CUDA if available, otherwise return error.
#[cfg(feature = "cuda-runtime")]
pub fn cuda_fft(
    data: &mut [u32],
    twiddles: &[Vec<u32>],
    log_size: u32,
) -> Result<(), CudaFftError> {
    let executor = get_cuda_executor().map_err(|e| e.clone())?;
    executor.execute_fft(data, twiddles, log_size)
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn cuda_ifft(
    _data: &mut [u32],
    _twiddles_dbl: &[Vec<u32>],
    _log_size: u32,
) -> Result<(), CudaFftError> {
    Err(CudaFftError::NoDevice)
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn cuda_fft(
    _data: &mut [u32],
    _twiddles: &[Vec<u32>],
    _log_size: u32,
) -> Result<(), CudaFftError> {
    Err(CudaFftError::NoDevice)
}

// =============================================================================
// High-Level FRI Folding Interface
// =============================================================================

/// Execute FRI fold_line using CUDA.
///
/// # Arguments
/// * `input` - Input SecureField values as flat u32 array (4 u32 per element)
/// * `itwiddles` - Inverse twiddle factors
/// * `alpha` - Folding random challenge (4 u32 for QM31)
/// * `n` - Number of input elements
///
/// # Returns
/// Output SecureField values (n/2 elements, 4 u32 each)
#[cfg(feature = "cuda-runtime")]
pub fn cuda_fold_line(
    input: &[u32],
    itwiddles: &[u32],
    alpha: &[u32; 4],
    n: usize,
) -> Result<Vec<u32>, CudaFftError> {
    let executor = get_cuda_executor().map_err(|e| e.clone())?;
    executor.execute_fold_line(input, itwiddles, alpha, n)
}

/// Execute FRI fold_circle_into_line using CUDA.
///
/// # Arguments
/// * `dst` - Destination line evaluation (modified in place)
/// * `src` - Source circle evaluation
/// * `itwiddles` - Inverse twiddle factors (y-coordinates)
/// * `alpha` - Folding random challenge (4 u32 for QM31)
/// * `n` - Number of source elements
#[cfg(feature = "cuda-runtime")]
pub fn cuda_fold_circle_into_line(
    dst: &mut [u32],
    src: &[u32],
    itwiddles: &[u32],
    alpha: &[u32; 4],
    n: usize,
) -> Result<(), CudaFftError> {
    let executor = get_cuda_executor().map_err(|e| e.clone())?;
    executor.execute_fold_circle_into_line(dst, src, itwiddles, alpha, n)
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn cuda_fold_line(
    _input: &[u32],
    _itwiddles: &[u32],
    _alpha: &[u32; 4],
    _n: usize,
) -> Result<Vec<u32>, CudaFftError> {
    Err(CudaFftError::NoDevice)
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn cuda_fold_circle_into_line(
    _dst: &mut [u32],
    _src: &[u32],
    _itwiddles: &[u32],
    _alpha: &[u32; 4],
    _n: usize,
) -> Result<(), CudaFftError> {
    Err(CudaFftError::NoDevice)
}

// =============================================================================
// High-Level Quotient Accumulation Interface
// =============================================================================

/// Execute quotient accumulation using CUDA.
///
/// # Arguments
/// * `columns` - Column data (each column is a Vec<u32> of M31 values)
/// * `line_coeffs` - Line coefficients (a, b, c as QM31, 12 u32 each)
/// * `denom_inv` - Denominator inverses (CM31, 2 u32 each)
/// * `batch_sizes` - Number of columns per sample batch
/// * `col_indices` - Column indices for each coefficient
/// * `n_points` - Number of domain points
///
/// # Returns
/// Output QM31 values (4 u32 per element)
#[cfg(feature = "cuda-runtime")]
pub fn cuda_accumulate_quotients(
    columns: &[Vec<u32>],
    line_coeffs: &[[u32; 12]],
    denom_inv: &[u32],
    batch_sizes: &[usize],
    col_indices: &[usize],
    n_points: usize,
) -> Result<Vec<u32>, CudaFftError> {
    let executor = get_cuda_executor().map_err(|e| e.clone())?;
    executor.execute_accumulate_quotients(
        columns,
        line_coeffs,
        denom_inv,
        batch_sizes,
        col_indices,
        n_points,
    )
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn cuda_accumulate_quotients(
    _columns: &[Vec<u32>],
    _line_coeffs: &[[u32; 12]],
    _denom_inv: &[u32],
    _batch_sizes: &[usize],
    _col_indices: &[usize],
    _n_points: usize,
) -> Result<Vec<u32>, CudaFftError> {
    Err(CudaFftError::NoDevice)
}

// =============================================================================
// High-Level Merkle Hashing Interface
// =============================================================================

/// Execute Blake2s Merkle hashing using CUDA.
///
/// # Arguments
/// * `columns` - Column data (each column is a Vec<u32> of M31 values)
/// * `prev_layer` - Previous layer hashes (64 bytes per pair, or None for leaves)
/// * `n_hashes` - Number of hashes to compute
///
/// # Returns
/// Output hashes (32 bytes each)
#[cfg(feature = "cuda-runtime")]
pub fn cuda_blake2s_merkle(
    columns: &[Vec<u32>],
    prev_layer: Option<&[u8]>,
    n_hashes: usize,
) -> Result<Vec<u8>, CudaFftError> {
    let executor = get_cuda_executor().map_err(|e| e.clone())?;
    executor.execute_blake2s_merkle(columns, prev_layer, n_hashes)
}

#[cfg(not(feature = "cuda-runtime"))]
pub fn cuda_blake2s_merkle(
    _columns: &[Vec<u32>],
    _prev_layer: Option<&[u8]>,
    _n_hashes: usize,
) -> Result<Vec<u8>, CudaFftError> {
    Err(CudaFftError::NoDevice)
}

// =============================================================================
// Poseidon252 Round Constants
// =============================================================================

/// Compute the 107 compressed Poseidon252 round constants as u64 limbs.
///
/// This replicates the round key compression from starknet-crypto-codegen.
/// The result is 107 × 4 = 428 u64 values (big-endian limb order matching
/// starknet_ff::FieldElement::to_bytes_be layout).
///
/// Layout: [rc0_limb3, rc0_limb2, rc0_limb1, rc0_limb0, rc1_limb3, ...]
/// where limb3 is the most significant (matching how felt252 is stored in the CUDA kernel).
#[cfg(feature = "cuda-runtime")]
pub fn compute_poseidon252_round_constants() -> Vec<u64> {
    use starknet_ff::FieldElement;

    const FULL_ROUNDS: usize = 8;
    const PARTIAL_ROUNDS: usize = 83;

    // Raw round keys (91 rounds × 3 FieldElements)
    let raw_keys = poseidon252_raw_round_keys();

    // Compress round keys (same algorithm as starknet-crypto-codegen)
    let mut comp = Vec::with_capacity(107);

    // First half full rounds (4 rounds × 3 constants = 12)
    for round in &raw_keys[..FULL_ROUNDS / 2] {
        comp.extend_from_slice(round);
    }

    // Compressed partial rounds + first of last full rounds
    {
        let mut state = [FieldElement::ZERO; 3];
        let mut idx = FULL_ROUNDS / 2;

        for _ in 0..PARTIAL_ROUNDS {
            state[0] += raw_keys[idx][0];
            state[1] += raw_keys[idx][1];
            state[2] += raw_keys[idx][2];

            comp.push(state[2]);
            state[2] = FieldElement::ZERO;

            // MixLayer
            let t = state[0] + state[1] + state[2];
            state[0] = t + state[0].double();
            state[1] = t - state[1].double();
            state[2] = t - FieldElement::THREE * state[2];

            idx += 1;
        }

        // First of the last full rounds
        state[0] += raw_keys[idx][0];
        state[1] += raw_keys[idx][1];
        state[2] += raw_keys[idx][2];
        comp.push(state[0]);
        comp.push(state[1]);
        comp.push(state[2]);
    }

    // Last full rounds except the first (3 rounds × 3 = 9)
    for round in &raw_keys[(FULL_ROUNDS / 2 + PARTIAL_ROUNDS + 1)..] {
        comp.extend_from_slice(round);
    }

    assert_eq!(comp.len(), 107, "Expected 107 compressed round constants");

    // Convert to u64 limbs (4 per felt252)
    // starknet_ff stores internally as Montgomery form, but to_bytes_be gives canonical big-endian
    let mut limbs = Vec::with_capacity(107 * 4);
    for fe in &comp {
        let bytes = fe.to_bytes_be();
        // Convert 32 bytes to 4 u64s (big-endian: limb[3] is most significant)
        // CUDA kernel uses: limb[0] = least significant, limb[3] = most significant
        for i in 0..4 {
            let offset = 24 - i * 8; // byte offsets: 24, 16, 8, 0
            let mut val = 0u64;
            for j in 0..8 {
                val = (val << 8) | bytes[offset + j] as u64;
            }
            limbs.push(val);
        }
    }

    limbs
}

/// Upload Poseidon252 round constants to GPU device memory.
/// Returns a CudaSlice that should be cached and reused across kernel calls.
#[cfg(feature = "cuda-runtime")]
pub fn upload_poseidon252_round_constants(
    device: &std::sync::Arc<cudarc::driver::CudaDevice>,
) -> Result<CudaSlice<u64>, CudaFftError> {
    let limbs = compute_poseidon252_round_constants();
    device
        .htod_sync_copy(&limbs)
        .map_err(|e| CudaFftError::MemoryAllocation(format!("RC upload: {:?}", e)))
}

/// The 91 raw Poseidon252 round keys (decimal strings → FieldElement).
#[cfg(feature = "cuda-runtime")]
fn poseidon252_raw_round_keys() -> Vec<[starknet_ff::FieldElement; 3]> {
    use starknet_ff::FieldElement;

    // Extracted from starknet-crypto-codegen params.rs (poseidon3.txt)
    let raw: [[&str; 3]; 91] = [
        [
            "2950795762459345168613727575620414179244544320470208355568817838579231751791",
            "1587446564224215276866294500450702039420286416111469274423465069420553242820",
            "1645965921169490687904413452218868659025437693527479459426157555728339600137",
        ],
        [
            "2782373324549879794752287702905278018819686065818504085638398966973694145741",
            "3409172630025222641379726933524480516420204828329395644967085131392375707302",
            "2379053116496905638239090788901387719228422033660130943198035907032739387135",
        ],
        [
            "2570819397480941104144008784293466051718826502582588529995520356691856497111",
            "3546220846133880637977653625763703334841539452343273304410918449202580719746",
            "2720682389492889709700489490056111332164748138023159726590726667539759963454",
        ],
        [
            "1899653471897224903834726250400246354200311275092866725547887381599836519005",
            "2369443697923857319844855392163763375394720104106200469525915896159690979559",
            "2354174693689535854311272135513626412848402744119855553970180659094265527996",
        ],
        [
            "2404084503073127963385083467393598147276436640877011103379112521338973185443",
            "950320777137731763811524327595514151340412860090489448295239456547370725376",
            "2121140748740143694053732746913428481442990369183417228688865837805149503386",
        ],
        [
            "2372065044800422557577242066480215868569521938346032514014152523102053709709",
            "2618497439310693947058545060953893433487994458443568169824149550389484489896",
            "3518297267402065742048564133910509847197496119850246255805075095266319996916",
        ],
        [
            "340529752683340505065238931581518232901634742162506851191464448040657139775",
            "1954876811294863748406056845662382214841467408616109501720437541211031966538",
            "813813157354633930267029888722341725864333883175521358739311868164460385261",
        ],
        [
            "71901595776070443337150458310956362034911936706490730914901986556638720031",
            "2789761472166115462625363403490399263810962093264318361008954888847594113421",
            "2628791615374802560074754031104384456692791616314774034906110098358135152410",
        ],
        [
            "3617032588734559635167557152518265808024917503198278888820567553943986939719",
            "2624012360209966117322788103333497793082705816015202046036057821340914061980",
            "149101987103211771991327927827692640556911620408176100290586418839323044234",
        ],
        [
            "1039927963829140138166373450440320262590862908847727961488297105916489431045",
            "2213946951050724449162431068646025833746639391992751674082854766704900195669",
            "2792724903541814965769131737117981991997031078369482697195201969174353468597",
        ],
        [
            "3212031629728871219804596347439383805499808476303618848198208101593976279441",
            "3343514080098703935339621028041191631325798327656683100151836206557453199613",
            "614054702436541219556958850933730254992710988573177298270089989048553060199",
        ],
        [
            "148148081026449726283933484730968827750202042869875329032965774667206931170",
            "1158283532103191908366672518396366136968613180867652172211392033571980848414",
            "1032400527342371389481069504520755916075559110755235773196747439146396688513",
        ],
        [
            "806900704622005851310078578853499250941978435851598088619290797134710613736",
            "462498083559902778091095573017508352472262817904991134671058825705968404510",
            "1003580119810278869589347418043095667699674425582646347949349245557449452503",
        ],
        [
            "619074932220101074089137133998298830285661916867732916607601635248249357793",
            "2635090520059500019661864086615522409798872905401305311748231832709078452746",
            "978252636251682252755279071140187792306115352460774007308726210405257135181",
        ],
        [
            "1766912167973123409669091967764158892111310474906691336473559256218048677083",
            "1663265127259512472182980890707014969235283233442916350121860684522654120381",
            "3532407621206959585000336211742670185380751515636605428496206887841428074250",
        ],
        [
            "2507023127157093845256722098502856938353143387711652912931112668310034975446",
            "3321152907858462102434883844787153373036767230808678981306827073335525034593",
            "3039253036806065280643845548147711477270022154459620569428286684179698125661",
        ],
        [
            "103480338868480851881924519768416587261556021758163719199282794248762465380",
            "2394049781357087698434751577708655768465803975478348134669006211289636928495",
            "2660531560345476340796109810821127229446538730404600368347902087220064379579",
        ],
        [
            "3603166934034556203649050570865466556260359798872408576857928196141785055563",
            "1553799760191949768532188139643704561532896296986025007089826672890485412324",
            "2744284717053657689091306578463476341218866418732695211367062598446038965164",
        ],
        [
            "320745764922149897598257794663594419839885234101078803811049904310835548856",
            "979382242100682161589753881721708883681034024104145498709287731138044566302",
            "1860426855810549882740147175136418997351054138609396651615467358416651354991",
        ],
        [
            "336173081054369235994909356892506146234495707857220254489443629387613956145",
            "1632470326779699229772327605759783482411227247311431865655466227711078175883",
            "921958250077481394074960433988881176409497663777043304881055317463712938502",
        ],
        [
            "3034358982193370602048539901033542101022185309652879937418114324899281842797",
            "25626282149517463867572353922222474817434101087272320606729439087234878607",
            "3002662261401575565838149305485737102400501329139562227180277188790091853682",
        ],
        [
            "2939684373453383817196521641512509179310654199629514917426341354023324109367",
            "1076484609897998179434851570277297233169621096172424141759873688902355505136",
            "2575095284833160494841112025725243274091830284746697961080467506739203605049",
        ],
        [
            "3565075264617591783581665711620369529657840830498005563542124551465195621851",
            "2197016502533303822395077038351174326125210255869204501838837289716363437993",
            "331415322883530754594261416546036195982886300052707474899691116664327869405",
        ],
        [
            "1935011233711290003793244296594669823169522055520303479680359990463281661839",
            "3495901467168087413996941216661589517270845976538454329511167073314577412322",
            "954195417117133246453562983448451025087661597543338750600301835944144520375",
        ],
        [
            "1271840477709992894995746871435810599280944810893784031132923384456797925777",
            "2565310762274337662754531859505158700827688964841878141121196528015826671847",
            "3365022288251637014588279139038152521653896670895105540140002607272936852513",
        ],
        [
            "1660592021628965529963974299647026602622092163312666588591285654477111176051",
            "970104372286014048279296575474974982288801187216974504035759997141059513421",
            "2617024574317953753849168721871770134225690844968986289121504184985993971227",
        ],
        [
            "999899815343607746071464113462778273556695659506865124478430189024755832262",
            "2228536129413411161615629030408828764980855956560026807518714080003644769896",
            "2701953891198001564547196795777701119629537795442025393867364730330476403227",
        ],
        [
            "837078355588159388741598313782044128527494922918203556465116291436461597853",
            "2121749601840466143704862369657561429793951309962582099604848281796392359214",
            "771812260179247428733132708063116523892339056677915387749121983038690154755",
        ],
        [
            "3317336423132806446086732225036532603224267214833263122557471741829060578219",
            "481570067997721834712647566896657604857788523050900222145547508314620762046",
            "242195042559343964206291740270858862066153636168162642380846129622127460192",
        ],
        [
            "2855462178889999218204481481614105202770810647859867354506557827319138379686",
            "3525521107148375040131784770413887305850308357895464453970651672160034885202",
            "1320839531502392535964065058804908871811967681250362364246430459003920305799",
        ],
        [
            "2514191518588387125173345107242226637171897291221681115249521904869763202419",
            "2798335750958827619666318316247381695117827718387653874070218127140615157902",
            "2808467767967035643407948058486565877867906577474361783201337540214875566395",
        ],
        [
            "3551834385992706206273955480294669176699286104229279436819137165202231595747",
            "1219439673853113792340300173186247996249367102884530407862469123523013083971",
            "761519904537984520554247997444508040636526566551719396202550009393012691157",
        ],
        [
            "3355402549169351700500518865338783382387571349497391475317206324155237401353",
            "199541098009731541347317515995192175813554789571447733944970283654592727138",
            "192100490643078165121235261796864975568292640203635147901612231594408079071",
        ],
        [
            "1187019357602953326192019968809486933768550466167033084944727938441427050581",
            "189525349641911362389041124808934468936759383310282010671081989585219065700",
            "2831653363992091308880573627558515686245403755586311978724025292003353336665",
        ],
        [
            "2052859812632218952608271535089179639890275494426396974475479657192657094698",
            "1670756178709659908159049531058853320846231785448204274277900022176591811072",
            "3538757242013734574731807289786598937548399719866320954894004830207085723125",
        ],
        [
            "710549042741321081781917034337800036872214466705318638023070812391485261299",
            "2345013122330545298606028187653996682275206910242635100920038943391319595180",
            "3528369671971445493932880023233332035122954362711876290904323783426765912206",
        ],
        [
            "1167120829038120978297497195837406760848728897181138760506162680655977700764",
            "3073243357129146594530765548901087443775563058893907738967898816092270628884",
            "378514724418106317738164464176041649567501099164061863402473942795977719726",
        ],
        [
            "333391138410406330127594722511180398159664250722328578952158227406762627796",
            "1727570175639917398410201375510924114487348765559913502662122372848626931905",
            "968312190621809249603425066974405725769739606059422769908547372904403793174",
        ],
        [
            "360659316299446405855194688051178331671817370423873014757323462844775818348",
            "1386580151907705298970465943238806620109618995410132218037375811184684929291",
            "3604888328937389309031638299660239238400230206645344173700074923133890528967",
        ],
        [
            "2496185632263372962152518155651824899299616724241852816983268163379540137546",
            "486538168871046887467737983064272608432052269868418721234810979756540672990",
            "1558415498960552213241704009433360128041672577274390114589014204605400783336",
        ],
        [
            "3512058327686147326577190314835092911156317204978509183234511559551181053926",
            "2235429387083113882635494090887463486491842634403047716936833563914243946191",
            "1290896777143878193192832813769470418518651727840187056683408155503813799882",
        ],
        [
            "1143310336918357319571079551779316654556781203013096026972411429993634080835",
            "3235435208525081966062419599803346573407862428113723170955762956243193422118",
            "1293239921425673430660897025143433077974838969258268884994339615096356996604",
        ],
        [
            "236252269127612784685426260840574970698541177557674806964960352572864382971",
            "1733907592497266237374827232200506798207318263912423249709509725341212026275",
            "302004309771755665128395814807589350526779835595021835389022325987048089868",
        ],
        [
            "3018926838139221755384801385583867283206879023218491758435446265703006270945",
            "39701437664873825906031098349904330565195980985885489447836580931425171297",
            "908381723021746969965674308809436059628307487140174335882627549095646509778",
        ],
        [
            "219062858908229855064136253265968615354041842047384625689776811853821594358",
            "1283129863776453589317845316917890202859466483456216900835390291449830275503",
            "418512623547417594896140369190919231877873410935689672661226540908900544012",
        ],
        [
            "1792181590047131972851015200157890246436013346535432437041535789841136268632",
            "370546432987510607338044736824316856592558876687225326692366316978098770516",
            "3323437805230586112013581113386626899534419826098235300155664022709435756946",
        ],
        [
            "910076621742039763058481476739499965761942516177975130656340375573185415877",
            "1762188042455633427137702520675816545396284185254002959309669405982213803405",
            "2186362253913140345102191078329764107619534641234549431429008219905315900520",
        ],
        [
            "2230647725927681765419218738218528849146504088716182944327179019215826045083",
            "1069243907556644434301190076451112491469636357133398376850435321160857761825",
            "2695241469149243992683268025359863087303400907336026926662328156934068747593",
        ],
        [
            "1361519681544413849831669554199151294308350560528931040264950307931824877035",
            "1339116632207878730171031743761550901312154740800549632983325427035029084904",
            "790593524918851401449292693473498591068920069246127392274811084156907468875",
        ],
        [
            "2723400368331924254840192318398326090089058735091724263333980290765736363637",
            "3457180265095920471443772463283225391927927225993685928066766687141729456030",
            "1483675376954327086153452545475557749815683871577400883707749788555424847954",
        ],
        [
            "2926303836265506736227240325795090239680154099205721426928300056982414025239",
            "543969119775473768170832347411484329362572550684421616624136244239799475526",
            "237401230683847084256617415614300816373730178313253487575312839074042461932",
        ],
        [
            "844568412840391587862072008674263874021460074878949862892685736454654414423",
            "151922054871708336050647150237534498235916969120198637893731715254687336644",
            "1299332034710622815055321547569101119597030148120309411086203580212105652312",
        ],
        [
            "487046922649899823989594814663418784068895385009696501386459462815688122993",
            "1104883249092599185744249485896585912845784382683240114120846423960548576851",
            "1458388705536282069567179348797334876446380557083422364875248475157495514484",
        ],
        [
            "850248109622750774031817200193861444623975329881731864752464222442574976566",
            "2885843173858536690032695698009109793537724845140477446409245651176355435722",
            "3027068551635372249579348422266406787688980506275086097330568993357835463816",
        ],
        [
            "3231892723647447539926175383213338123506134054432701323145045438168976970994",
            "1719080830641935421242626784132692936776388194122314954558418655725251172826",
            "1172253756541066126131022537343350498482225068791630219494878195815226839450",
        ],
        [
            "1619232269633026603732619978083169293258272967781186544174521481891163985093",
            "3495680684841853175973173610562400042003100419811771341346135531754869014567",
            "1576161515913099892951745452471618612307857113799539794680346855318958552758",
        ],
        [
            "2618326122974253423403350731396350223238201817594761152626832144510903048529",
            "2696245132758436974032479782852265185094623165224532063951287925001108567649",
            "930116505665110070247395429730201844026054810856263733273443066419816003444",
        ],
        [
            "2786389174502246248523918824488629229455088716707062764363111940462137404076",
            "1555260846425735320214671887347115247546042526197895180675436886484523605116",
            "2306241912153325247392671742757902161446877415586158295423293240351799505917",
        ],
        [
            "411529621724849932999694270803131456243889635467661223241617477462914950626",
            "1542495485262286701469125140275904136434075186064076910329015697714211835205",
            "1853045663799041100600825096887578544265580718909350942241802897995488264551",
        ],
        [
            "2963055259497271220202739837493041799968576111953080503132045092194513937286",
            "2303806870349915764285872605046527036748108533406243381676768310692344456050",
            "2622104986201990620910286730213140904984256464479840856728424375142929278875",
        ],
        [
            "2369987021925266811581727383184031736927816625797282287927222602539037105864",
            "285070227712021899602056480426671736057274017903028992288878116056674401781",
            "3034087076179360957800568733595959058628497428787907887933697691951454610691",
        ],
        [
            "469095854351700119980323115747590868855368701825706298740201488006320881056",
            "360001976264385426746283365024817520563236378289230404095383746911725100012",
            "3438709327109021347267562000879503009590697221730578667498351600602230296178",
        ],
        [
            "63573904800572228121671659287593650438456772568903228287754075619928214969",
            "3470881855042989871434874691030920672110111605547839662680968354703074556970",
            "724559311507950497340993415408274803001166693839947519425501269424891465492",
        ],
        [
            "880409284677518997550768549487344416321062350742831373397603704465823658986",
            "6876255662475867703077362872097208259197756317287339941435193538565586230",
            "2701916445133770775447884812906226786217969545216086200932273680400909154638",
        ],
        [
            "425152119158711585559310064242720816611629181537672850898056934507216982586",
            "1475552998258917706756737045704649573088377604240716286977690565239187213744",
            "2413772448122400684309006716414417978370152271397082147158000439863002593561",
        ],
        [
            "392160855822256520519339260245328807036619920858503984710539815951012864164",
            "1075036996503791536261050742318169965707018400307026402939804424927087093987",
            "2176439430328703902070742432016450246365760303014562857296722712989275658921",
        ],
        [
            "1413865976587623331051814207977382826721471106513581745229680113383908569693",
            "4879283427490523253696177116563427032332223531862961281430108575019551814",
            "3392583297537374046875199552977614390492290683707960975137418536812266544902",
        ],
        [
            "3600854486849487646325182927019642276644093512133907046667282144129939150983",
            "2779924664161372134024229593301361846129279572186444474616319283535189797834",
            "2722699960903170449291146429799738181514821447014433304730310678334403972040",
        ],
        [
            "819109815049226540285781191874507704729062681836086010078910930707209464699",
            "3046121243742768013822760785918001632929744274211027071381357122228091333823",
            "1339019590803056172509793134119156250729668216522001157582155155947567682278",
        ],
        [
            "1933279639657506214789316403763326578443023901555983256955812717638093967201",
            "2138221547112520744699126051903811860205771600821672121643894708182292213541",
            "2694713515543641924097704224170357995809887124438248292930846280951601597065",
        ],
        [
            "2471734202930133750093618989223585244499567111661178960753938272334153710615",
            "504903761112092757611047718215309856203214372330635774577409639907729993533",
            "1943979703748281357156510253941035712048221353507135074336243405478613241290",
        ],
        [
            "684525210957572142559049112233609445802004614280157992196913315652663518936",
            "1705585400798782397786453706717059483604368413512485532079242223503960814508",
            "192429517716023021556170942988476050278432319516032402725586427701913624665",
        ],
        [
            "1586493702243128040549584165333371192888583026298039652930372758731750166765",
            "686072673323546915014972146032384917012218151266600268450347114036285993377",
            "3464340397998075738891129996710075228740496767934137465519455338004332839215",
        ],
        [
            "2805249176617071054530589390406083958753103601524808155663551392362371834663",
            "667746464250968521164727418691487653339733392025160477655836902744186489526",
            "1131527712905109997177270289411406385352032457456054589588342450404257139778",
        ],
        [
            "1908969485750011212309284349900149072003218505891252313183123635318886241171",
            "1025257076985551890132050019084873267454083056307650830147063480409707787695",
            "2153175291918371429502545470578981828372846236838301412119329786849737957977",
        ],
        [
            "3410257749736714576487217882785226905621212230027780855361670645857085424384",
            "3442969106887588154491488961893254739289120695377621434680934888062399029952",
            "3029953900235731770255937704976720759948880815387104275525268727341390470237",
        ],
        [
            "85453456084781138713939104192561924536933417707871501802199311333127894466",
            "2730629666577257820220329078741301754580009106438115341296453318350676425129",
            "178242450661072967256438102630920745430303027840919213764087927763335940415",
        ],
        [
            "2844589222514708695700541363167856718216388819406388706818431442998498677557",
            "3547876269219141094308889387292091231377253967587961309624916269569559952944",
            "2525005406762984211707203144785482908331876505006839217175334833739957826850",
        ],
        [
            "3096397013555211396701910432830904669391580557191845136003938801598654871345",
            "574424067119200181933992948252007230348512600107123873197603373898923821490",
            "1714030696055067278349157346067719307863507310709155690164546226450579547098",
        ],
        [
            "2339895272202694698739231405357972261413383527237194045718815176814132612501",
            "3562501318971895161271663840954705079797767042115717360959659475564651685069",
            "69069358687197963617161747606993436483967992689488259107924379545671193749",
        ],
        [
            "2614502738369008850475068874731531583863538486212691941619835266611116051561",
            "655247349763023251625727726218660142895322325659927266813592114640858573566",
            "2305235672527595714255517865498269719545193172975330668070873705108690670678",
        ],
        [
            "926416070297755413261159098243058134401665060349723804040714357642180531931",
            "866523735635840246543516964237513287099659681479228450791071595433217821460",
            "2284334068466681424919271582037156124891004191915573957556691163266198707693",
        ],
        [
            "1812588309302477291425732810913354633465435706480768615104211305579383928792",
            "2836899808619013605432050476764608707770404125005720004551836441247917488507",
            "2989087789022865112405242078196235025698647423649950459911546051695688370523",
        ],
        [
            "68056284404189102136488263779598243992465747932368669388126367131855404486",
            "505425339250887519581119854377342241317528319745596963584548343662758204398",
            "2118963546856545068961709089296976921067035227488975882615462246481055679215",
        ],
        [
            "2253872596319969096156004495313034590996995209785432485705134570745135149681",
            "1625090409149943603241183848936692198923183279116014478406452426158572703264",
            "179139838844452470348634657368199622305888473747024389514258107503778442495",
        ],
        [
            "1567067018147735642071130442904093290030432522257811793540290101391210410341",
            "2737301854006865242314806979738760349397411136469975337509958305470398783585",
            "3002738216460904473515791428798860225499078134627026021350799206894618186256",
        ],
        [
            "374029488099466837453096950537275565120689146401077127482884887409712315162",
            "973403256517481077805460710540468856199855789930951602150773500862180885363",
            "2691967457038172130555117632010860984519926022632800605713473799739632878867",
        ],
        [
            "3515906794910381201365530594248181418811879320679684239326734893975752012109",
            "148057579455448384062325089530558091463206199724854022070244924642222283388",
            "1541588700238272710315890873051237741033408846596322948443180470429851502842",
        ],
        [
            "147013865879011936545137344076637170977925826031496203944786839068852795297",
            "2630278389304735265620281704608245039972003761509102213752997636382302839857",
            "1359048670759642844930007747955701205155822111403150159614453244477853867621",
        ],
        [
            "2438984569205812336319229336885480537793786558293523767186829418969842616677",
            "2137792255841525507649318539501906353254503076308308692873313199435029594138",
            "2262318076430740712267739371170174514379142884859595360065535117601097652755",
        ],
        [
            "2792703718581084537295613508201818489836796608902614779596544185252826291584",
            "2294173715793292812015960640392421991604150133581218254866878921346561546149",
            "2770011224727997178743274791849308200493823127651418989170761007078565678171",
        ],
    ];

    raw.iter()
        .map(|r| {
            [
                FieldElement::from_dec_str(r[0]).unwrap(),
                FieldElement::from_dec_str(r[1]).unwrap(),
                FieldElement::from_dec_str(r[2]).unwrap(),
            ]
        })
        .collect()
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_display() {
        let err = CudaFftError::NoDevice;
        assert_eq!(format!("{}", err), "No CUDA device found");

        let err = CudaFftError::KernelCompilation("test".to_string());
        assert!(format!("{}", err).contains("test"));
    }

    #[test]
    fn test_cuda_not_available_without_feature() {
        // When cuda-runtime feature is not enabled, CUDA should not be available
        #[cfg(not(feature = "cuda-runtime"))]
        {
            assert!(!is_cuda_available());
        }
    }
}