tomoxide 0.14.0

GPU/CPU tomographic reconstruction toolkit (tomopy + tomocupy, in Rust)
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
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
//! # tomoxide-cuda
//!
//! The CUDA backend. It re-uses tomocupy's battle-tested `.cu` kernels through
//! a thin C-ABI shim (see `ffi` and `cuda/shim.cpp`) rather than rewriting
//! them. Compiled only when the **`cuda` feature** is enabled and an NVIDIA
//! toolkit is present; otherwise [`CudaBackend::new`] reports the backend as
//! unavailable so the rest of the workspace still builds and runs (on CPU).
//!
//! ## M4 scope
//! GPU capabilities wired through the shim: the FBP **filter** (`cfunc_filter`,
//! cuFFT), parallel-beam **back-projection** (`cfunc_linerec`), **Fourier**
//! reconstruction (`cfunc_fourierrec`, via the `FourierReconstruct` capability),
//! and **elementwise** dark/flat + minus-log. The `AnalyticReconstruct`
//! capability fuses the analytic chain into a **device-resident** path:
//! `recon(Fbp/Linerec/Fourierrec, &CudaBackend)` uploads the sinogram once,
//! runs pad → filter → crop → back-projection (or pack → fourierrec → unpack)
//! all on the device, and downloads the volume once — no per-stage host copies.
//! A cuFFT-backed [`Fft`](crate::backend::Fft) capability additionally
//! composes every Fft-based method onto CUDA through the backend-agnostic code:
//! `gridrec`, `lprec`, and Paganin/GPaganin/Farago phase all run on the GPU.
//! Still CPU-only: stripe removal (`remove_stripe` takes no backend).
#![cfg_attr(not(feature = "cuda"), allow(dead_code))]

#[cfg(feature = "cuda")]
pub mod ffi;

use crate::backend::{Backend, DeviceKind};
use crate::dtype::Dtype;
#[cfg(not(feature = "cuda"))]
use crate::error::Error;
use crate::error::Result;

/// Handle to the CUDA backend.
#[derive(Clone, Copy, Debug, Default)]
pub struct CudaBackend;

impl CudaBackend {
    /// Initialise the CUDA backend.
    ///
    /// Without the `cuda` feature this always returns
    /// [`crate::Error::BackendUnavailable`]. With the feature it probes for a device
    /// via the shim and fails if none is present.
    pub fn new() -> Result<Self> {
        #[cfg(not(feature = "cuda"))]
        {
            Err(Error::BackendUnavailable(
                "compiled without the `cuda` feature".into(),
            ))
        }
        #[cfg(feature = "cuda")]
        {
            let count = unsafe { ffi::tomoxide_cuda_device_count() };
            if count <= 0 {
                return Err(crate::error::Error::BackendUnavailable(
                    "no CUDA device found".into(),
                ));
            }
            Ok(CudaBackend)
        }
    }
}

/// Pre-averaged flat/dark correction to **fuse** into the laminography
/// fourierrec stage-1 upload, instead of a standalone full-stack GPU round-trip
/// (`normalize_dataset` uploads the whole projection stack, runs darkflat +
/// minus-log, downloads it, then the recon re-uploads it chunk by chunk — three
/// wasted full-stack PCIe copies). When [`crate::reconstruct_lamino_streaming`]
/// can defer normalization to the recon (Fourierrec, no host-domain phase/stripe
/// prep between), it hands the recon a `LamNorm` and the recon applies the
/// correction to each projection chunk it already uploads for stage 1.
///
/// `darkflat` carries `(mean(dark), denom)` — each `[deth·detw]`, the exact
/// operands `crate::prep::normalize::darkflat_frames` produces — or `None`
/// when the dataset had no flat/dark (already-normalized input); minus-log is
/// always applied, matching `normalize_dataset`.
pub struct LamNorm {
    darkflat: Option<(Vec<f32>, Vec<f32>)>,
}

impl LamNorm {
    /// Build the fused correction from a dataset's flat/dark frames, matching
    /// `normalize_dataset` (darkflat when both are present, minus-log always).
    pub fn from_dataset(ds: &crate::data::Dataset<f32>) -> Result<Self> {
        let darkflat = match (&ds.flat, &ds.dark) {
            (Some(flat), Some(dark)) => {
                let (dark2d, denom) = crate::prep::normalize::darkflat_frames(flat, dark)?;
                Some((
                    dark2d.into_raw_vec_and_offset().0,
                    denom.into_raw_vec_and_offset().0,
                ))
            }
            _ => None,
        };
        Ok(Self { darkflat })
    }
}

/// Name of the active CUDA device (e.g. `"NVIDIA RTX 5000 Ada Generation"`),
/// or `None` without the `cuda` feature or when the query fails. Used to key the
/// chunk-tuning cache so a chunk tuned on one GPU is not reused on another model.
/// CUDA device indices a CUDA reconstruction will use, in order. Mirrors the
/// internal selection: `TOMOXIDE_CUDA_DEVICES` (comma-separated indices) when set
/// and non-empty, else all visible devices; an empty/invalid override falls back
/// to `[0]`. Returns `[]` without the `cuda` feature. The multi-GPU `recon`
/// orchestrator fans one z-shard process per returned index.
pub fn selected_devices() -> Vec<i32> {
    #[cfg(not(feature = "cuda"))]
    {
        Vec::new()
    }
    #[cfg(feature = "cuda")]
    {
        cuda_impl::selected_devices()
    }
}

/// Laminography output height `rh` for a detector-row count `nz` and tilt
/// `lamino_angle_deg`: tomocupy's `ceil(nz / cos(angle) / 2) * 2` (even by
/// construction). Pure geometry — no device needed — so a streaming caller can
/// `reserve` the output before the first tile arrives. `params.lamino_rh`
/// overrides it.
pub fn lamino_recon_height(nz: usize, lamino_angle_deg: f32) -> usize {
    let c = (lamino_angle_deg * std::f32::consts::PI / 180.0).cos();
    (((nz as f32 / c) / 2.0).ceil() as usize) * 2
}

/// Reconstruct the single output slice `sz` at every tilt in `tilts_deg`, in one
/// pass over the filtered projection stack. Returns `[tilts_deg.len(), n, n]`,
/// one candidate image per tilt, in the row order given.
///
/// `cfunc_linerec`'s `backprojection_try_lamino` indexes `phi` per output slot,
/// so `N` tilts cost one launch over one filtered stack, where sweeping tilts
/// through [`crate::recon::recon`] costs `N` filter passes and `N` whole
/// `[rh, n, n]` volumes — for the 1024² pouch scans, ~1400 slices of work per
/// tilt discarded.
///
/// **That saving is only real when you already know which slice you want, and a
/// tilt search on an unknown sample does not.** The in-focus layer moves in z
/// with the tilt (measured on the pouch scans: `z_peak` walked 800 → 1120 as the
/// tilt went 40° → 58°), so scoring a fixed `sz` across tilts scores a different
/// plane at every candidate. The tilt response is broad — ~2 % per degree — and
/// the plane error swamps it: on the aligned pouch scan a fixed-slice focus
/// sweep returned an interior wrong answer or railed depending only on which
/// slice it was pointed at. `docs/LAMINOGRAPHY_ALIGNMENT.md` §2 is the reason:
/// score over the *whole* z range, which needs every (tilt, z) pair —
/// exactly the work this primitive skips, so it buys nothing there.
///
/// Use it where the plane is known and fixed: refining a tilt after a
/// full-volume scan has located `z_peak`, or on a sample whose layer is known.
/// The rotation centre is an in-plane shift and does not move `z_peak`, so a
/// fixed `sz` does rank centre candidates — but only **on the sample's own
/// slice, near the answer**. On the aligned reference scan probed at the sample
/// plane (the `--focus_z` band midpoint), the curve resolves the known axis to
/// 1.0 px over ±8 px; probed at an empty plane the response is ~100× weaker and
/// the sweep rails. So [`center_probe_sweep`] refines a prior on a slice the
/// sample occupies; it does not find one, and `tomoxide align` uses it that way.
///
/// The images carry the same orientation and dθ scale as `Algorithm::Linerec`
/// laminography, so a slice here is the slice that reconstruction produces at
/// that tilt, and a focus metric ranks the real thing.
///
/// `sino` must already be prepped (flat/dark, minus-log, stripe removal), like
/// every other analytic CUDA entry point. The rotation center comes from
/// `geom.center`; `geom.beam` is ignored, since `tilts_deg` supplies the tilt.
/// `sz` is a volume z: the same slice index a full reconstruction at that tilt
/// produces, in any algorithm — every path centres z on the recon height's
/// midpoint (`tests/cuda_lamino_z_convention.rs` pins this). `cancel`, if
/// given, is checked before the filtering, before the back-projection and
/// between angle chunks. Errors without the `cuda` feature.
pub fn lamino_tilt_probe(
    sino: &crate::data::Tomo<f32>,
    geom: &crate::geometry::Geometry,
    params: &crate::params::ReconParams,
    tilts_deg: &[f32],
    sz: i32,
    cancel: Option<&crate::pipeline::CancelToken>,
) -> Result<ndarray::Array3<f32>> {
    #[cfg(not(feature = "cuda"))]
    {
        let _ = (sino, geom, params, tilts_deg, sz, cancel);
        Err(Error::Backend("cuda feature not enabled".into()))
    }
    #[cfg(feature = "cuda")]
    {
        cuda_impl::lamino_tilt_probe(sino, geom, params, tilts_deg, sz, cancel)
    }
}

/// Rotation-centre probe — the centre-axis twin of [`lamino_tilt_probe`]:
/// reconstruct output slice `sz` once per candidate in `centers`, in **one**
/// launch, returning `[centers.len(), n, n]`. `geom.beam` supplies the tilt
/// (`Beam::Parallel` ⇒ untilted), so this serves parallel-beam and laminography
/// alike, and `geom.center` is the *nominal* centre that goes into the filter.
///
/// **A probe slice equals the reconstruction at that centre only on the integer
/// lattice.** The filter runs once, at the nominal centre, and each candidate is
/// realised as a shift of the back-projection sampling coordinate — that is what
/// buys N candidates for one filtering, and it is how tomocupy's `try_center`
/// works. A full reconstruction instead moves its centre with a Fourier linear
/// phase. The two coincide exactly when `nominal − candidate` is a whole number
/// of detector columns, and not otherwise. Measured against `Algorithm::Fbp`
/// inside the reconstruction disk (128², shepp2d, 180 angles):
///
/// | `nominal − candidate` | max &#124;probe − recon&#124; / peak |
/// |---|---|
/// | integer (any nominal, fractional included) | `2e-7 … 9e-7` — round-off |
/// | half-integer | `1.6e-2` |
///
/// So a sharpness ranking over a sub-pixel grid does **not** return the sharpest
/// centre: the fractional candidates carry ~1.6 % of extra smoothing that the
/// integer ones do not, and the argmax is pulled onto the integer lattice. Use
/// [`center_probe_sweep`], which keeps every candidate on its own lattice by
/// construction; reach for this function directly only for an integer sweep.
///
/// Outside the reconstruction disk the two differ by ~12 % of peak at any shift,
/// integer or not — the shift moves where the sampling leaves the detector, so
/// the field boundary is not the same set of voxels. Score inside the disk.
///
/// `cancel` is checked as in [`lamino_tilt_probe`].
pub fn center_probe(
    sino: &crate::data::Tomo<f32>,
    geom: &crate::geometry::Geometry,
    params: &crate::params::ReconParams,
    centers: &[f32],
    sz: i32,
    cancel: Option<&crate::pipeline::CancelToken>,
) -> Result<ndarray::Array3<f32>> {
    #[cfg(not(feature = "cuda"))]
    {
        let _ = (sino, geom, params, centers, sz, cancel);
        Err(Error::Backend("cuda feature not enabled".into()))
    }
    #[cfg(feature = "cuda")]
    {
        cuda_impl::center_probe(sino, geom, params, centers, sz, cancel)
    }
}

/// The detector frames a laminography reconstruction at rotation centre
/// `center` and tilt `tilt_deg` reads `band` from: the line integrals of
/// volume slices `z0 .. z0 + nb` of a volume `depth` slices deep, onto a
/// `rows × n` detector at each angle of `theta` (radians). `band` is
/// `[nb, n, n]`; returns `[theta.len(), rows, n]`.
///
/// Column `center` is where voxel column `n/2` lands and volume z is centred
/// on `depth/2`, as in every reconstruction here, so a band read off a
/// reconstruction reprojects onto the frames it was reconstructed from:
/// reprojection matching compares the two. Linear in `band`. One
/// [`LaminoReprojector`] call; hold a reprojector to project the same band
/// at several angle chunks. CUDA-only.
pub fn lamino_reproject(
    band: ndarray::ArrayView3<'_, f32>,
    z0: usize,
    depth: usize,
    theta: &[f32],
    tilt_deg: f32,
    center: f32,
    rows: usize,
) -> Result<ndarray::Array3<f32>> {
    LaminoReprojector::new(band, z0, depth, tilt_deg, center, rows)?.project(theta)
}

/// A band held on the device for [`lamino_reproject`] at any number of angle
/// chunks, uploaded once. The kernel's `int` indexing and its per-angle shared
/// cache bound one [`project`](Self::project) to 6144 angles and fewer than
/// 2^31 elements on either side; split `theta` to stay inside. CUDA-only.
pub struct LaminoReprojector {
    #[cfg(feature = "cuda")]
    inner: cuda_impl::LaminoReprojector,
}

impl LaminoReprojector {
    /// Upload `band` (`[nb, n, n]`, slices `z0 .. z0 + nb` of a volume `depth`
    /// slices deep) for frames of `rows` rows at `tilt_deg` and `center`.
    pub fn new(
        band: ndarray::ArrayView3<'_, f32>,
        z0: usize,
        depth: usize,
        tilt_deg: f32,
        center: f32,
        rows: usize,
    ) -> Result<Self> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = (band, z0, depth, tilt_deg, center, rows);
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            Ok(Self {
                inner: cuda_impl::LaminoReprojector::new(band, z0, depth, tilt_deg, center, rows)?,
            })
        }
    }

    /// The band's frames at each angle of `theta` (radians), `[theta.len(),
    /// rows, n]`.
    pub fn project(&self, theta: &[f32]) -> Result<ndarray::Array3<f32>> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = theta;
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            self.inner.project(theta)
        }
    }

    /// For each frame `t` of `frames` (`[theta.len(), rows, n]`, at angle
    /// `theta[t]`): the band's frame at that angle ([`project`](Self::project))
    /// dotted with frame `t`'s derivative along the detector columns, and along
    /// the rows, each filtered with `filter` as a lamino reconstruction filters
    /// its frames. `[theta.len(), 2]`, columns first; derivatives as numpy's
    /// `gradient`.
    ///
    /// With the band a score's derivative over a reconstruction's band, this is
    /// the score's derivative over each frame's shift through a
    /// back-projection reconstruction (unit gain): that reconstruction moves
    /// by the back-projected filtered frame derivative, and back-projection at
    /// one angle is the transpose of `project`'s. Nothing per angle is
    /// projected or returned, so this costs far less than `project`.
    pub fn shift_gradient(
        &self,
        theta: &[f32],
        frames: ndarray::ArrayView3<'_, f32>,
        filter: crate::params::FilterName,
    ) -> Result<ndarray::Array2<f64>> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = (theta, frames, filter);
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            self.inner.shift_gradient(theta, frames, filter)
        }
    }
}

/// A projection stack held on the device to score one band of its linerec
/// laminography reconstruction for per-frame shifts and a rotation centre, and
/// to differentiate that score. A frame moves as
/// [`PreppedStack::moved`](crate::align::PreppedStack::moved) moves it (no
/// roll); each band slice scores as
/// [`slice_focus`](crate::recon::center::slice_focus). Only the shifts and the
/// centre go to the device per call, and only the scores and derivatives come
/// back, or the band itself from [`band`](Self::band). CUDA-only.
pub struct LaminoBandFocus {
    #[cfg(feature = "cuda")]
    inner: cuda_impl::LaminoBandFocus,
}

/// Where a [`LaminoBandFocus`] keeps its frames between evaluations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BandFrames {
    /// On the device, which must hold the whole stack.
    Device,
    /// In host memory; an evaluation uploads them an angle chunk at a time.
    Host,
}

/// [`LaminoBandFocus::gradient`]'s result.
#[derive(Debug, Clone)]
pub struct BandFocusGradient {
    /// Each band slice's focus, as [`LaminoBandFocus::profile`].
    pub profile: Vec<f64>,
    /// The profile's mean differentiated by each frame's shift, `[nproj, 2]`,
    /// `dx` first.
    pub shift: ndarray::Array2<f64>,
    /// The profile's mean differentiated by the centre.
    pub center: f64,
}

impl LaminoBandFocus {
    /// Hold `proj` (`[nproj, rows, n]` `−log` frames at angles `theta`,
    /// radians) in `frames` to score slices `z.0 ..= z.1` of its
    /// reconstruction at `tilt_deg`, filtered with `filter`.
    pub fn new(
        proj: ndarray::ArrayView3<'_, f32>,
        theta: &[f32],
        filter: crate::params::FilterName,
        tilt_deg: f32,
        z: (usize, usize),
        frames: BandFrames,
    ) -> Result<Self> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = (proj, theta, filter, tilt_deg, z, frames);
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            Ok(Self {
                inner: cuda_impl::LaminoBandFocus::new(proj, theta, filter, tilt_deg, z, frames)?,
            })
        }
    }

    /// Each band slice's focus with frame `t` moved by `(dy[t], dx[t])` and the
    /// rotation axis at detector column `center`.
    pub fn profile(&mut self, dy: &[f32], dx: &[f32], center: f32) -> Result<Vec<f64>> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = (dy, dx, center);
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            self.inner.profile(dy, dx, center)
        }
    }

    /// The band [`profile`](Self::profile) scores, `[z.1 − z.0 + 1, n, n]`:
    /// the reconstruction's slices `z.0 ..= z.1` of the frames so moved.
    pub fn band(&mut self, dy: &[f32], dx: &[f32], center: f32) -> Result<ndarray::Array3<f32>> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = (dy, dx, center);
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            self.inner.band(dy, dx, center)
        }
    }

    /// [`profile`](Self::profile) and its mean's derivatives by every shift
    /// and the centre: the transpose of each step the score takes, so exact
    /// for this discretisation rather than a difference quotient.
    pub fn gradient(&mut self, dy: &[f32], dx: &[f32], center: f32) -> Result<BandFocusGradient> {
        #[cfg(not(feature = "cuda"))]
        {
            let _ = (dy, dx, center);
            Err(Error::Backend("cuda feature not enabled".into()))
        }
        #[cfg(feature = "cuda")]
        {
            self.inner.gradient(dy, dx, center)
        }
    }
}

/// Reconstruct slice `sz` at every candidate in `centers` — each one **exactly**
/// equal to the corresponding full reconstruction, at any candidate spacing.
/// Returns `[centers.len(), n, n]` in the order given. `geom.center` is ignored
/// (each candidate supplies its own); `geom.beam` supplies the tilt.
///
/// This is [`center_probe`] with its integer-lattice restriction made structural
/// instead of documented. A probe is exact only where `nominal − candidate` is a
/// whole number, so rather than sweeping one nominal and letting fractional
/// candidates come back smoothed, this groups the candidates by fractional part
/// and issues **one probe per distinct fraction**, each anchored on a nominal of
/// that fraction. Every candidate is then an integer shift from its own anchor,
/// so no candidate is ever the smoothed one — there is no ranking bias to correct
/// for afterwards, because the biased slices are never produced.
///
/// Cost is one filtering + one launch per distinct fractional part, independent
/// of how many candidates share it: an integer sweep of any width costs one, a
/// quarter-pixel grid costs four. (Candidates on no common lattice — irrational
/// spacings — degenerate to one probe each: still exact, just not amortised.)
///
/// `cancel` is checked within each probe as in [`center_probe`], so also
/// between them.
pub fn center_probe_sweep(
    sino: &crate::data::Tomo<f32>,
    geom: &crate::geometry::Geometry,
    params: &crate::params::ReconParams,
    centers: &[f32],
    sz: i32,
    cancel: Option<&crate::pipeline::CancelToken>,
) -> Result<ndarray::Array3<f32>> {
    #[cfg(not(feature = "cuda"))]
    {
        let _ = (sino, geom, params, centers, sz, cancel);
        Err(Error::Backend("cuda feature not enabled".into()))
    }
    #[cfg(feature = "cuda")]
    {
        cuda_impl::center_probe_sweep(sino, geom, params, centers, sz, cancel)
    }
}

/// Per-tile sink for [`reconstruct_lamino_streaming`]: called as `(rh0, tile)`
/// where `tile` is the `[tlen, n, n]` output volume at rows `[rh0, rh0 + tlen)`
/// (`tlen = tile.dims().0`). Invoked on a single thread in ascending row order,
/// so a `VolumeWriter` sink never crosses threads.
pub type LaminoTileFn<'a> = dyn FnMut(usize, &crate::data::Volume<f32>) -> Result<()> + 'a;

/// Reconstruct a laminography volume on CUDA, streaming the output rh-tiles to
/// `on_tile(rh0, tile)` instead of returning the whole `[rh, n, n]` volume — so
/// an output larger than host RAM never has to be assembled. Returns
/// `(rh, n, n)`. `on_tile` is called on a single thread in ascending row order,
/// so the caller's writer never crosses threads. Errors without the `cuda`
/// feature. The sinogram must already be prepped (flat/dark, minus-log, stripe
/// removal) — [`crate::reconstruct_lamino_streaming`] runs that prep first,
/// **unless** it passes `norm`: for the Fourierrec path with no host-domain prep
/// it defers flat/dark + minus-log into the recon's stage-1 upload (see
/// [`LamNorm`]), so `sino` is then the raw (un-normalized) projection stack.
/// `norm` is honoured only by the Fourierrec path; Fbp/Linerec always require a
/// pre-normalized `sino` (`norm = None`). `cancel` is checked between the
/// chunks of every stage, so Fourierrec stops before its first tile too.
pub fn reconstruct_lamino_streaming(
    sino: &crate::data::Tomo<f32>,
    geom: &crate::geometry::Geometry,
    algorithm: crate::params::Algorithm,
    params: &crate::params::ReconParams,
    norm: Option<&LamNorm>,
    cancel: Option<&crate::pipeline::CancelToken>,
    on_tile: &mut LaminoTileFn,
) -> Result<(usize, usize, usize)> {
    #[cfg(not(feature = "cuda"))]
    {
        let _ = (sino, geom, algorithm, params, norm, cancel, on_tile);
        Err(Error::Backend("cuda feature not enabled".into()))
    }
    #[cfg(feature = "cuda")]
    {
        cuda_impl::reconstruct_lamino_streaming(
            sino, geom, algorithm, params, norm, cancel, on_tile,
        )
    }
}

pub fn device_name() -> Option<String> {
    #[cfg(not(feature = "cuda"))]
    {
        None
    }
    #[cfg(feature = "cuda")]
    {
        let mut buf = [0u8; 256];
        let rc = unsafe {
            ffi::tomoxide_cuda_device_name(buf.as_mut_ptr() as *mut std::os::raw::c_char, buf.len())
        };
        if rc != 0 {
            return None;
        }
        let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
        let name = String::from_utf8_lossy(&buf[..end]).trim().to_string();
        if name.is_empty() {
            None
        } else {
            Some(name)
        }
    }
}

impl Backend for CudaBackend {
    fn name(&self) -> &'static str {
        "cuda"
    }
    fn device(&self) -> DeviceKind {
        DeviceKind::Cuda
    }
    fn supports(&self, dt: Dtype) -> bool {
        // tomocupy compiles f32 and f16 (`*fp16`) kernel variants.
        matches!(dt, Dtype::F32 | Dtype::F16)
    }

    /// FBP filter on the GPU (`cfunc_filter`, cuFFT), applying the shared ramp
    /// definition so the filtered sinogram matches the CPU path.
    #[cfg(feature = "cuda")]
    fn fbp_filter(&self) -> Option<&dyn crate::backend::FbpFilter> {
        Some(self)
    }

    /// Parallel-beam back-projection on the GPU (`cfunc_linerec`).
    #[cfg(feature = "cuda")]
    fn backprojector(&self) -> Option<&dyn crate::backend::FilteredBackproject> {
        Some(self)
    }

    /// Parallel-beam forward projection on the GPU — the discrete adjoint of
    /// `backprojector` (`cfunc_linerec`), which unlocks the iterative suite
    /// (SIRT/MLEM/OSEM/OSPML/PML/GRAD/TIKH/TV) on CUDA via the generic solvers.
    #[cfg(feature = "cuda")]
    fn projector(&self) -> Option<&dyn crate::backend::ForwardProject> {
        Some(self)
    }

    /// Row-action (ART/BART) projection rows. These solvers are sequential
    /// Kaczmarz updates with no GPU kernel in this design, and the rows are
    /// geometry-only, so CUDA reuses the shared host geometry — `recon(Art|Bart,
    /// …, cuda)` runs the same computation, and yields the same result, as the
    /// CPU backend.
    #[cfg(feature = "cuda")]
    fn ray_projector(&self) -> Option<&dyn crate::backend::RayProject> {
        Some(self)
    }

    /// Device-resident iterative reconstruction — keeps the volume/sinogram on
    /// the GPU across all iterations (currently SIRT; others return `None` and
    /// fall back to the generic host solver).
    #[cfg(feature = "cuda")]
    fn iterative_reconstruct(&self) -> Option<&dyn crate::backend::IterativeReconstruct> {
        Some(self)
    }

    /// Fourier-gridding reconstruction on the GPU (`cfunc_fourierrec`).
    #[cfg(feature = "cuda")]
    fn fourier_reconstruct(&self) -> Option<&dyn crate::backend::FourierReconstruct> {
        Some(self)
    }

    /// Fused on-device analytic reconstruction (filter → back-projection /
    /// fourierrec without per-stage host copies).
    #[cfg(feature = "cuda")]
    fn analytic_reconstruct(&self) -> Option<&dyn crate::backend::AnalyticReconstruct> {
        Some(self)
    }

    /// Device-resident log-polar reconstruction (`cuda/lprec.cu`): the
    /// gather/scatter + spline prefilter run on the GPU instead of the host.
    #[cfg(feature = "cuda")]
    fn lprec_reconstruct(&self) -> Option<&dyn crate::backend::LpRecReconstruct> {
        Some(self)
    }

    /// Dark/flat correction + minus-log on the GPU.
    #[cfg(feature = "cuda")]
    fn elementwise(&self) -> Option<&dyn crate::backend::Elementwise> {
        Some(self)
    }

    /// Batched C2C FFT (cuFFT). Implementing this composes every Fft-based
    /// method (gridrec, lprec, Paganin/GPaganin/Farago phase, Fourier-wavelet
    /// stripe) onto CUDA through the backend-agnostic code.
    #[cfg(feature = "cuda")]
    fn fft(&self) -> Option<&dyn crate::backend::Fft> {
        Some(self)
    }

    /// Pinned (`cudaHostAlloc`) staging buffer so the streaming reader can read a
    /// chunk's projections straight into page-locked memory and the H2D is a
    /// direct DMA — no driver staging copy competing with the reader for host
    /// bandwidth. Falls back to a `Vec` if pinning fails.
    #[cfg(feature = "cuda")]
    fn alloc_host_buffer(&self, len: usize) -> Box<dyn crate::backend::HostBuffer> {
        match cuda_impl::PinnedHostBuffer::new(len) {
            Ok(b) => Box::new(b),
            Err(_) => Box::new(crate::backend::VecHostBuffer::new(len)),
        }
    }

    /// CUDA has the device-resident raw path
    /// ([`reconstruct_chunk_raw`](crate::backend::StreamingAnalytic::reconstruct_chunk_raw)),
    /// so the pipeline reads chunks straight into the pinned staging buffer above.
    #[cfg(feature = "cuda")]
    fn wants_raw_chunks(&self) -> bool {
        true
    }
}

#[cfg(feature = "cuda")]
mod cuda_impl {
    use super::{ffi, BandFrames, CudaBackend};
    use crate::backend::{
        make_fbp_filter, parallel_ray_rows, Elementwise, FbpFilter, FilteredBackproject,
        ForwardProject, FourierReconstruct, IterativeReconstruct, LpRecReconstruct, RampShape,
        RayProject, RayRow, StreamingAnalytic,
    };
    use crate::data::{Frames, Layout, Tomo, Volume};
    use crate::error::{Error, Result};
    use crate::geometry::{lamino_phi, lamino_tilt_deg, Angles, Beam, Center, Geometry};
    use crate::params::{FilterName, StripeMethod};
    use crate::pipeline::{check_cancel, CancelToken};
    use crate::prep::alignment::{spline_coeffs, SPLINE_PAD};
    use ndarray::{s, Array3, ArrayView3, ArrayViewMut2, Axis};
    use rayon::prelude::*;
    use rayon::{ThreadPool, ThreadPoolBuilder};
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::os::raw::c_void;
    use std::sync::{Mutex, OnceLock};

    /// RAII wrapper over a `cudaMalloc` allocation (freed on drop).
    struct DevBuf {
        ptr: *mut c_void,
        bytes: usize,
    }

    impl DevBuf {
        fn new(bytes: usize) -> Result<Self> {
            let ptr = unsafe { ffi::tomoxide_cuda_malloc(bytes) };
            if ptr.is_null() {
                return Err(Error::Backend(format!("cudaMalloc({bytes}) failed")));
            }
            Ok(DevBuf { ptr, bytes })
        }

        fn from_host_f32(data: &[f32]) -> Result<Self> {
            let bytes = std::mem::size_of_val(data);
            let buf = DevBuf::new(bytes)?;
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_h2d(buf.ptr, data.as_ptr() as *const c_void, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaMemcpy H2D failed ({rc})")));
            }
            Ok(buf)
        }

        /// Upload host f64 `data` into a fresh device buffer (FW wavelet path is
        /// f64; also used for the per-level damping vectors).
        fn from_host_f64(data: &[f64]) -> Result<Self> {
            let bytes = std::mem::size_of_val(data);
            let buf = DevBuf::new(bytes)?;
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_h2d(buf.ptr, data.as_ptr() as *const c_void, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaMemcpy H2D (f64) failed ({rc})"
                )));
            }
            Ok(buf)
        }

        /// Upload host i32 `data` into a fresh device buffer (lprec target index
        /// sets: `lpids`/`wids`/`cids`).
        fn from_host_i32(data: &[i32]) -> Result<Self> {
            let bytes = std::mem::size_of_val(data);
            let buf = DevBuf::new(bytes)?;
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_h2d(buf.ptr, data.as_ptr() as *const c_void, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaMemcpy H2D (i32) failed ({rc})"
                )));
            }
            Ok(buf)
        }

        fn zeroed(bytes: usize) -> Result<Self> {
            let buf = DevBuf::new(bytes)?;
            let rc = unsafe { ffi::tomoxide_cuda_memset(buf.ptr, 0, bytes) };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaMemset failed ({rc})")));
            }
            Ok(buf)
        }

        fn to_host_f32(&self, out: &mut [f32]) -> Result<()> {
            let bytes = std::mem::size_of_val(out);
            debug_assert!(bytes <= self.bytes);
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_d2h(out.as_mut_ptr() as *mut c_void, self.ptr, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaMemcpy D2H failed ({rc})")));
            }
            Ok(())
        }

        /// Upload `data` (host f32) as half-precision: each element is rounded to
        /// `f16` so the device buffer holds 2 bytes/element. Used for the f16
        /// analytic path (sinogram and filter weights).
        fn from_host_f16(data: &[f32]) -> Result<Self> {
            // The f32→f16 round of a full sinogram/volume is tens-to-hundreds of
            // millions of scalars; single-threaded it dominated the f16 path's
            // overhead. par_iter().collect() keeps element order.
            let h: Vec<half::f16> = data.par_iter().map(|&x| half::f16::from_f32(x)).collect();
            let bytes = std::mem::size_of_val(h.as_slice());
            let buf = DevBuf::new(bytes)?;
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_h2d(buf.ptr, h.as_ptr() as *const c_void, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaMemcpy H2D (f16) failed ({rc})"
                )));
            }
            Ok(buf)
        }

        /// Download `count` f64 elements into a fresh Vec.
        fn to_host_f64(&self, count: usize) -> Result<Vec<f64>> {
            let mut out = vec![0.0f64; count];
            let bytes = std::mem::size_of_val(out.as_slice());
            debug_assert!(bytes <= self.bytes);
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_d2h(out.as_mut_ptr() as *mut c_void, self.ptr, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaMemcpy D2H (f64) failed ({rc})"
                )));
            }
            Ok(out)
        }

        /// Upload host f32 `data` into this **already-allocated** buffer (no
        /// realloc). Used by the streaming reconstructor, which reuses one buffer
        /// across chunks. `data` must fit (`len*4 ≤ self.bytes`).
        fn copy_from_host_f32(&self, data: &[f32]) -> Result<()> {
            let bytes = std::mem::size_of_val(data);
            debug_assert!(bytes <= self.bytes);
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_h2d(self.ptr, data.as_ptr() as *const c_void, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaMemcpy H2D failed ({rc})")));
            }
            Ok(())
        }

        /// Upload host f32 `data` rounded to `f16` into this already-allocated
        /// buffer (no realloc). f16 streaming counterpart of
        /// [`copy_from_host_f32`]; `len*2 ≤ self.bytes`.
        fn copy_from_host_f16(&self, data: &[f32]) -> Result<()> {
            let h: Vec<half::f16> = data.par_iter().map(|&x| half::f16::from_f32(x)).collect();
            let bytes = std::mem::size_of_val(h.as_slice());
            debug_assert!(bytes <= self.bytes);
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_h2d(self.ptr, h.as_ptr() as *const c_void, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaMemcpy H2D (f16) failed ({rc})"
                )));
            }
            Ok(())
        }

        /// Download `count` half-precision elements and widen them back to f32.
        fn to_host_f16_as_f32(&self, count: usize) -> Result<Vec<f32>> {
            let mut h = vec![half::f16::from_f32(0.0); count];
            let bytes = std::mem::size_of_val(h.as_slice());
            debug_assert!(bytes <= self.bytes);
            let rc = unsafe {
                ffi::tomoxide_cuda_memcpy_d2h(h.as_mut_ptr() as *mut c_void, self.ptr, bytes)
            };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaMemcpy D2H (f16) failed ({rc})"
                )));
            }
            // Widen f16→f32 in parallel (see from_host_f16); order preserved.
            Ok(h.par_iter().map(|x| x.to_f32()).collect())
        }
    }

    impl Drop for DevBuf {
        fn drop(&mut self) {
            unsafe { ffi::tomoxide_cuda_free(self.ptr) };
        }
    }

    thread_local! {
        /// Per-thread reusable device scratch for the composed FFT path, keyed by
        /// exact byte size. `Fft::for_each_slice` runs the per-slice loop on
        /// device-pinned worker threads, and each thread issues many same-shaped
        /// `fft_1d`/`fft_2d` calls, so a `cudaMalloc`/`cudaFree` per call serialized
        /// on the driver and dominated the per-slice cost. Thread-local ⇒ no
        /// locking and each buffer lives on the device its worker is pinned to;
        /// keyed by size ⇒ a constant-shape loop reuses one allocation for all
        /// slices. Buffers are freed when the worker thread exits (process end).
        static FFT_SCRATCH: RefCell<HashMap<usize, DevBuf>> = RefCell::new(HashMap::new());
    }

    /// Run `f` with a thread-local device scratch buffer of exactly `bytes`,
    /// allocating it once per (thread, size) and reusing it thereafter. Replaces
    /// the per-call `DevBuf::from_host_f32` allocate-free in the FFT wrappers.
    fn with_fft_scratch<R>(bytes: usize, f: impl FnOnce(&DevBuf) -> Result<R>) -> Result<R> {
        use std::collections::hash_map::Entry;
        FFT_SCRATCH.with(|cell| {
            let mut map = cell.borrow_mut();
            let buf = match map.entry(bytes) {
                Entry::Occupied(e) => e.into_mut(),
                Entry::Vacant(e) => e.insert(DevBuf::new(bytes)?),
            };
            f(buf)
        })
    }

    /// An owned CUDA stream. Work issued on it runs in order but overlaps work on
    /// other streams; the async pipeline uses one per double-buffer slot so a
    /// chunk's compute can run while another slot's H2D/D2H copies are in flight.
    struct Stream {
        ptr: *mut c_void,
    }

    impl Stream {
        fn new() -> Result<Self> {
            let ptr = unsafe { ffi::tomoxide_cuda_stream_create() };
            if ptr.is_null() {
                return Err(Error::Backend("cudaStreamCreate failed".into()));
            }
            Ok(Stream { ptr })
        }

        /// Block the calling thread until every operation on this stream finishes.
        fn sync(&self) -> Result<()> {
            let rc = unsafe { ffi::tomoxide_cuda_stream_sync(self.ptr) };
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cudaStreamSynchronize failed ({rc})"
                )));
            }
            Ok(())
        }

        /// Defer all work subsequently enqueued on this stream until `e` fires
        /// (device-side; the host is not blocked). Used to make a copy stream wait
        /// for a compute-stream event before reusing/reading a double buffer.
        fn wait_event(&self, e: &Event) -> Result<()> {
            let rc = unsafe { ffi::tomoxide_cuda_stream_wait_event(self.ptr, e.ptr) };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaStreamWaitEvent failed ({rc})")));
            }
            Ok(())
        }
    }

    impl Drop for Stream {
        fn drop(&mut self) {
            unsafe { ffi::tomoxide_cuda_stream_destroy(self.ptr) };
        }
    }

    /// A CUDA event used only for cross-stream ordering (timing disabled). Record
    /// it on one stream, `Stream::wait_event` it on another.
    struct Event {
        ptr: *mut c_void,
    }

    impl Event {
        fn new() -> Result<Self> {
            let ptr = unsafe { ffi::tomoxide_cuda_event_create() };
            if ptr.is_null() {
                return Err(Error::Backend("cudaEventCreate failed".into()));
            }
            Ok(Event { ptr })
        }

        /// Record on the **compute** (per-thread) stream — the one the FFTs and the
        /// `null`-stream kernels run on (this build uses `--default-stream
        /// per-thread`, so a null stream handle *is* `cudaStreamPerThread`).
        fn record_compute(&self) -> Result<()> {
            let rc = unsafe { ffi::tomoxide_cuda_event_record(self.ptr, std::ptr::null_mut()) };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaEventRecord failed ({rc})")));
            }
            Ok(())
        }

        /// Record on the copy `stream`.
        fn record_on(&self, stream: &Stream) -> Result<()> {
            let rc = unsafe { ffi::tomoxide_cuda_event_record(self.ptr, stream.ptr) };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaEventRecord failed ({rc})")));
            }
            Ok(())
        }

        /// Defer subsequent **compute** (per-thread) work until this event fires.
        fn wait_compute(&self) -> Result<()> {
            let rc =
                unsafe { ffi::tomoxide_cuda_stream_wait_event(std::ptr::null_mut(), self.ptr) };
            if rc != 0 {
                return Err(Error::Backend(format!("cudaStreamWaitEvent failed ({rc})")));
            }
            Ok(())
        }
    }

    impl Drop for Event {
        fn drop(&mut self) {
            unsafe { ffi::tomoxide_cuda_event_destroy(self.ptr) };
        }
    }

    /// An owned `cfunc_*` handle, freed on drop so a launch error returned with
    /// `?` between its creation and its last use does not leak it.
    struct Handle {
        ptr: *mut c_void,
        free: unsafe extern "C" fn(*mut c_void),
    }

    impl Handle {
        /// Take `ptr` from a `tomoxide_*_new`; null (allocation failed) is an error.
        fn new(
            ptr: *mut c_void,
            free: unsafe extern "C" fn(*mut c_void),
            what: &str,
        ) -> Result<Self> {
            if ptr.is_null() {
                return Err(Error::Backend(format!("{what} allocation failed")));
            }
            Ok(Handle { ptr, free })
        }
    }

    impl Drop for Handle {
        fn drop(&mut self) {
            unsafe { (self.free)(self.ptr) };
        }
    }

    /// A page-locked (pinned) host buffer of `f32`. Async H2D/D2H copies only
    /// overlap kernel execution when their host side is pinned — pageable memory
    /// forces the driver into a synchronous staged copy, defeating the pipeline.
    struct PinnedBuf<T = f32> {
        ptr: *mut c_void,
        len: usize, // elements
        _marker: std::marker::PhantomData<T>,
    }

    impl<T: Copy> PinnedBuf<T> {
        fn new(len: usize) -> Result<Self> {
            let bytes = len * std::mem::size_of::<T>();
            // Test/debug hook: refuse a buffer above this many bytes, as a
            // Windows host refuses one beyond its pinned share.
            let refused = std::env::var("TOMOXIDE_CUDA_MAX_PINNED_BYTES")
                .ok()
                .and_then(|s| s.trim().parse::<usize>().ok())
                .is_some_and(|cap| bytes > cap);
            let ptr = if refused {
                std::ptr::null_mut()
            } else {
                unsafe { ffi::tomoxide_cuda_host_alloc(bytes) }
            };
            if ptr.is_null() {
                return Err(Error::Backend(format!("cudaHostAlloc({len} elems) failed")));
            }
            Ok(PinnedBuf {
                ptr,
                len,
                _marker: std::marker::PhantomData,
            })
        }

        fn as_mut_slice(&mut self) -> &mut [T] {
            unsafe { std::slice::from_raw_parts_mut(self.ptr as *mut T, self.len) }
        }

        fn as_slice(&self) -> &[T] {
            unsafe { std::slice::from_raw_parts(self.ptr as *const T, self.len) }
        }
    }

    impl<T> Drop for PinnedBuf<T> {
        fn drop(&mut self) {
            unsafe { ffi::tomoxide_cuda_host_free(self.ptr) };
        }
    }

    /// Elements in each slab of a [`PinnedStage`] (64 MiB of `f32`).
    const PINNED_STAGE_ELEMS: usize = 16 << 20;

    /// Moves pageable host data to or from the device through two pinned slabs
    /// of at most [`PINNED_STAGE_ELEMS`], the host filling or emptying one while
    /// the other's DMA runs. The pinned footprint is fixed rather than sized to a
    /// stack, a volume or a device chunk: Windows pins only a share of RAM, so a
    /// buffer that large fails there with RAM to spare.
    struct PinnedStage {
        slab: [PinnedBuf<f32>; 2],
        // Recorded after each slab's latest DMA; synced before the host refills it.
        dma: [Event; 2],
    }

    impl PinnedStage {
        /// Slabs for transfers of up to `len` elements.
        fn new(len: usize) -> Result<Self> {
            let elems = len.clamp(1, PINNED_STAGE_ELEMS);
            Ok(PinnedStage {
                slab: [PinnedBuf::new(elems)?, PinnedBuf::new(elems)?],
                dma: [Event::new()?, Event::new()?],
            })
        }

        /// Enqueue `src` → device `dst` on `stream`, returning once every piece
        /// is staged; work that reads `dst` orders after `stream`.
        fn upload(&mut self, dst: *mut c_void, src: &[f32], stream: &Stream) -> Result<()> {
            let piece = self.slab[0].len;
            for (k, part) in src.chunks(piece).enumerate() {
                let s = k % 2;
                ck(
                    unsafe { ffi::tomoxide_cuda_event_sync(self.dma[s].ptr) },
                    "stage_h2d_sync",
                )?;
                par_copy(&mut self.slab[s].as_mut_slice()[..part.len()], part);
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memcpy_h2d_async(
                            (dst as *mut f32).add(k * piece) as *mut c_void,
                            self.slab[s].ptr,
                            std::mem::size_of_val(part),
                            stream.ptr,
                        )
                    },
                    "stage_h2d",
                )?;
                self.dma[s].record_on(stream)?;
            }
            Ok(())
        }

        /// Copy device `src` → `dst` after the work already on `stream`,
        /// returning once `dst` holds it.
        fn download(&self, dst: &mut [f32], src: *const c_void, stream: &Stream) -> Result<()> {
            let (piece, total) = (self.slab[0].len, dst.len());
            let issue = |k: usize| -> Result<()> {
                let s = k % 2;
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memcpy_d2h_async(
                            self.slab[s].ptr,
                            (src as *const f32).add(k * piece) as *const c_void,
                            piece.min(total - k * piece) * std::mem::size_of::<f32>(),
                            stream.ptr,
                        )
                    },
                    "stage_d2h",
                )?;
                self.dma[s].record_on(stream)
            };
            issue(0)?;
            // Piece k+1's DMA runs while the host empties piece k.
            for (k, out) in dst.chunks_mut(piece).enumerate() {
                if (k + 1) * piece < total {
                    issue(k + 1)?;
                }
                let s = k % 2;
                ck(
                    unsafe { ffi::tomoxide_cuda_event_sync(self.dma[s].ptr) },
                    "stage_d2h_sync",
                )?;
                let n = out.len();
                par_copy(out, &self.slab[s].as_slice()[..n]);
            }
            Ok(())
        }
    }

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

        // 2.5 slabs per transfer: pieces alternate slabs, the last one is short,
        // and the second upload refills slabs the first one's DMA still owns.
        #[test]
        fn pieces_round_trip_through_two_slabs() {
            let _b = CudaBackend::new().expect("cuda backend");
            ck(unsafe { ffi::tomoxide_cuda_set_device(0) }, "set_device").unwrap();
            let (slab, len) = (1000usize, 2500usize);
            let mut stage = PinnedStage {
                slab: [PinnedBuf::new(slab).unwrap(), PinnedBuf::new(slab).unwrap()],
                dma: [Event::new().unwrap(), Event::new().unwrap()],
            };
            let a: Vec<f32> = (0..len).map(|i| i as f32).collect();
            let b: Vec<f32> = (0..len).map(|i| -(i as f32) - 0.5).collect();
            let bytes = len * std::mem::size_of::<f32>();
            let dev = [DevBuf::new(bytes).unwrap(), DevBuf::new(bytes).unwrap()];
            let stream = Stream::new().unwrap();
            stage.upload(dev[0].ptr, &a, &stream).unwrap();
            stage.upload(dev[1].ptr, &b, &stream).unwrap();
            let (mut ra, mut rb) = (vec![0.0f32; len], vec![0.0f32; len]);
            stage.download(&mut ra, dev[0].ptr, &stream).unwrap();
            stage.download(&mut rb, dev[1].ptr, &stream).unwrap();
            assert_eq!(ra, a);
            assert_eq!(rb, b);
        }
    }

    /// A pinned (`cudaHostAlloc`) [`HostBuffer`] of `f32` for the streaming
    /// reader to fill via `read_slice_into`, so a chunk's H2D is a direct DMA. The
    /// page-locked bytes are plain host memory — safe to fill on the reader thread
    /// and upload/free on the compute thread — so it is `Send` (the raw pointer in
    /// `PinnedBuf` only blocks the auto-derive).
    pub(super) struct PinnedHostBuffer(PinnedBuf<f32>);

    impl PinnedHostBuffer {
        /// Allocate `len` pinned `f32`. Errors propagate so the caller can fall
        /// back to a plain `Vec` buffer.
        pub(super) fn new(len: usize) -> Result<Self> {
            Ok(PinnedHostBuffer(PinnedBuf::<f32>::new(len)?))
        }
    }

    // SAFETY: the wrapped pointer addresses page-locked host memory with no
    // thread affinity; `cudaHostAlloc`/`cudaFreeHost` and plain loads/stores are
    // valid from any thread, and the buffer is moved (not shared) across the
    // reader→compute channel.
    unsafe impl Send for PinnedHostBuffer {}

    impl crate::backend::HostBuffer for PinnedHostBuffer {
        fn as_mut_slice(&mut self) -> &mut [f32] {
            self.0.as_mut_slice()
        }
        fn as_slice(&self) -> &[f32] {
            self.0.as_slice()
        }
    }

    impl FilteredBackproject for CudaBackend {
        /// Parallel-beam voxel-driven back-projection via the vendored
        /// `cfunc_linerec` kernel (phi = π/2, gain 1), about `geom.center` (the
        /// analytic dispatcher hands a filtered sinogram centred at `ncols/2`,
        /// the iterative solvers the caller's centre). Output is
        /// `[nz, n, n]` in the **CPU/tomopy convention**: the kernel's tomocupy
        /// y-flip has been unified to the CPU handedness (Phase 1/2 cross-backend
        /// unification), so CUDA back-projection matches the CPU back-projector
        /// directly (see `tests/cuda_cpu_convention_parity.rs` and
        /// `docs/ARCHITECTURE.md §4.1`). Like every `FilteredBackproject`, this is
        /// the *pure* adjoint `Wᵀ` (no angular-quadrature gain): the analytic
        /// dispatcher applies the FBP `π/nproj` dθ weight itself, and the iterative
        /// solvers consume `Wᵀ` directly.
        fn backproject(
            &self,
            sino: &Tomo<f32>,
            geom: &Geometry,
            out: &mut Volume<f32>,
        ) -> Result<()> {
            let pg = pair_geom(geom)?;
            let s = sino.as_layout(Layout::Sinogram); // [nz, nproj, ncols], no copy if already
            let nz = s.n_rows();
            let nproj = s.n_angles();
            let ncols = s.n_cols();
            let (oz, ny, nx) = out.dims();
            if ny != ncols || nx != ncols {
                return Err(Error::InvalidParam(format!(
                    "cuda back-projection needs a square grid = detector width {ncols}; got {ny}x{nx}"
                )));
            }
            let theta = &geom.angles.0;
            if theta.len() != nproj {
                return Err(Error::ShapeMismatch {
                    expected: format!("{nproj} angles"),
                    found: theta.len().to_string(),
                });
            }
            // Laminography: back-project the `[nz, nproj, n]` sinogram into the
            // `[rh, n, n]` volume (rh = output height) with the tilted geometry
            // (sz = 0, ncz = rh). Pure adjoint `Wᵀ` — the exact transpose of the
            // tilted forward projector, so {A, Aᵀ} is a true adjoint pair.
            if matches!(geom.beam, Beam::Laminography { .. }) {
                let rh = oz;
                let sino_std = s.array.as_standard_layout();
                let sino_slice = sino_std
                    .as_slice()
                    .expect("as_standard_layout is C-contiguous");
                let g = DevBuf::from_host_f32(sino_slice)?;
                let theta_d = DevBuf::from_host_f32(theta)?;
                let f = DevBuf::zeroed(rh * ncols * ncols * std::mem::size_of::<f32>())?;
                let handle = Handle::new(
                    unsafe { ffi::tomoxide_linerec_new(nproj, nz, ncols, nproj, rh) },
                    ffi::tomoxide_linerec_free,
                    "cfunc_linerec",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_linerec_backproject(
                            handle.ptr,
                            f.ptr,
                            g.ptr,
                            theta_d.ptr as *const f32,
                            pg.phi,
                            pg.axis,
                            1.0,       // pure adjoint Wᵀ
                            0,         // sz
                            rh as i32, // volume z centred on the full recon height
                            std::ptr::null_mut(),
                        )
                    },
                    "linerec backproject",
                )?;
                let rc = unsafe { ffi::tomoxide_cuda_sync() };
                drop(handle);
                if rc != 0 {
                    return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
                }
                let mut host = vec![0.0f32; rh * ncols * ncols];
                f.to_host_f32(&mut host)?;
                out.array = Array3::from_shape_vec((rh, ncols, ncols), host)
                    .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
                return Ok(());
            }
            if oz != nz {
                return Err(Error::ShapeMismatch {
                    expected: format!("{nz} sinogram rows"),
                    found: oz.to_string(),
                });
            }
            // Materialize a C-contiguous host buffer for the flat D2H upload:
            // the analytic path hands a contiguous `sino.clone()` (borrowed, no
            // copy), but the iterative solvers hand strided sub-sinograms
            // (`select(Axis(1), …)` over an angle subset, e.g. OSEM) — copy those.
            let sino_std = s.array.as_standard_layout();
            let sino_slice = sino_std
                .as_slice()
                .expect("as_standard_layout is C-contiguous");
            // Batch-domain minimum (same family as `IterativeReconstruct::
            // solve`): the kernel's z-bilinear sampling needs ≥2 slices — a
            // 1-slice batch back-projects to zero. Duplicate the row (the
            // interpolation weights sum to 1 on identical rows, so the result
            // is exact) and drop the duplicate after download.
            let nz_run = nz.max(2);
            let dup;
            let sino_slice = if nz_run != nz {
                dup = [sino_slice, sino_slice].concat();
                &dup[..]
            } else {
                sino_slice
            };

            // Device buffers: filtered sinogram, theta, output volume.
            let g = DevBuf::from_host_f32(sino_slice)?;
            let theta_d = DevBuf::from_host_f32(theta)?;
            let f = DevBuf::zeroed(nz_run * ncols * ncols * std::mem::size_of::<f32>())?;

            // cfunc_linerec(nproj, nz, n, ncproj=nproj, ncz=nz): whole stack at once.
            let handle = Handle::new(
                unsafe { ffi::tomoxide_linerec_new(nproj, nz_run, ncols, nproj, nz_run) },
                ffi::tomoxide_linerec_free,
                "cfunc_linerec",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_linerec_backproject(
                        handle.ptr,
                        f.ptr,
                        g.ptr,
                        theta_d.ptr as *const f32,
                        pg.phi, // π/2 (parallel beam)
                        pg.axis,
                        1.0, // pure adjoint Wᵀ — no angular-quadrature gain
                        0,
                        nz_run as i32, // parallel beam: rh == nz
                        std::ptr::null_mut(),
                    )
                },
                "linerec backproject",
            )?;
            let rc = unsafe { ffi::tomoxide_cuda_sync() };
            drop(handle);
            if rc != 0 {
                return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
            }

            let mut host = vec![0.0f32; nz_run * ncols * ncols];
            f.to_host_f32(&mut host)?;
            host.truncate(nz * ncols * ncols);
            out.array = Array3::from_shape_vec((nz, ncols, ncols), host)
                .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
            Ok(())
        }
    }

    impl ForwardProject for CudaBackend {
        /// Parallel-beam forward projection (`forwardprojection_ker`), the exact
        /// discrete transpose of [`FilteredBackproject::backproject`]
        /// (`cfunc_linerec`, phi = π/2, gain 1): same handedness, centre, and
        /// both unweighted, so the two form a true `{A, Aᵀ}` pair — matching the
        /// CPU projector pair — which is what the generic iterative solvers
        /// (SIRT/MLEM/OSEM/OSPML/PML/GRAD/TIKH/TV) require. `A` is the plain
        /// line-integral Radon transform (unit pixel spacing), so a converged
        /// solve of `A x = p` yields the physical μ. Like the back-projector, it
        /// projects about `geom.center` (`pair_geom`) and assumes the detector
        /// width equals the grid `n`. Output is `[nz, nproj, n]` in
        /// `Sinogram` layout.
        fn project(&self, vol: &Volume<f32>, geom: &Geometry, out: &mut Tomo<f32>) -> Result<()> {
            let pg = pair_geom(geom)?;
            let (rh, ny, nx) = vol.dims(); // volume z-extent (== detector rows for parallel)
            if ny != nx {
                return Err(Error::InvalidParam(format!(
                    "cuda forward projection needs a square grid; got {ny}x{nx}"
                )));
            }
            let n = nx;
            let nproj = geom.angles.0.len();
            let ncols = geom.detector.width;
            if ncols != n {
                return Err(Error::InvalidParam(format!(
                    "cuda forward projection needs detector width = grid {n}; got {ncols}"
                )));
            }
            // Detector rows: for the parallel beam this equals the volume height;
            // for laminography the tilted axis makes `rh != nz`, so the detector
            // row count comes from the geometry.
            let nz = geom.detector.height;
            let theta = &geom.angles.0;
            if theta.len() != nproj {
                return Err(Error::ShapeMismatch {
                    expected: format!("{nproj} angles"),
                    found: theta.len().to_string(),
                });
            }
            // Laminography: forward-project the whole `[rh, n, n]` volume into the
            // `[nz, nproj, n]` sinogram with the tilted geometry (sz = 0, ncz = rh).
            // The exact transpose of the `cfunc_linerec` back-projector used by the
            // analytic/iterative lamino paths, so {A, Aᵀ} is a true adjoint pair.
            if let Beam::Laminography { .. } = geom.beam {
                let vol_std = vol.array.as_standard_layout();
                let vol_slice = vol_std
                    .as_slice()
                    .expect("as_standard_layout is C-contiguous");
                let f = DevBuf::from_host_f32(vol_slice)?;
                let theta_d = DevBuf::from_host_f32(theta)?;
                let g = DevBuf::zeroed(nz * nproj * n * std::mem::size_of::<f32>())?;
                ck(
                    unsafe {
                        ffi::tomoxide_forwardproject(
                            g.ptr,
                            f.ptr,
                            theta_d.ptr as *const f32,
                            pg.phi,
                            pg.axis,
                            0,
                            rh as i32,
                            nz as i32,
                            n as i32,
                            rh as i32, // volume z centred on the full recon height
                            nproj as i32,
                            std::ptr::null_mut(),
                        )
                    },
                    "forwardproject",
                )?;
                let rc = unsafe { ffi::tomoxide_cuda_sync() };
                if rc != 0 {
                    return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
                }
                let mut host = vec![0.0f32; nz * nproj * n];
                g.to_host_f32(&mut host)?;
                let array = Array3::from_shape_vec((nz, nproj, n), host)
                    .map_err(|e| Error::InvalidParam(format!("cuda sinogram shape: {e}")))?;
                *out = Tomo::new(array, Layout::Sinogram);
                return Ok(());
            }
            let nz = rh; // parallel beam: volume height == detector rows
                         // Materialize a C-contiguous host buffer for the flat D2H upload
                         // (borrowed when already contiguous, copied otherwise), so the
                         // iterative solvers may hand any array layout — symmetric with the
                         // back-projector's sinogram handling.
            let vol_std = vol.array.as_standard_layout();
            let vol_slice = vol_std
                .as_slice()
                .expect("as_standard_layout is C-contiguous");
            // Batch-domain minimum (same family as `IterativeReconstruct::
            // solve`): the kernel's z-bilinear scatter needs ≥2 slices — a
            // 1-slice volume forward-projects to zero. Duplicate the slice
            // (exact: the interpolation weights sum to 1 on identical rows)
            // and drop the duplicate after download.
            let nz_run = nz.max(2);
            let dup;
            let vol_slice = if nz_run != nz {
                dup = [vol_slice, vol_slice].concat();
                &dup[..]
            } else {
                vol_slice
            };

            // Device buffers: input volume, theta, zeroed output sinogram (the
            // kernel only atomic-adds into it).
            let f = DevBuf::from_host_f32(vol_slice)?;
            let theta_d = DevBuf::from_host_f32(theta)?;
            let g = DevBuf::zeroed(nz_run * nproj * n * std::mem::size_of::<f32>())?;

            ck(
                unsafe {
                    ffi::tomoxide_forwardproject(
                        g.ptr,
                        f.ptr,
                        theta_d.ptr as *const f32,
                        pg.phi, // π/2 (parallel beam)
                        pg.axis,
                        0,
                        nz_run as i32,
                        nz_run as i32,
                        n as i32,
                        nz_run as i32, // parallel beam: rh == nz
                        nproj as i32,
                        std::ptr::null_mut(),
                    )
                },
                "forwardproject",
            )?;
            let rc = unsafe { ffi::tomoxide_cuda_sync() };
            if rc != 0 {
                return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
            }

            let mut host = vec![0.0f32; nz_run * nproj * n];
            g.to_host_f32(&mut host)?;
            host.truncate(nz * nproj * n);
            let array = Array3::from_shape_vec((nz, nproj, n), host)
                .map_err(|e| Error::InvalidParam(format!("cuda sinogram shape: {e}")))?;
            *out = Tomo::new(array, Layout::Sinogram);
            Ok(())
        }
    }

    impl RayProject for CudaBackend {
        /// Row-action (ART/BART) rows. The row-action solvers are sequential
        /// Kaczmarz updates (no GPU kernel in this design) and the rows are
        /// geometry-only, so CUDA reuses the shared host geometry
        /// `parallel_ray_rows` — byte-identical to the CPU backend's rows.
        fn ray_rows(&self, geom: &Geometry, n: usize) -> Result<Vec<Vec<RayRow>>> {
            parallel_ray_rows(geom, n)
        }
    }

    /// What the `{A, Aᵀ}` kernel pair reads of a geometry: the tilt `phi`
    /// (`π/2` for a parallel beam) and `axis`, the detector column voxel column
    /// `n/2` lands on — `geom.center`, as the CPU projector pair reads it.
    /// Threaded into [`dev_forward`]/[`dev_backproject`] and the host
    /// projectors so both directions always share it.
    #[cfg(feature = "cuda")]
    #[derive(Clone, Copy)]
    struct PairGeom {
        phi: f32,
        axis: f32,
    }

    /// [`PairGeom`] of `geom`. The kernels take one centre for every row, so a
    /// `Center::PerRow` with differing values is refused rather than read at
    /// row 0.
    #[cfg(feature = "cuda")]
    fn pair_geom(geom: &Geometry) -> Result<PairGeom> {
        let phi = match geom.beam {
            Beam::Parallel => std::f32::consts::FRAC_PI_2,
            Beam::Laminography { phi } => phi,
            Beam::Cone { .. } => {
                return Err(Error::InvalidParam(
                    "the cuda projector pair supports parallel beam and laminography only".into(),
                ));
            }
        };
        let axis = match &geom.center {
            Center::Scalar(c) => *c,
            Center::PerRow(v) => {
                let first = *v
                    .first()
                    .ok_or_else(|| Error::InvalidParam("empty PerRow centre".into()))?;
                if v.iter().any(|c| *c != first) {
                    return Err(Error::InvalidParam(
                        "the cuda projector pair takes one rotation centre; \
                         geom.center is Center::PerRow with differing values"
                            .into(),
                    ));
                }
                first
            }
        };
        Ok(PairGeom { phi, axis })
    }

    /// On-device forward projection `g = A f`: zero `g` (the scatter-add kernel
    /// accumulates) then launch with tilt `phi`. The projector requires a square
    /// grid = detector width, so `g` is `[nz,nproj,n]` and its byte size is
    /// derived (`nz*nproj*n*4`) rather than passed — the caller cannot desync it.
    ///
    /// # Safety
    /// `g`/`f`/`theta` must be valid device pointers sized for `[nz,nproj,n]` /
    /// `[nz,n,n]` / `[nproj]`.
    #[cfg(feature = "cuda")]
    unsafe fn dev_forward(
        g: *mut c_void,
        f: *const c_void,
        theta: *const f32,
        pg: PairGeom,
        nz: usize,
        n: usize,
        nproj: usize,
    ) -> Result<()> {
        let null = std::ptr::null_mut::<c_void>();
        let sbytes = nz * nproj * n * std::mem::size_of::<f32>();
        ck(
            ffi::tomoxide_cuda_memset_async(g, 0, sbytes, null),
            "memset",
        )?;
        ck(
            ffi::tomoxide_forwardproject(
                g,
                f,
                theta,
                pg.phi,
                pg.axis,
                0,         // sz: whole volume, no offset
                nz as i32, // ncz: recon height == detector rows (rh == nz here)
                nz as i32,
                n as i32,
                nz as i32, // rh == nz by the device-path design (see above)
                nproj as i32,
                null,
            ),
            "forwardproject",
        )
    }

    /// On-device back projection `f = Aᵀ g` (tilt `phi`) via a reused
    /// `cfunc_linerec` handle: zero `f` (the kernel accumulates) then launch.
    /// Gain 1 — the pure adjoint of [`dev_forward`], no angular-quadrature
    /// weight (that π/nproj belongs to the analytic FBP paths only). `vbytes` =
    /// byte size of `f`; `nz` = the volume height (== detector rows in the
    /// device path — rh == nz by design, mirroring [`dev_forward`]'s centring).
    ///
    /// # Safety
    /// `handle` from [`ffi::tomoxide_linerec_new`]; `f`/`g`/`theta` valid device
    /// pointers sized for `[nz,n,n]` / `[nz,nproj,n]` / `[nproj]`.
    #[cfg(feature = "cuda")]
    unsafe fn dev_backproject(
        handle: *mut c_void,
        f: *mut c_void,
        g: *const c_void,
        theta: *const f32,
        pg: PairGeom,
        nz: usize,
        vbytes: usize,
    ) -> Result<()> {
        let null = std::ptr::null_mut::<c_void>();
        ck(
            ffi::tomoxide_cuda_memset_async(f, 0, vbytes, null),
            "memset",
        )?;
        ck(
            ffi::tomoxide_linerec_backproject(
                handle, f, g, theta, pg.phi, pg.axis, 1.0, 0,
                nz as i32, // rh == nz by the device-path design
                null,
            ),
            "linerec backproject",
        )
    }

    /// Device-resident SIRT: upload `b`/θ/ones once, precompute the ray-length
    /// `R = 1/A(1)` and sensitivity `C = 1/Aᵀ(1)` weights on-device, then run every
    /// iteration `x ← x + C ∘ Aᵀ(R ∘ (b − A x))` entirely on the GPU, and download
    /// `x` once. Reuses the same `A`/`Aᵀ` kernels (and one back-projection handle)
    /// as the generic path, so the result matches the host SIRT to the atomic-add
    /// ordering floor.
    /// Initial device iterate for a device-resident solver: the warm-start `init`
    /// host volume (physical domain) scaled by `inv_scale` — `1.0` for the
    /// physical-domain solvers (SIRT/EM/OSPML), `1/r` for the r-scaled ones
    /// (GRAD/TIKH/TV) — else a constant-`default` volume. Single upload; mirrors
    /// the host [`crate::recon::init_volume`] seeding.
    #[cfg(feature = "cuda")]
    fn seed_buf(init: Option<&[f32]>, default: f32, len: usize, inv_scale: f32) -> Result<DevBuf> {
        let host: Vec<f32> = match init {
            Some(h) => h.iter().map(|v| v * inv_scale).collect(),
            None => vec![default; len],
        };
        DevBuf::from_host_f32(&host)
    }

    #[cfg(feature = "cuda")]
    fn sirt_device(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        init: Option<&[f32]>,
    ) -> Result<Volume<f32>> {
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, nproj, ncols) = (s.n_rows(), s.n_angles(), s.n_cols());
        let sino_std = s.array.as_standard_layout();
        let sino_slice = sino_std
            .as_slice()
            .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;
        let theta = &geom.angles.0;

        let (nvol, nsino) = (nz * n * n, nz * nproj * ncols);
        let (vbytes, sbytes) = (
            nvol * std::mem::size_of::<f32>(),
            nsino * std::mem::size_of::<f32>(),
        );
        let null = std::ptr::null_mut::<c_void>();

        let theta_d = DevBuf::from_host_f32(theta)?;
        let tp = theta_d.ptr as *const f32;
        let pg = pair_geom(geom)?;
        let b_d = DevBuf::from_host_f32(sino_slice)?;
        let ones_v = DevBuf::from_host_f32(&vec![1.0f32; nvol])?;
        let ones_s = DevBuf::from_host_f32(&vec![1.0f32; nsino])?;
        let vol_d = seed_buf(init, 0.0, nvol, 1.0)?; // x (init 0 or warm-start)
        let ax_d = DevBuf::zeroed(sbytes)?; // A x, reused as the weighted residual
        let corr_d = DevBuf::zeroed(vbytes)?; // Aᵀ(…)
        let rw_d = DevBuf::zeroed(sbytes)?; // R = 1/A(1)
        let cw_d = DevBuf::zeroed(vbytes)?; // C = 1/Aᵀ(1)

        let handle = Handle::new(
            unsafe { ffi::tomoxide_linerec_new(nproj, nz, ncols, nproj, nz) },
            ffi::tomoxide_linerec_free,
            "cfunc_linerec",
        )?;

        // All ops on the per-thread default stream (null) → FIFO-ordered, so one
        // sync before the download suffices.
        unsafe {
            dev_forward(ax_d.ptr, ones_v.ptr, tp, pg, nz, n, nproj)?; // A(1)
            ck(
                ffi::tomoxide_iter_recip_thresh(rw_d.ptr, ax_d.ptr, 1e-6, nsino, null),
                "iter_recip_thresh",
            )?; // R
            dev_backproject(handle.ptr, corr_d.ptr, ones_s.ptr, tp, pg, nz, vbytes)?; // Aᵀ(1)
            ck(
                ffi::tomoxide_iter_recip_thresh(cw_d.ptr, corr_d.ptr, 1e-6, nvol, null),
                "iter_recip_thresh",
            )?; // C
            for _ in 0..num_iter.max(1) {
                dev_forward(ax_d.ptr, vol_d.ptr, tp, pg, nz, n, nproj)?; // ax = A x
                ck(
                    ffi::tomoxide_iter_residual(ax_d.ptr, b_d.ptr, rw_d.ptr, nsino, null),
                    "iter_residual",
                )?; // (b−Ax)∘R
                dev_backproject(handle.ptr, corr_d.ptr, ax_d.ptr, tp, pg, nz, vbytes)?; // corr = Aᵀ(…)
                ck(
                    ffi::tomoxide_iter_update(vol_d.ptr, cw_d.ptr, corr_d.ptr, nvol, null),
                    "iter_update",
                )?;
                // x += C∘corr
            }
        }

        let rc = unsafe { ffi::tomoxide_cuda_sync() };
        drop(handle);
        if rc != 0 {
            return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
        }
        let mut host = vec![0.0f32; nvol];
        vol_d.to_host_f32(&mut host)?;
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    /// Multi-GPU angle-split SIRT for laminography — the same `A`/`Aᵀ` tilted
    /// projector pair as [`sirt_device`], but the projection angles are sharded
    /// across GPUs so the full-angle sinogram working set never has to fit one
    /// device. Each GPU `g` holds the **whole** volume `x` (`[nz, n, n]`) plus
    /// only its angle chunk of the sinogram (`bₘ`, ray weights `Rₘ`, forward
    /// scratch), which is why a tilted volume too large for a single 32 GB card
    /// (the sinogram is 3 full copies of `nz·nproj·ncols`) fits when the angles
    /// divide across 4.
    ///
    /// SIRT is `x ← x + C ∘ Aᵀ(R ∘ (b − A x))`. Sharded:
    /// * `A x` and `R ∘ (b − A x)` are per-ray, so each GPU computes its angle
    ///   chunk independently — no communication.
    /// * `Aᵀ(…)` is a sum over angles, so each GPU produces a **partial** volume
    ///   `Aᵀₘ(…)`; the full correction is `Σₘ Aᵀₘ`, an all-reduce of the
    ///   `[nz, n, n]` volume across GPUs each iteration (host tree-sum under the
    ///   barrier; the reduced volume is the only per-iteration cross-GPU
    ///   traffic).
    /// * `C = 1/Aᵀ(1)` is the same angle-sum sensitivity, reduced **once** before
    ///   the loop; `R = 1/A(1)` is per-ray and stays local.
    ///
    /// Every GPU applies the identical (globally reduced) update to its identical
    /// volume copy, so all copies stay bit-identical across iterations and only
    /// GPU 0's copy is downloaded. Bit-parity with `sirt_device` holds to the
    /// atomic-add floor plus the angle-partition sum reassociation (the partial
    /// backprojections sum in a different order than one device's single pass).
    #[cfg(feature = "cuda")]
    fn sirt_multigpu_lamino(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        init: Option<&[f32]>,
        devices: &[i32],
    ) -> Result<Volume<f32>> {
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, nproj, ncols) = (s.n_rows(), s.n_angles(), s.n_cols());
        let pg = pair_geom(geom)?;
        let theta = &geom.angles.0;
        let nvol = nz * n * n;
        let vbytes = nvol * std::mem::size_of::<f32>();
        let sino_std = s.array.as_standard_layout();
        let sino_slice = sino_std
            .as_slice()
            .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

        // Contiguous angle chunks, one per device (drop empty chunks when
        // nproj < devices so `g` is the real worker count).
        let bounds: Vec<(usize, usize, i32)> = devices
            .iter()
            .enumerate()
            .map(|(i, &dev)| {
                (
                    i * nproj / devices.len(),
                    (i + 1) * nproj / devices.len(),
                    dev,
                )
            })
            .filter(|&(a0, a1, _)| a1 > a0)
            .collect();
        let g = bounds.len();

        // Zero seed (or warm-start), broadcast identically to every GPU.
        let init_owned: Vec<f32>;
        let init_slice: &[f32] = match init {
            Some(v) => v,
            None => {
                init_owned = vec![0.0f32; nvol];
                &init_owned
            }
        };

        // Cross-GPU all-reduce scratch: one volume slot per worker (written by its
        // owner) and one shared `summed` volume. Worker 0 alone sums the slots
        // into `summed` between two barriers — the other workers wait, then read
        // `summed` concurrently. Summing on one worker (rayon-parallel over the
        // volume) is g× less arithmetic than every worker re-summing, and avoids
        // the host-memory-bandwidth thrash of g concurrent full-volume sweeps.
        let partials: Vec<std::sync::RwLock<Vec<f32>>> = (0..g)
            .map(|_| std::sync::RwLock::new(vec![0.0f32; nvol]))
            .collect();
        let summed: std::sync::RwLock<Vec<f32>> = std::sync::RwLock::new(vec![0.0f32; nvol]);
        let barrier = std::sync::Barrier::new(g);
        let result: Mutex<Option<Vec<f32>>> = Mutex::new(None);

        std::thread::scope(|scope| -> Result<()> {
            let handles: Vec<_> = bounds
                .iter()
                .copied()
                .enumerate()
                .map(|(gi, (a0, a1, dev))| {
                    let partials = &partials;
                    let summed = &summed;
                    let barrier = &barrier;
                    let result = &result;
                    scope.spawn(move || -> Result<()> {
                        ck(unsafe { ffi::tomoxide_cuda_set_device(dev) }, "set_device")?;
                        let len = a1 - a0;
                        let nsub = nz * len * ncols;
                        let sbytes = nsub * std::mem::size_of::<f32>();
                        let null = std::ptr::null_mut::<c_void>();

                        // All-reduce Σₘ of a `[nz,n,n]` partial across workers:
                        // each writes its slot, then worker 0 alone sums the slots
                        // into `summed` (rayon over the volume) while the others
                        // wait; on return every worker reads `summed`. Two barriers
                        // bracket worker 0's exclusive write.
                        let allreduce = |hc: Vec<f32>| {
                            *partials[gi].write().unwrap() = hc;
                            barrier.wait();
                            if gi == 0 {
                                let mut acc = vec![0.0f32; nvol];
                                for slot in partials.iter() {
                                    let p = slot.read().unwrap();
                                    acc.par_iter_mut()
                                        .zip(p.par_iter())
                                        .for_each(|(a, &b)| *a += b);
                                }
                                *summed.write().unwrap() = acc;
                            }
                            barrier.wait();
                        };

                        // This worker's angle chunk: contiguous θ and sinogram
                        // (gather the [z, a0..a1, :] band out of [nz, nproj, ncols]).
                        let theta_g: Vec<f32> = theta[a0..a1].to_vec();
                        let mut bslice = vec![0.0f32; nsub];
                        for z in 0..nz {
                            let src = &sino_slice
                                [z * nproj * ncols + a0 * ncols..z * nproj * ncols + a1 * ncols];
                            bslice[z * len * ncols..(z + 1) * len * ncols].copy_from_slice(src);
                        }

                        let theta_d = DevBuf::from_host_f32(&theta_g)?;
                        let tp = theta_d.ptr as *const f32;
                        let b_d = DevBuf::from_host_f32(&bslice)?;
                        let vol_d = DevBuf::from_host_f32(init_slice)?; // full volume copy
                        let ax_d = DevBuf::zeroed(sbytes)?; // A x / weighted residual
                        let rw_d = DevBuf::zeroed(sbytes)?; // R = 1/A(1) (local)
                        let corr_d = DevBuf::zeroed(vbytes)?; // Aᵀ(…) partial, then global
                        let cw_d = DevBuf::zeroed(vbytes)?; // C = 1/Aᵀ(1) (global)
                        let handle = Handle::new(
                            unsafe { ffi::tomoxide_linerec_new(len, nz, ncols, len, nz) },
                            ffi::tomoxide_linerec_free,
                            "cfunc_linerec",
                        )?;

                        // Ray weights R = 1/A(1) — local (each ray is on one GPU).
                        {
                            let ones_v = DevBuf::from_host_f32(&vec![1.0f32; nvol])?;
                            unsafe {
                                dev_forward(ax_d.ptr, ones_v.ptr, tp, pg, nz, n, len)?;
                                ck(
                                    ffi::tomoxide_iter_recip_thresh(
                                        rw_d.ptr, ax_d.ptr, 1e-6, nsub, null,
                                    ),
                                    "iter_recip_thresh",
                                )?;
                            }
                        }
                        // Partial sensitivity Aᵀₘ(1) → corr_d, then all-reduce → C.
                        {
                            let ones_s = DevBuf::from_host_f32(&vec![1.0f32; nsub])?;
                            unsafe {
                                dev_backproject(
                                    handle.ptr, corr_d.ptr, ones_s.ptr, tp, pg, nz, vbytes,
                                )?;
                                if ffi::tomoxide_cuda_sync() != 0 {
                                    return Err(Error::Backend("cuda sync failed".into()));
                                }
                            }
                        }
                        {
                            let mut hc = vec![0.0f32; nvol];
                            corr_d.to_host_f32(&mut hc)?;
                            allreduce(hc); // Σₘ Aᵀₘ(1) → summed
                        }
                        let cwh: Vec<f32> = summed
                            .read()
                            .unwrap()
                            .par_iter()
                            .map(|&v| if v.abs() > 1e-6 { 1.0 / v } else { 0.0 })
                            .collect();
                        cw_d.copy_from_host_f32(&cwh)?;

                        // SIRT iterations, volume resident, correction all-reduced.
                        for _ in 0..num_iter.max(1) {
                            unsafe {
                                dev_forward(ax_d.ptr, vol_d.ptr, tp, pg, nz, n, len)?; // A x
                                ck(
                                    ffi::tomoxide_iter_residual(
                                        ax_d.ptr, b_d.ptr, rw_d.ptr, nsub, null,
                                    ),
                                    "iter_residual",
                                )?; // (b−Ax)∘R
                                dev_backproject(
                                    handle.ptr, corr_d.ptr, ax_d.ptr, tp, pg, nz, vbytes,
                                )?; // Aᵀₘ(…)
                                if ffi::tomoxide_cuda_sync() != 0 {
                                    return Err(Error::Backend("cuda sync failed".into()));
                                }
                            }
                            {
                                let mut hc = vec![0.0f32; nvol];
                                corr_d.to_host_f32(&mut hc)?;
                                allreduce(hc); // Σₘ Aᵀₘ(…) → summed
                            }
                            corr_d.copy_from_host_f32(&summed.read().unwrap())?; // global correction back on device
                            unsafe {
                                ck(
                                    ffi::tomoxide_iter_update(
                                        vol_d.ptr, cw_d.ptr, corr_d.ptr, nvol, null,
                                    ),
                                    "iter_update",
                                )?; // x += C∘corr
                                if ffi::tomoxide_cuda_sync() != 0 {
                                    return Err(Error::Backend("cuda sync failed".into()));
                                }
                            }
                        }

                        // Every copy is identical; only GPU 0 downloads.
                        if gi == 0 {
                            let mut host = vec![0.0f32; nvol];
                            vol_d.to_host_f32(&mut host)?;
                            *result.lock().unwrap() = Some(host);
                        }
                        drop(handle);
                        Ok(())
                    })
                })
                .collect();
            for h in handles {
                h.join()
                    .unwrap_or_else(|_| Err(Error::Backend("cuda SIRT worker panicked".into())))?;
            }
            Ok(())
        })?;

        let host = result
            .into_inner()
            .unwrap()
            .ok_or_else(|| Error::Backend("multi-GPU SIRT produced no volume".into()))?;
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    /// One ordered subset held device-resident: its angles (θ), gathered
    /// measured sinogram `bₛ`, iteration-invariant sensitivity `Aₛᵀ(1)`, a reused
    /// `cfunc_linerec` handle, and a scratch `Aₛ x` buffer. `len` = subset angles.
    #[cfg(feature = "cuda")]
    struct DevSubset {
        theta_d: DevBuf,
        b_d: DevBuf,
        sens_d: DevBuf,
        ax_d: DevBuf,
        handle: Handle,
        len: usize,
    }

    /// Build every ordered subset device-resident: for each subset gather its θ
    /// and measured sinogram `bₛ` (uploaded once), precompute the sensitivity
    /// `Aₛᵀ(1)` on-device, and create a reused `cfunc_linerec` handle (freed by
    /// its [`Handle`]). Shared by [`em_device`] and [`ospml_device`].
    #[cfg(feature = "cuda")]
    fn build_dev_subsets(
        s: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        subsets_idx: Vec<Vec<usize>>,
    ) -> Result<Vec<DevSubset>> {
        let (nz, ncols) = (s.n_rows(), s.n_cols());
        let pg = pair_geom(geom)?;
        let vbytes = nz * n * n * std::mem::size_of::<f32>();
        let mut subs: Vec<DevSubset> = Vec::with_capacity(subsets_idx.len());
        for idx in subsets_idx {
            let len = idx.len();
            let theta_sub: Vec<f32> = idx.iter().map(|&p| geom.angles.0[p]).collect();
            let theta_d = DevBuf::from_host_f32(&theta_sub)?;
            let sub_b = s.array.select(ndarray::Axis(1), &idx); // [nz, len, ncols], strided
            let sub_b_std = sub_b.as_standard_layout();
            let b_d =
                DevBuf::from_host_f32(sub_b_std.as_slice().ok_or_else(|| {
                    Error::InvalidParam("non-contiguous subset sinogram".into())
                })?)?;
            let sbytes = nz * len * ncols * std::mem::size_of::<f32>();
            let handle = Handle::new(
                unsafe { ffi::tomoxide_linerec_new(len, nz, ncols, len, nz) },
                ffi::tomoxide_linerec_free,
                "cfunc_linerec",
            )?;
            let ones_s = DevBuf::from_host_f32(&vec![1.0f32; nz * len * ncols])?;
            let sens_d = DevBuf::zeroed(vbytes)?;
            unsafe {
                dev_backproject(
                    handle.ptr,
                    sens_d.ptr,
                    ones_s.ptr,
                    theta_d.ptr as *const f32,
                    pg,
                    nz,
                    vbytes,
                )?
            };
            subs.push(DevSubset {
                theta_d,
                b_d,
                sens_d,
                ax_d: DevBuf::zeroed(sbytes)?,
                handle,
                len,
            });
        }
        Ok(subs)
    }

    /// Device-resident MLEM / OSEM. Uploads each ordered subset's θ / `bₛ` once and
    /// precomputes `Aₛᵀ(1)` on-device, then runs every subset update
    /// `x ← x ∘ Aₛᵀ(bₛ ⊘ Aₛ x) ⊘ Aₛᵀ(1)` on the GPU, downloading `x` once. MLEM is
    /// the single-subset case (all angles, identity order) — the caller passes the
    /// subset partition ([`crate::recon::ordered_subsets`], shared with the host
    /// solver so the two agree). Reuses the same `A`/`Aᵀ` kernels as the generic
    /// path ⇒ matches the host EM output to the atomic-add floor.
    #[cfg(feature = "cuda")]
    fn em_device(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        subsets_idx: Vec<Vec<usize>>,
        init: Option<&[f32]>,
    ) -> Result<Volume<f32>> {
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, ncols) = (s.n_rows(), s.n_cols());
        let pg = pair_geom(geom)?;
        let nvol = nz * n * n;
        let vbytes = nvol * std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();

        let subs = build_dev_subsets(&s, geom, n, subsets_idx)?;
        let vol_d = seed_buf(init, 1.0, nvol, 1.0)?; // positive init (or warm-start)
        let corr_d = DevBuf::zeroed(vbytes)?;
        unsafe {
            for _ in 0..num_iter.max(1) {
                for sub in &subs {
                    let tp = sub.theta_d.ptr as *const f32;
                    let nsub = nz * sub.len * ncols;
                    dev_forward(sub.ax_d.ptr, vol_d.ptr, tp, pg, nz, n, sub.len)?; // Aₛ x
                    ck(
                        ffi::tomoxide_iter_em_ratio(sub.ax_d.ptr, sub.b_d.ptr, nsub, null),
                        "iter_em_ratio",
                    )?; // bₛ ⊘ Aₛ x
                    dev_backproject(sub.handle.ptr, corr_d.ptr, sub.ax_d.ptr, tp, pg, nz, vbytes)?; // Aₛᵀ(…)
                    ck(
                        ffi::tomoxide_iter_em_update(
                            vol_d.ptr,
                            corr_d.ptr,
                            sub.sens_d.ptr,
                            nvol,
                            null,
                        ),
                        "iter_em_update",
                    )?;
                    // x ∘ corr ⊘ sens
                }
            }
        }

        let rc = unsafe { ffi::tomoxide_cuda_sync() };
        if rc != 0 {
            return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
        }
        let mut host = vec![0.0f32; nvol];
        vol_d.to_host_f32(&mut host)?; // subset handles freed when `subs` drops after this
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    /// Device-resident OSPML / PML (quadratic or hybrid prior). OSEM's subset EM
    /// correction `Aₛᵀ(bₛ ⊘ Aₛ x)` on-device, followed by the De Pierro penalized
    /// pixel update (`iter_pml_update`, an 8-neighbour quadratic solved per pixel
    /// against the pre-update snapshot `old`). PML is the single-subset case; the
    /// hybrid prior passes `delta = Some(edge threshold)`, the quadratic `None`.
    /// `reg` is `reg_par[0]` (0 ⇒ reduces to OSEM). Mirrors the host `ospml`.
    #[cfg(feature = "cuda")]
    fn ospml_device(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        // Penalty config: strength `reg_par[0]` and the hybrid edge threshold
        // (`Some` ⇒ hybrid prior, `None` ⇒ quadratic).
        prior: (f32, Option<f32>),
        subsets_idx: Vec<Vec<usize>>,
        init: Option<&[f32]>,
    ) -> Result<Volume<f32>> {
        let (reg, delta) = prior;
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, ncols) = (s.n_rows(), s.n_cols());
        let pg = pair_geom(geom)?;
        let nvol = nz * n * n;
        let vbytes = nvol * std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let (has_delta, delta_v) = match delta {
            Some(d) => (1i32, d),
            None => (0i32, 0.0f32),
        };

        let subs = build_dev_subsets(&s, geom, n, subsets_idx)?;
        let vol_d = seed_buf(init, 1.0, nvol, 1.0)?; // positive init (or warm-start)
        let old_d = DevBuf::zeroed(vbytes)?; // pre-update snapshot for the stencil
        let corr_d = DevBuf::zeroed(vbytes)?;
        unsafe {
            for _ in 0..num_iter.max(1) {
                for sub in &subs {
                    let tp = sub.theta_d.ptr as *const f32;
                    let nsub = nz * sub.len * ncols;
                    dev_forward(sub.ax_d.ptr, vol_d.ptr, tp, pg, nz, n, sub.len)?; // Aₛ x
                    ck(
                        ffi::tomoxide_iter_em_ratio(sub.ax_d.ptr, sub.b_d.ptr, nsub, null),
                        "iter_em_ratio",
                    )?; // bₛ ⊘ Aₛ x
                    dev_backproject(sub.handle.ptr, corr_d.ptr, sub.ax_d.ptr, tp, pg, nz, vbytes)?; // Aₛᵀ(…)
                    ck(
                        ffi::tomoxide_cuda_memcpy_d2d_async(old_d.ptr, vol_d.ptr, vbytes, null),
                        "memcpy_d2d_async",
                    )?; // snapshot
                    ck(
                        ffi::tomoxide_iter_pml_update(
                            vol_d.ptr,
                            old_d.ptr,
                            corr_d.ptr,
                            sub.sens_d.ptr,
                            reg,
                            delta_v,
                            has_delta,
                            n,
                            nz,
                            null,
                        ),
                        "iter_pml_update",
                    )?;
                }
            }
        }

        let rc = unsafe { ffi::tomoxide_cuda_sync() };
        if rc != 0 {
            return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
        }
        let mut host = vec![0.0f32; nvol];
        vol_d.to_host_f32(&mut host)?;
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    /// Device-resident least-squares gradient descent (`grad`) and its Tikhonov
    /// variant (`tikh`). The iterate lives on the GPU in the r-scaled domain
    /// (init 0); each iteration computes `grad = 2r·Rᵀ(r·R x − b)` (+ the
    /// Tikhonov term `2·reg1·(x − prior)` when `tikh` is `Some`), a per-slice step
    /// `λ` (fixed if `reg_par[0] ≥ 0`, else Barzilai–Borwein via on-device
    /// reductions), and `x ← x − λ g`, then unscales by `r`. `recon0`/`grad0`
    /// (previous iterate/gradient, needed for BB) are kept device-resident and
    /// refreshed with D2D copies. Mirrors the host `gradient_descent` op-for-op.
    #[cfg(feature = "cuda")]
    fn grad_device(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        reg_par: &[f32],
        tikh: Option<(f32, Vec<f32>)>,
        init: Option<&[f32]>,
    ) -> Result<Volume<f32>> {
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, nproj, ncols) = (s.n_rows(), s.n_angles(), s.n_cols());
        let sino_std = s.array.as_standard_layout();
        let sino_slice = sino_std
            .as_slice()
            .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;
        let theta = &geom.angles.0;

        let (nvol, nsino) = (nz * n * n, nz * nproj * ncols);
        let (vbytes, sbytes) = (
            nvol * std::mem::size_of::<f32>(),
            nsino * std::mem::size_of::<f32>(),
        );
        let zbytes = nz * std::mem::size_of::<f32>();
        let slice_len = n * n;
        let null = std::ptr::null_mut::<c_void>();

        let r = 1.0 / ((ncols * nproj) as f32 / 2.0).sqrt();
        let coef = 2.0 * r; // grad = 2r·Rᵀ(r·R x − b), {R, Rᵀ} the unweighted pair
        let fixed_step = reg_par.first().copied().unwrap_or(1.0);
        let two_reg1 = tikh.as_ref().map(|(r1, _)| 2.0 * r1).unwrap_or(0.0);

        let theta_d = DevBuf::from_host_f32(theta)?;
        let tp = theta_d.ptr as *const f32;
        let pg = pair_geom(geom)?;
        let b_d = DevBuf::from_host_f32(sino_slice)?;
        let vol_d = seed_buf(init, 0.0, nvol, 1.0 / r)?; // x, r-scaled (init 0 or warm-start/r)
        let recon0_d = DevBuf::zeroed(vbytes)?; // previous x (BB)
        let grad0_d = DevBuf::zeroed(vbytes)?; // previous grad (BB)
        let grad_d = DevBuf::zeroed(vbytes)?;
        let ax_d = DevBuf::zeroed(sbytes)?;
        let bpv_d = DevBuf::zeroed(vbytes)?;
        let lambda_d = DevBuf::zeroed(zbytes)?;
        let num_d = DevBuf::zeroed(zbytes)?;
        let den_d = DevBuf::zeroed(zbytes)?;
        let prior_d = match &tikh {
            Some((_, p)) => Some(DevBuf::from_host_f32(p)?),
            None => None,
        };

        let handle = Handle::new(
            unsafe { ffi::tomoxide_linerec_new(nproj, nz, ncols, nproj, nz) },
            ffi::tomoxide_linerec_free,
            "cfunc_linerec",
        )?;

        unsafe {
            for it in 0..num_iter.max(1) {
                dev_forward(ax_d.ptr, vol_d.ptr, tp, pg, nz, n, nproj)?; // ax = R x
                ck(
                    ffi::tomoxide_iter_grad_prox(ax_d.ptr, b_d.ptr, r, nsino, null),
                    "iter_grad_prox",
                )?; // r·R x − b
                dev_backproject(handle.ptr, bpv_d.ptr, ax_d.ptr, tp, pg, nz, vbytes)?; // Rᵀ(…)
                ck(
                    ffi::tomoxide_iter_grad_assemble(grad_d.ptr, bpv_d.ptr, coef, nvol, null),
                    "iter_grad_assemble",
                )?; // 2r·Rᵀ
                if let Some(pd) = &prior_d {
                    ck(
                        ffi::tomoxide_iter_grad_tikh(
                            grad_d.ptr, vol_d.ptr, pd.ptr, two_reg1, nvol, null,
                        ),
                        "iter_grad_tikh",
                    )?;
                }
                // Step size from the previous iterate/gradient, then save them.
                ck(
                    ffi::tomoxide_iter_bb_reduce(
                        num_d.ptr,
                        den_d.ptr,
                        vol_d.ptr,
                        recon0_d.ptr,
                        grad_d.ptr,
                        grad0_d.ptr,
                        slice_len,
                        nz,
                        null,
                    ),
                    "iter_bb_reduce",
                )?;
                ck(
                    ffi::tomoxide_iter_bb_lambda(
                        lambda_d.ptr,
                        num_d.ptr,
                        den_d.ptr,
                        fixed_step,
                        i32::from(it == 0),
                        nz,
                        null,
                    ),
                    "iter_bb_lambda",
                )?;
                ck(
                    ffi::tomoxide_cuda_memcpy_d2d_async(recon0_d.ptr, vol_d.ptr, vbytes, null),
                    "memcpy_d2d_async",
                )?;
                ck(
                    ffi::tomoxide_cuda_memcpy_d2d_async(grad0_d.ptr, grad_d.ptr, vbytes, null),
                    "memcpy_d2d_async",
                )?;
                ck(
                    ffi::tomoxide_iter_axpy_neg_slice(
                        vol_d.ptr,
                        grad_d.ptr,
                        lambda_d.ptr,
                        slice_len,
                        nvol,
                        null,
                    ),
                    "iter_axpy_neg_slice",
                )?; // x ← x − λ g
            }
            ck(
                ffi::tomoxide_iter_scale_inplace(vol_d.ptr, r, nvol, null),
                "iter_scale_inplace",
            )?; // back to physical domain
        }

        let rc = unsafe { ffi::tomoxide_cuda_sync() };
        drop(handle);
        if rc != 0 {
            return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
        }
        let mut host = vec![0.0f32; nvol];
        vol_d.to_host_f32(&mut host)?;
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    /// Device-resident Conjugate-Gradient Least Squares (`cgls`). The iterate
    /// `x`, the sinogram residual `r`, the search direction `p`, the gradient
    /// `z = Aᵀr`, and the scratch `w = Ap` all stay on the GPU across every
    /// iteration — one upload (b, θ, optional seed), one download (x). Mirrors
    /// the host [`crate::recon::cgls`] op-for-op with per-slice scalars
    /// (`gamma`/`wdot`/`alpha`/`beta` are device `[nz]`): each z-slice is an
    /// independent 2-D problem, so no dot product couples slices.
    ///
    /// The `x += alpha·p` and `r −= alpha·w` updates reuse the per-slice
    /// `iter_axpy_neg_slice` kernel (x with `−alpha`, r with `+alpha`); CGLS is
    /// self-scaling, so no r-domain rescaling is applied (unlike grad/tv).
    #[cfg(feature = "cuda")]
    fn cgls_device(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        init: Option<&[f32]>,
    ) -> Result<Volume<f32>> {
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, nproj, ncols) = (s.n_rows(), s.n_angles(), s.n_cols());
        let sino_std = s.array.as_standard_layout();
        let sino_slice = sino_std
            .as_slice()
            .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;
        let theta = &geom.angles.0;

        let (nvol, nsino) = (nz * n * n, nz * nproj * ncols);
        let sz = std::mem::size_of::<f32>();
        let (vbytes, sbytes, zbytes) = (nvol * sz, nsino * sz, nz * sz);
        let vslice = n * n; // volume slice length
        let sslice = nproj * ncols; // sinogram slice length
        let null = std::ptr::null_mut::<c_void>();

        let theta_d = DevBuf::from_host_f32(theta)?;
        let tp = theta_d.ptr as *const f32;
        let pg = pair_geom(geom)?;
        let b_d = DevBuf::from_host_f32(sino_slice)?;
        let ones_s = DevBuf::from_host_f32(&vec![1.0f32; nsino])?; // r = (b − A x0)·1

        let vol_d = seed_buf(init, 0.0, nvol, 1.0)?; // x = x0 (0 or warm-start)
        let r_d = DevBuf::zeroed(sbytes)?; // residual b − A x (sinogram)
        let w_d = DevBuf::zeroed(sbytes)?; // A p (sinogram)
        let z_d = DevBuf::zeroed(vbytes)?; // Aᵀ r (volume)
        let p_d = DevBuf::zeroed(vbytes)?; // search direction (volume)
        let gamma_d = DevBuf::zeroed(zbytes)?; // ⟨z,z⟩, advanced each iter
        let gnew_d = DevBuf::zeroed(zbytes)?; // new ⟨z,z⟩
        let wdot_d = DevBuf::zeroed(zbytes)?; // ⟨w,w⟩
        let alpha_d = DevBuf::zeroed(zbytes)?;
        let neg_alpha_d = DevBuf::zeroed(zbytes)?;
        let beta_d = DevBuf::zeroed(zbytes)?;

        let handle = Handle::new(
            unsafe { ffi::tomoxide_linerec_new(nproj, nz, ncols, nproj, nz) },
            ffi::tomoxide_linerec_free,
            "cfunc_linerec",
        )?;

        unsafe {
            // Init: r = b − A x0 ; z = Aᵀ r ; p = z ; gamma = ⟨z,z⟩ per slice.
            dev_forward(r_d.ptr, vol_d.ptr, tp, pg, nz, n, nproj)?; // r = A x0
            ck(
                ffi::tomoxide_iter_residual(r_d.ptr, b_d.ptr, ones_s.ptr, nsino, null),
                "iter_residual",
            )?; // r = b − A x0
            dev_backproject(handle.ptr, z_d.ptr, r_d.ptr, tp, pg, nz, vbytes)?; // z = Aᵀ r
            ck(
                ffi::tomoxide_cuda_memcpy_d2d_async(p_d.ptr, z_d.ptr, vbytes, null),
                "memcpy_d2d_async",
            )?; // p = z
            ck(
                ffi::tomoxide_iter_slice_dot(gamma_d.ptr, z_d.ptr, z_d.ptr, vslice, nz, null),
                "iter_slice_dot",
            )?;

            for _ in 0..num_iter.max(1) {
                dev_forward(w_d.ptr, p_d.ptr, tp, pg, nz, n, nproj)?; // w = A p
                ck(
                    ffi::tomoxide_iter_slice_dot(wdot_d.ptr, w_d.ptr, w_d.ptr, sslice, nz, null),
                    "iter_slice_dot",
                )?;
                ck(
                    ffi::tomoxide_iter_cgls_alpha(
                        alpha_d.ptr,
                        neg_alpha_d.ptr,
                        gamma_d.ptr,
                        wdot_d.ptr,
                        nz,
                        null,
                    ),
                    "iter_cgls_alpha",
                )?;
                // x += alpha·p  (x −= (−alpha)·p) ;  r −= alpha·w.
                ck(
                    ffi::tomoxide_iter_axpy_neg_slice(
                        vol_d.ptr,
                        p_d.ptr,
                        neg_alpha_d.ptr,
                        vslice,
                        nvol,
                        null,
                    ),
                    "iter_axpy_neg_slice",
                )?;
                ck(
                    ffi::tomoxide_iter_axpy_neg_slice(
                        r_d.ptr,
                        w_d.ptr,
                        alpha_d.ptr,
                        sslice,
                        nsino,
                        null,
                    ),
                    "iter_axpy_neg_slice",
                )?;
                dev_backproject(handle.ptr, z_d.ptr, r_d.ptr, tp, pg, nz, vbytes)?; // z = Aᵀ r
                ck(
                    ffi::tomoxide_iter_slice_dot(gnew_d.ptr, z_d.ptr, z_d.ptr, vslice, nz, null),
                    "iter_slice_dot",
                )?;
                ck(
                    ffi::tomoxide_iter_cgls_beta(beta_d.ptr, gamma_d.ptr, gnew_d.ptr, nz, null),
                    "iter_cgls_beta",
                )?;
                ck(
                    ffi::tomoxide_iter_xpby_slice(p_d.ptr, z_d.ptr, beta_d.ptr, vslice, nvol, null),
                    "iter_xpby_slice",
                )?;
                // p = z + beta·p
            }
        }

        let rc = unsafe { ffi::tomoxide_cuda_sync() };
        drop(handle);
        if rc != 0 {
            return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
        }
        let mut host = vec![0.0f32; nvol];
        vol_d.to_host_f32(&mut host)?;
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    /// Device-resident total variation (`tv`, Chambolle–Pock primal–dual). The
    /// r-scaled iterate (`x`, extrapolated primal `xbar`), the TV dual fields
    /// (`p0x`/`p0y`), and the data dual (`pd`) all stay on the GPU across
    /// iterations. Each iteration: forward `R xbar`, the data dual proximal, the
    /// back-projection `Rᵀ(pd)`, the TV dual ascent + λ-ball projection, and the
    /// primal step with over-relaxation — then unscale by r. Mirrors the host
    /// `tv` op-for-op (same fixed step `C = 0.35`).
    #[cfg(feature = "cuda")]
    fn tv_device(
        sino: &Tomo<f32>,
        geom: &Geometry,
        n: usize,
        num_iter: usize,
        lambda: f32,
        init: Option<&[f32]>,
    ) -> Result<Volume<f32>> {
        const C: f32 = 0.35; // tomopy's fixed primal–dual step
        let s = sino.as_layout(Layout::Sinogram);
        let (nz, nproj, ncols) = (s.n_rows(), s.n_angles(), s.n_cols());
        let sino_std = s.array.as_standard_layout();
        let sino_slice = sino_std
            .as_slice()
            .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;
        let theta = &geom.angles.0;

        let (nvol, nsino) = (nz * n * n, nz * nproj * ncols);
        let (vbytes, sbytes) = (
            nvol * std::mem::size_of::<f32>(),
            nsino * std::mem::size_of::<f32>(),
        );
        let null = std::ptr::null_mut::<c_void>();
        let r = 1.0 / ((ncols * nproj) as f32 / 2.0).sqrt();

        let theta_d = DevBuf::from_host_f32(theta)?;
        let tp = theta_d.ptr as *const f32;
        let pg = pair_geom(geom)?;
        let b_d = DevBuf::from_host_f32(sino_slice)?;
        // Both the extrapolated and the primal iterate start from the seed / r
        // (r-scaled domain); a `None` init is the plain zero start.
        let xbar_d = seed_buf(init, 0.0, nvol, 1.0 / r)?; // extrapolated primal (recon)
        let x_d = seed_buf(init, 0.0, nvol, 1.0 / r)?; // primal iterate
        let p0x_d = DevBuf::zeroed(vbytes)?; // TV dual, x-gradient
        let p0y_d = DevBuf::zeroed(vbytes)?; // TV dual, y-gradient
        let pd_d = DevBuf::zeroed(sbytes)?; // data dual (persists across iters)
        let ax_d = DevBuf::zeroed(sbytes)?;
        let bpv_d = DevBuf::zeroed(vbytes)?;

        let handle = Handle::new(
            unsafe { ffi::tomoxide_linerec_new(nproj, nz, ncols, nproj, nz) },
            ffi::tomoxide_linerec_free,
            "cfunc_linerec",
        )?;

        unsafe {
            for _ in 0..num_iter.max(1) {
                dev_forward(ax_d.ptr, xbar_d.ptr, tp, pg, nz, n, nproj)?; // R x̄
                ck(
                    ffi::tomoxide_iter_tv_datadual(pd_d.ptr, ax_d.ptr, b_d.ptr, C, r, nsino, null),
                    "iter_tv_datadual",
                )?;
                dev_backproject(handle.ptr, bpv_d.ptr, pd_d.ptr, tp, pg, nz, vbytes)?; // Rᵀ(pd)
                ck(
                    ffi::tomoxide_iter_tv_dual(
                        p0x_d.ptr, p0y_d.ptr, xbar_d.ptr, C, lambda, n, nz, null,
                    ),
                    "iter_tv_dual",
                )?;
                ck(
                    ffi::tomoxide_iter_tv_primal(
                        x_d.ptr, xbar_d.ptr, bpv_d.ptr, p0x_d.ptr, p0y_d.ptr, C, r, n, nz, null,
                    ),
                    "iter_tv_primal",
                )?;
            }
            ck(
                ffi::tomoxide_iter_scale_inplace(xbar_d.ptr, r, nvol, null),
                "iter_scale_inplace",
            )?; // back to physical domain
        }

        let rc = unsafe { ffi::tomoxide_cuda_sync() };
        drop(handle);
        if rc != 0 {
            return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
        }
        let mut host = vec![0.0f32; nvol];
        xbar_d.to_host_f32(&mut host)?;
        let array = Array3::from_shape_vec((nz, n, n), host)
            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?;
        Ok(Volume::new(array))
    }

    impl IterativeReconstruct for CudaBackend {
        /// Device-resident iterative reconstruction — the volume/sinogram stay on
        /// the GPU across all iterations (no per-iteration host↔device transfer).
        /// Implemented for SIRT (`sirt_device`), MLEM/OSEM (`em_device`),
        /// OSPML/PML (`ospml_device`), GRAD/TIKH (`grad_device`), and TV
        /// (`tv_device`); every other algorithm returns `Ok(None)` → generic
        /// host fallback (ART/BART are dispatched earlier, by ray projector).
        /// Serves parallel beam and laminography (`pair_geom` threads the tilt
        /// into the projector pair; recon-height = detector rows); falls back for
        /// the tilt-invalid per-slice solvers (CGLS/GRAD/TIKH on laminography) or
        /// a non-square grid (the kernels assume detector width = grid `n`).
        /// Reuses the same `A`/`Aᵀ` kernels as
        /// the generic solvers, so results match the host to the atomic-add floor
        /// (since the orientation/scale unification the CUDA projectors share the
        /// CPU handedness — no volume-space y-flip; the projector pair is the
        /// unweighted `{Wᵀ, W}`, so every solver converges to the physical μ).
        fn solve(
            &self,
            sino: &Tomo<f32>,
            geom: &Geometry,
            algorithm: crate::params::Algorithm,
            params: &crate::params::ReconParams,
        ) -> Result<Option<Volume<f32>>> {
            use crate::params::Algorithm;
            // The device-resident path serves both parallel beam and
            // laminography (the tilt is threaded into dev_forward/dev_backproject
            // via `pair_geom`; the recon-height equals the detector-row count, so
            // the volume/sinogram buffers are sized exactly as the parallel case
            // and stay resident across every iteration). For a tilted axis the
            // per-slice-step solvers (CGLS/GRAD/TIKH) are invalid — their scalar
            // step assumes parallel-beam slice-separability — so return `None`
            // and let the generic host path raise the explicit rejection.
            match geom.beam {
                Beam::Parallel => {}
                Beam::Laminography { .. } => {
                    if matches!(
                        algorithm,
                        Algorithm::Cgls | Algorithm::Grad | Algorithm::Tikh
                    ) {
                        return Ok(None);
                    }
                }
                // Cone beam has no device-resident projector here — defer to the
                // generic host path (preserves the prior non-parallel fallback).
                Beam::Cone { .. } => return Ok(None),
            }
            let s = sino.as_layout(Layout::Sinogram);
            let (nz, nproj, ncols) = (s.n_rows(), s.n_angles(), s.n_cols());
            let n = params.num_gridx.unwrap_or(ncols);
            if n != ncols || geom.angles.0.len() != nproj {
                return Ok(None); // square-grid + matching θ only
            }
            let it = params.num_iter;
            // Warm-start seed (physical domain, `[nz, n, n]`), uploaded once by
            // each device solver; the r-scaled solvers rescale it themselves.
            let init_host: Option<Vec<f32>> = match &params.init {
                Some(v) => {
                    if v.dims() != (nz, n, n) {
                        return Err(Error::ShapeMismatch {
                            expected: format!("init volume [{nz}, {n}, {n}]"),
                            found: format!("{:?}", v.dims()),
                        });
                    }
                    let std = v.array.as_standard_layout();
                    Some(
                        std.as_slice()
                            .ok_or_else(|| Error::InvalidParam("non-contiguous init".into()))?
                            .to_vec(),
                    )
                }
                None => None,
            };
            // Multi-GPU angle-split for laminography SIRT: the full-angle working
            // set (measured sinogram + ray weights + forward scratch = 3 full
            // `nz·nproj·ncols` copies) overflows a single 32 GB GPU for large
            // tilted volumes. Shard the angles across the selected GPUs, keeping
            // the whole volume resident on each and all-reducing the correction
            // volume per iteration. A single selected GPU (or a small problem that
            // fits) falls through to `sirt_device` below.
            if matches!(geom.beam, Beam::Laminography { .. })
                && algorithm == Algorithm::Sirt
                && nz > 1
            {
                let devices = selected_devices();
                if devices.len() > 1 {
                    return sirt_multigpu_lamino(sino, geom, n, it, init_host.as_deref(), &devices)
                        .map(Some);
                }
            }
            // Batch-domain minimum, same family as the analytic paths: the
            // z-bilinear forward/back-projection kernel pair samples slice
            // pairs (vr, vr+1), so a 1-slice problem forward-projects to zero
            // and never converges. Duplicate the slice into a 2-slice problem
            // — identical neighbouring rows make the z-interpolation exact
            // (the weights sum to 1) and the duplicated blocks are independent
            // copies of the same problem, so every solver's iterates (incl.
            // the global dot products of GRAD/TIKH/CGLS: numerator and
            // denominator both double) match the single-slice solve — and
            // drop the duplicate row from the output.
            let padded = nz == 1;
            let sino2: Tomo<f32>;
            let sino: &Tomo<f32> = if padded {
                let a = ndarray::concatenate(ndarray::Axis(0), &[s.array.view(), s.array.view()])
                    .map_err(|e| Error::InvalidParam(format!("pad 1-slice sinogram: {e}")))?;
                sino2 = Tomo::new(a, Layout::Sinogram);
                &sino2
            } else {
                sino
            };
            let init_host = init_host.map(|mut v| {
                if padded {
                    v.extend_from_within(..);
                }
                v
            });
            let init = init_host.as_deref();
            let solved = match algorithm {
                Algorithm::Sirt => sirt_device(sino, geom, n, it, init).map(Some),
                Algorithm::Mlem => {
                    em_device(sino, geom, n, it, vec![(0..nproj).collect()], init).map(Some)
                }
                Algorithm::Osem => {
                    let subsets = crate::recon::ordered_subsets(nproj, params);
                    em_device(sino, geom, n, it, subsets, init).map(Some)
                }
                // pml_* are ospml_* with a single block; the hybrid prior uses
                // reg_par[1] as the edge threshold (absent ⇒ quadratic prior).
                Algorithm::OspmlQuad
                | Algorithm::PmlQuad
                | Algorithm::OspmlHybrid
                | Algorithm::PmlHybrid => {
                    let reg = params.reg_par.first().copied().unwrap_or(0.0);
                    let (block_count, delta) = match algorithm {
                        Algorithm::OspmlQuad => (params.num_block, None),
                        Algorithm::PmlQuad => (1, None),
                        Algorithm::OspmlHybrid => {
                            (params.num_block, params.reg_par.get(1).copied())
                        }
                        _ => (1, params.reg_par.get(1).copied()), // PmlHybrid
                    };
                    let block_params = crate::params::ReconParams {
                        num_block: block_count,
                        ..params.clone()
                    };
                    let subsets = crate::recon::ordered_subsets(nproj, &block_params);
                    ospml_device(sino, geom, n, it, (reg, delta), subsets, init).map(Some)
                }
                Algorithm::Grad => {
                    grad_device(sino, geom, n, it, &params.reg_par, None, init).map(Some)
                }
                Algorithm::Tikh => {
                    // Tikhonov prior: reg_data ([nz,n,n] flat) or zeros. Wrong-sized
                    // reg_data ⇒ fall back so the host raises the shape error.
                    let reg1 = params.reg_par.get(1).copied().unwrap_or(0.0);
                    let mut prior = if params.reg_data.is_empty() {
                        vec![0.0f32; nz * n * n]
                    } else if params.reg_data.len() == nz * n * n {
                        params.reg_data.clone()
                    } else {
                        return Ok(None);
                    };
                    if padded {
                        prior.extend_from_within(..);
                    }
                    grad_device(
                        sino,
                        geom,
                        n,
                        it,
                        &params.reg_par,
                        Some((reg1, prior)),
                        init,
                    )
                    .map(Some)
                }
                Algorithm::Tv => {
                    let lambda = params.reg_par.first().copied().unwrap_or(1.0);
                    tv_device(sino, geom, n, it, lambda, init).map(Some)
                }
                Algorithm::Cgls => cgls_device(sino, geom, n, it, init).map(Some),
                _ => Ok(None),
            };
            match solved {
                Ok(Some(v)) if padded => Ok(Some(Volume::new(v.array.slice_move(ndarray::s![
                    0..1,
                    ..,
                    ..
                ])))),
                other => other,
            }
        }
    }

    /// Complex FBP weight `w[z, k] = ramp[k]·exp(-2πi·k·δ_z/pad)/pad`, for
    /// `k in 0..ne/2+1`, `δ_z = ncols/2 − center(z)` (half spectrum ⇒ `f_k = k ≥
    /// 0`), interleaved re/im — folds the ramp, signed-frequency centre-shift
    /// phase, and the `1/pad` cuFFT-inverse normalization.
    ///
    /// The filter gain is `1/pad` (CPU/tomopy convention). It was tomocupy's
    /// `½/pad`: that extra `½` halved the CUDA analytic amplitude to match tomocupy
    /// (tomoxide's CUDA output measured exactly 2.000× tomopy, hidden by the scale-
    /// invariant Pearson parity), but the cross-backend convention unification
    /// (Phase 2) targets CPU/tomopy — whose filter carries no such ½ — so it was
    /// dropped. The gain lives only here, so this single site sets the filter scale
    /// for every CUDA analytic method (fbp/linerec/fourierrec f32 + f16, one-shot +
    /// streaming). fbp/linerec additionally need the `π/nproj` dθ weight the
    /// analytic call sites pass to `cfunc_linerec` (was tomocupy's baked-in
    /// `4/nproj`) to reach CPU scale; fourierrec
    /// additionally normalizes its unnormalized cuFFT inverse by `(2n)²`. The
    /// laminography path also reads this filter but is a *different algorithm* from
    /// CPU USFFT lamino and is excluded from the unification (its cuda/cpu scale +
    /// sign difference is documented, not unified). The residual ~1.6% on the
    /// unified paths is the `make_fbp_filter` `_wint` quadrature ramp SHAPE (vs the
    /// CPU linear ramp), not scale.
    fn build_filter_w(
        filter: &[f32],
        geom: &Geometry,
        nz: usize,
        ncols: usize,
        pad: usize,
    ) -> Vec<f32> {
        let nfreq = pad / 2 + 1;
        let half = ncols as f32 / 2.0;
        // Filter gain `1/pad` (was tomocupy's `0.5/pad`). The extra ½ halved the
        // CUDA analytic amplitude to match tomocupy; the cross-backend convention
        // unification (Phase 2) targets CPU/tomopy instead, whose filter carries no
        // such ½ — so drop it. This alone brings lprec to cpu scale (k ½→1); fbp/
        // linerec additionally need the π/nproj dθ weight passed at the analytic
        // back-projection call sites (was tomocupy's baked-in 4/nproj).
        let inv_pad = 1.0f32 / pad as f32;
        let mut w = vec![0.0f32; nz * nfreq * 2];
        for z in 0..nz {
            let delta = half - geom.center.at(z);
            for (k, &fk) in filter[..nfreq].iter().enumerate() {
                let ang = -std::f32::consts::TAU * k as f32 * delta / pad as f32;
                let idx = z * nfreq + k;
                w[2 * idx] = fk * ang.cos() * inv_pad;
                w[2 * idx + 1] = fk * ang.sin() * inv_pad;
            }
        }
        w
    }

    fn ck(rc: i32, what: &str) -> Result<()> {
        if rc != 0 {
            return Err(Error::Backend(format!("cuda {what} failed ({rc})")));
        }
        Ok(())
    }

    /// Pad → cuFFT filter → crop → `cfunc_linerec` back-projection for one
    /// z-chunk, entirely on the **current** device. Every device buffer is local
    /// to the calling thread, so this is safe to run on many devices at once (one
    /// thread per GPU, each having called `cudaSetDevice`). Returns the chunk's
    /// volume `[nz, n, n]`. `w` is the filter weight slice for *these* z rows.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fbp_chunk(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let sino_dev = DevBuf::from_host_f32(raw)?;
        let w_dev = DevBuf::from_host_f32(w)?;
        let theta_dev = DevBuf::from_host_f32(theta)?;
        let gpad = DevBuf::zeroed(nz * nproj * pad * fsz)?;
        ck(
            unsafe {
                ffi::tomoxide_pad(
                    sino_dev.ptr,
                    gpad.ptr,
                    nz,
                    nproj,
                    ncols,
                    pad,
                    pad_side,
                    null,
                )
            },
            "pad",
        )?;
        let fh = Handle::new(
            unsafe { ffi::tomoxide_filter_new(nproj, nz, pad) },
            ffi::tomoxide_filter_free,
            "cfunc_filter",
        )?;
        ck(
            unsafe { ffi::tomoxide_filter_apply(fh.ptr, gpad.ptr, w_dev.ptr, null) },
            "filter_apply",
        )?;
        drop(fh);
        let gf = DevBuf::zeroed(nz * nproj * ncols * fsz)?;
        ck(
            unsafe { ffi::tomoxide_crop(gpad.ptr, gf.ptr, nz, nproj, ncols, pad, pad_side, null) },
            "crop",
        )?;
        let f = DevBuf::zeroed(nz * n * n * fsz)?;
        let h = Handle::new(
            unsafe { ffi::tomoxide_linerec_new(nproj, nz, n, nproj, nz) },
            ffi::tomoxide_linerec_free,
            "cfunc_linerec",
        )?;
        unsafe {
            ck(
                ffi::tomoxide_linerec_backproject(
                    h.ptr,
                    f.ptr,
                    gf.ptr,
                    theta_dev.ptr as *const f32,
                    std::f32::consts::FRAC_PI_2,
                    (n / 2) as f32, // centred sinogram: axis = n/2
                    std::f32::consts::PI / nproj as f32, // FBP angular quadrature dθ
                    0,
                    nz as i32, // parallel beam: rh == nz
                    null,
                ),
                "linerec_backproject",
            )?;
        }
        drop(h);
        ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        let mut host = vec![0.0f32; nz * n * n];
        f.to_host_f32(&mut host)?;
        Ok(host)
    }

    /// Laminography back-projection (`cfunc_linerec` with a tilted rotation axis)
    /// for one output-z chunk, entirely on the **current** device. Mirrors
    /// [`analytic_fbp_chunk`]'s pad → cuFFT filter → crop, but the back-projection
    /// (a) feeds the scalar tilt `phi = π/2 + lamino_angle` instead of `π/2`,
    /// (b) reconstructs `rh` output slices (not the `nz` detector rows — every
    /// output voxel samples a detector row that depends on `(x,y,z)` once the axis
    /// is tilted, so a parallel-beam per-slice mapping no longer holds), and
    /// (c) passes the chunk's global z-start `sz` so the kernel's volume z
    /// `tz + sz` — centred on `rh/2`, the full recon height's midpoint, matching
    /// the Fourier (USFFT) laminography convention — lands on the right detector
    /// plane (row centre `nz/2`). `rh` is therefore the FULL reconstruction
    /// height: this function reconstructs all of it in one launch (`sz` = 0 from
    /// its only caller); partial-height streaming goes through
    /// [`lamino_backproject_shard`], which takes the shard extent and the full
    /// height separately. The full projection stack (`nz` rows) is filtered once
    /// and back-projected into every output slice. Returns the chunk volume `[rh, n, n]` in the CPU/tomopy
    /// handedness — no y-flip — at the `π/nproj` dθ gain the caller passes, the same
    /// orientation and quadrature weight as every other analytic path here
    /// (`backprojection_ker` lost tomocupy's `(n−1−ty)` write and baked-in `4/nproj`
    /// in the Phase 1/2 unification). What laminography *is* excluded from is the
    /// cross-backend **scale** unification: this kernel and the CPU `recon::lamino`
    /// USFFT algorithm are different reconstructions with different filter
    /// frameworks, so their amplitudes are not comparable (see
    /// `docs/ARCHITECTURE.md` §4.1). Each lamino path is validated against its own
    /// reference (CUDA vs tomocupy, CPU vs wgpu).
    #[allow(clippy::too_many_arguments)]
    fn analytic_lamino_chunk(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
        phi: f32,
        rh: usize,
        sz: i32,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let sino_dev = DevBuf::from_host_f32(raw)?;
        let w_dev = DevBuf::from_host_f32(w)?;
        let theta_dev = DevBuf::from_host_f32(theta)?;
        let gpad = DevBuf::zeroed(nz * nproj * pad * fsz)?;
        ck(
            unsafe {
                ffi::tomoxide_pad(
                    sino_dev.ptr,
                    gpad.ptr,
                    nz,
                    nproj,
                    ncols,
                    pad,
                    pad_side,
                    null,
                )
            },
            "pad",
        )?;
        let fh = Handle::new(
            unsafe { ffi::tomoxide_filter_new(nproj, nz, pad) },
            ffi::tomoxide_filter_free,
            "cfunc_filter",
        )?;
        ck(
            unsafe { ffi::tomoxide_filter_apply(fh.ptr, gpad.ptr, w_dev.ptr, null) },
            "filter_apply",
        )?;
        drop(fh);
        let gf = DevBuf::zeroed(nz * nproj * ncols * fsz)?;
        ck(
            unsafe { ffi::tomoxide_crop(gpad.ptr, gf.ptr, nz, nproj, ncols, pad, pad_side, null) },
            "crop",
        )?;
        // Output is `rh` slices, not `nz`; ncz = rh, ncproj = nproj (whole stack).
        let f = DevBuf::zeroed(rh * n * n * fsz)?;
        let h = Handle::new(
            unsafe { ffi::tomoxide_linerec_new(nproj, nz, n, nproj, rh) },
            ffi::tomoxide_linerec_free,
            "cfunc_linerec",
        )?;
        unsafe {
            ck(
                ffi::tomoxide_linerec_backproject(
                    h.ptr,
                    f.ptr,
                    gf.ptr,
                    theta_dev.ptr as *const f32,
                    phi,
                    (n / 2) as f32, // centred sinogram: axis = n/2
                    std::f32::consts::PI / nproj as f32, // analytic angular quadrature dθ
                    sz,
                    rh as i32, // volume z centred on the full recon height
                    null,
                ),
                "linerec_backproject",
            )?;
        }
        drop(h);
        ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        let mut host = vec![0.0f32; rh * n * n];
        f.to_host_f32(&mut host)?;
        Ok(host)
    }

    /// One slice `sz` back-projected at every tilt in `phi`, in a single launch.
    ///
    /// Same pad → cuFFT filter → crop as [`analytic_lamino_chunk`] — so the
    /// candidate images are the reconstruction, not an approximation of it — but
    /// the back-projection uses `cfunc_linerec`'s `backprojection_try_lamino`,
    /// whose `phi` is indexed per output slot. The handle's `ncz` is therefore
    /// the tilt count and the result is `[ntilt, n, n]`: one image per tilt from
    /// one pass over the filtered stack, where sweeping tilts through
    /// [`analytic_lamino_chunk`] reconstructs a whole `rh`-slice volume per tilt
    /// and throws all but one slice away.
    /// Which axis a probe sweeps, and the per-candidate parameter that sweeps it.
    ///
    /// The two try kernels differ only here: one indexes a back-projection shift
    /// per output slot, the other a tilt. Everything around them — filtering,
    /// angle chunking, accumulation — is identical, so it lives once in
    /// [`try_probe_chunk`] rather than in two copies that can drift apart.
    /// Each variant also carries the reconstruction height(s) `rh` the probed
    /// slice `sz` is centred on (`sz` is a volume z, `tz + sz` centred on `rh/2`
    /// like every reconstruction — see `kernels_linerec.cuh`): one scalar for the
    /// centre sweep (the geometry, and thus the height, is fixed), one per slot
    /// for the tilt sweep (the height depends on the tilt).
    enum TrySweep<'a> {
        /// Centre candidates as back-projection shifts; `phi` fixed for all.
        Center { sh: &'a [f32], phi: f32, rh: i32 },
        /// Tilt candidates as per-slot `phi`; the centre rides in the filter.
        Tilt { phi: &'a [f32], rh: &'a [i32] },
    }

    impl TrySweep<'_> {
        /// Number of candidates = the handle's `ncz` = the output's slot count.
        fn len(&self) -> usize {
            match self {
                TrySweep::Center { sh, .. } => sh.len(),
                TrySweep::Tilt { phi, .. } => phi.len(),
            }
        }

        fn host(&self) -> &[f32] {
            match self {
                TrySweep::Center { sh, .. } => sh,
                TrySweep::Tilt { phi, .. } => phi,
            }
        }
    }

    /// One slice `sz`, reconstructed at every candidate at once: `[ncand, n, n]`.
    ///
    /// Filtering goes through [`lamino_filter_to_host`] — the same owner the
    /// streaming reconstruction uses — so the padded stack is never materialised
    /// whole on the device. That is not a nicety: at 1800×1024×1024 with a 4096
    /// pad it is a single 30 GB `cudaMalloc`, and the probe existed to be cheap.
    /// The try kernels accumulate (`f[...] += ...`) and take the loop bound and
    /// data stride (`ncproj`) separately from the quadrature scale (`π/nproj`),
    /// so summing angle chunks into one zeroed output is exact, not approximate:
    /// each chunk contributes its own angles at the global `dθ` weight.
    #[allow(clippy::too_many_arguments)]
    fn try_probe_chunk(
        raw: ArrayView3<'_, f32>,
        w: &[f32],
        theta: &[f32],
        sweep: TrySweep<'_>,
        n: usize,
        pad: usize,
        pad_side: usize,
        sz: i32,
        cancel: Option<&CancelToken>,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let ncand = sweep.len();
        let (nz, nproj, ncols) = raw.dim();
        let free = device_free_bytes();
        let (host_gf, angle_chunks) = lamino_filter_to_host(raw, w, pad, pad_side, free, cancel)?;
        let ncproj_max = angle_chunks.iter().map(|&(_, l)| l).max().unwrap_or(0);

        let theta_dev = DevBuf::from_host_f32(theta)?;
        let cand_dev = DevBuf::from_host_f32(sweep.host())?;
        // Per-slot recon heights for the tilt sweep (the kernel reads rh[tz]);
        // the centre sweep's single height travels as a plain scalar argument.
        let rh_dev = match &sweep {
            TrySweep::Tilt { rh, .. } => Some(DevBuf::from_host_i32(rh)?),
            TrySweep::Center { .. } => None,
        };
        let gf_dev = DevBuf::new(nz * ncproj_max.max(1) * ncols * fsz)?;
        // ncz = ncand: the kernel's output index selects the CANDIDATE, not a z
        // row. Zeroed once; every angle chunk accumulates into it.
        let f_dev = DevBuf::zeroed(ncand * n * n * fsz)?;

        for (c, &(a0, alen)) in angle_chunks.iter().enumerate() {
            check_cancel(cancel)?;
            gf_dev.copy_from_host_f32(&host_gf[c])?;
            let theta_ptr = unsafe { (theta_dev.ptr as *const f32).add(a0) };
            // `nproj` global (fixes the π/nproj quadrature scale), `alen` local
            // (the kernel's angle loop bound and its `data` stride).
            let h = Handle::new(
                unsafe { ffi::tomoxide_linerec_new(nproj, nz, n, alen, ncand) },
                ffi::tomoxide_linerec_free,
                "cfunc_linerec",
            )?;
            match sweep {
                TrySweep::Center { phi, rh, .. } => unsafe {
                    ck(
                        ffi::tomoxide_linerec_backproject_try(
                            h.ptr,
                            f_dev.ptr,
                            gf_dev.ptr,
                            theta_ptr,
                            cand_dev.ptr as *const f32,
                            phi,
                            sz,
                            rh,
                            null,
                        ),
                        "linerec_backproject_try",
                    )?;
                },
                TrySweep::Tilt { .. } => unsafe {
                    ck(
                        ffi::tomoxide_linerec_backproject_try_lamino(
                            h.ptr,
                            f_dev.ptr,
                            gf_dev.ptr,
                            theta_ptr,
                            cand_dev.ptr as *const f32,
                            sz,
                            rh_dev
                                .as_ref()
                                .expect("Tilt sweep uploads its per-slot rh")
                                .ptr as *const i32,
                            null,
                        ),
                        "linerec_backproject_try_lamino",
                    )?;
                },
            }
            drop(h);
        }
        ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        let mut host = vec![0.0f32; ncand * n * n];
        f_dev.to_host_f32(&mut host)?;
        Ok(host)
    }

    /// See [`super::center_probe`].
    pub(super) fn center_probe(
        sino: &Tomo<f32>,
        geom: &Geometry,
        params: &crate::params::ReconParams,
        centers: &[f32],
        sz: i32,
        cancel: Option<&CancelToken>,
    ) -> Result<Array3<f32>> {
        use crate::backend::make_fbp_filter;

        if centers.is_empty() {
            return Err(Error::InvalidParam("center_probe needs ≥1 centre".into()));
        }
        let raw = sinogram_view(sino);
        let (nz, nproj, ncols) = raw.dim();
        let n = params.num_gridx.unwrap_or(ncols);
        if n != ncols {
            return Err(Error::InvalidParam(format!(
                "cuda center_probe needs a square grid = detector width {ncols}; got {n}"
            )));
        }
        let theta = &geom.angles.0;
        if theta.len() != nproj {
            return Err(Error::ShapeMismatch {
                expected: format!("{nproj} angles"),
                found: theta.len().to_string(),
            });
        }
        // The candidates are realised as shifts *away from the centre the filter
        // used*, so that nominal must be one number. `Center::PerRow` gives the
        // filter a different phase per detector row and leaves no single nominal
        // to sweep around — reject it rather than silently probe around row 0.
        let nominal = match &geom.center {
            Center::Scalar(c) => *c,
            Center::PerRow(v) => {
                let first = *v
                    .first()
                    .ok_or_else(|| Error::InvalidParam("empty PerRow centre".into()))?;
                if v.iter().any(|c| *c != first) {
                    return Err(Error::InvalidParam(
                        "center_probe needs one nominal centre to sweep around; \
                         geom.center is Center::PerRow with differing values"
                            .into(),
                    ));
                }
                first
            }
        };

        let filter = make_fbp_filter(params.filter_name, ncols, RampShape::Wint)?;
        let pad = filter.len();
        let pad_side = pad / 2 - ncols / 2;
        let w = build_filter_w(&filter, geom, nz, ncols, pad);
        let phi = match geom.beam {
            Beam::Laminography { phi } => phi,
            _ => std::f32::consts::FRAC_PI_2,
        };
        // Recon height the probed slice `sz` is centred on — the same height the
        // full reconstruction at this geometry would use, so `sz` means the same
        // volume z the reconstruction's slice index means.
        let rh = match geom.beam {
            Beam::Laminography { phi } => {
                let deg = lamino_tilt_deg(phi);
                params
                    .lamino_rh
                    .unwrap_or_else(|| super::lamino_recon_height(nz, deg))
            }
            _ => nz,
        } as i32;
        // The filter put `nominal` at ncols/2, so the point `c` now sits at
        // ncols/2 + (c − nominal); the kernel samples at `n/2 − sh`, so reaching
        // it needs sh = nominal − c. (Same mapping as tomocupy's
        // `save_centers = centeri − shift_array`, re-derived against tomoxide's
        // own filter phase rather than inherited.)
        let sh: Vec<f32> = centers.iter().map(|c| nominal - c).collect();

        let devices = selected_devices();
        ck(
            unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
            "set_device",
        )?;
        let out = try_probe_chunk(
            raw,
            &w,
            theta,
            TrySweep::Center { sh: &sh, phi, rh },
            n,
            pad,
            pad_side,
            sz,
            cancel,
        )?;
        Array3::from_shape_vec((centers.len(), n, n), out)
            .map_err(|e| Error::InvalidParam(format!("cuda center-probe shape: {e}")))
    }

    /// See [`super::LaminoReprojector`].
    pub(super) struct LaminoReprojector {
        band: DevBuf,
        dev: i32,
        z0: usize,
        nb: usize,
        n: usize,
        depth: usize,
        phi: f32,
        center: f32,
        rows: usize,
    }

    // The band is device memory of the runtime's primary context, valid on any
    // host thread; `project` only reads it and selects its device itself.
    unsafe impl Send for LaminoReprojector {}
    unsafe impl Sync for LaminoReprojector {}

    impl LaminoReprojector {
        pub(super) fn new(
            band: ArrayView3<'_, f32>,
            z0: usize,
            depth: usize,
            tilt_deg: f32,
            center: f32,
            rows: usize,
        ) -> Result<Self> {
            let (nb, ny, n) = band.dim();
            if nb == 0 || n == 0 || ny != n {
                return Err(Error::InvalidParam(format!(
                    "lamino reprojection needs a square band [nb, n, n]; got {nb}x{ny}x{n}"
                )));
            }
            if z0 + nb > depth {
                return Err(Error::InvalidParam(format!(
                    "lamino reprojection: band {z0}..{} exceeds depth {depth}",
                    z0 + nb
                )));
            }
            // The kernel's bilinear row taps need two detector rows.
            if rows < 2 {
                return Err(Error::InvalidParam(format!(
                    "lamino reprojection needs ≥2 rows; got {rows}"
                )));
            }
            if nb * n * n > i32::MAX as usize {
                return Err(Error::InvalidParam(format!(
                    "lamino reprojection: a {nb}x{n}x{n} band exceeds the kernel's int indexing"
                )));
            }
            let dev = *selected_devices().first().unwrap_or(&0);
            ck(unsafe { ffi::tomoxide_cuda_set_device(dev) }, "set_device")?;
            let band = band.as_standard_layout();
            Ok(Self {
                band: DevBuf::from_host_f32(band.as_slice().expect("standard layout"))?,
                dev,
                z0,
                nb,
                n,
                depth,
                phi: lamino_phi(tilt_deg),
                center,
                rows,
            })
        }

        pub(super) fn project(&self, theta: &[f32]) -> Result<Array3<f32>> {
            let (n, rows, nproj) = (self.n, self.rows, theta.len());
            // The launch caches cos/sin per angle in 48 KiB of shared memory, and
            // a launch that asks for more fails without reaching the sync.
            if nproj == 0 || nproj > 6144 || rows * nproj * n > i32::MAX as usize {
                return Err(Error::InvalidParam(format!(
                    "lamino reprojection takes 1..=6144 angles of {rows}x{n} under 2^31 \
                     elements per call; got {nproj}, split theta"
                )));
            }
            ck(
                unsafe { ffi::tomoxide_cuda_set_device(self.dev) },
                "set_device",
            )?;
            let theta_d = DevBuf::from_host_f32(theta)?;
            let g = DevBuf::zeroed(rows * nproj * n * std::mem::size_of::<f32>())?;
            unsafe {
                ck(
                    ffi::tomoxide_forwardproject(
                        g.ptr,
                        self.band.ptr,
                        theta_d.ptr as *const f32,
                        self.phi,
                        self.center,
                        self.z0 as i32,
                        self.nb as i32,
                        rows as i32,
                        n as i32,
                        self.depth as i32,
                        nproj as i32,
                        std::ptr::null_mut(),
                    ),
                    "forwardproject",
                )?;
            }
            let rc = unsafe { ffi::tomoxide_cuda_sync() };
            if rc != 0 {
                return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
            }
            let mut host = vec![0.0f32; rows * nproj * n];
            g.to_host_f32(&mut host)?;
            let sino = Array3::from_shape_vec((rows, nproj, n), host)
                .map_err(|e| Error::InvalidParam(format!("cuda reprojection shape: {e}")))?;
            Ok(sino
                .permuted_axes([1, 0, 2])
                .as_standard_layout()
                .into_owned())
        }

        pub(super) fn shift_gradient(
            &self,
            theta: &[f32],
            frames: ArrayView3<'_, f32>,
            filter: FilterName,
        ) -> Result<ndarray::Array2<f64>> {
            let (n, rows, nproj) = (self.n, self.rows, theta.len());
            if frames.dim() != (nproj, rows, n) || nproj == 0 || n < 2 {
                return Err(Error::InvalidParam(format!(
                    "lamino shift gradient needs frames [{nproj} angles, {rows}, {n}] (n ≥ 2, \
                     angles ≥ 1); got {:?}",
                    frames.dim()
                )));
            }
            ck(
                unsafe { ffi::tomoxide_cuda_set_device(self.dev) },
                "set_device",
            )?;
            let null = std::ptr::null_mut::<c_void>();
            let (fsz, csz) = (std::mem::size_of::<f32>(), 2 * std::mem::size_of::<f32>());
            let (filt, pad) = crate::recon::lamino::projection_filter(filter, n)?;
            let ne = filt.len();
            let filt_dev = DevBuf::from_host_f32(&filt)?;
            let theta_dev = DevBuf::from_host_f32(theta)?;
            let out = DevBuf::zeroed(2 * nproj * std::mem::size_of::<f64>())?;
            // A frame, its two derivatives, and their padded spectra, per angle.
            let per = rows * n * fsz + 2 * rows * n * fsz + 2 * rows * ne * csz;
            let tc_max = (device_free_bytes() / 100 * 30 / per).clamp(1, nproj);
            let m = DevBuf::new(tc_max * rows * n * fsz)?;
            let d = DevBuf::new(2 * tc_max * rows * n * fsz)?;
            let buf = DevBuf::new(2 * tc_max * rows * ne * csz)?;
            for (t0, tc) in chunk_ranges(nproj, tc_max) {
                let chunk = frames.slice(s![t0..t0 + tc, .., ..]);
                let chunk = chunk.as_standard_layout();
                let host = chunk.as_slice().expect("standard layout");
                let rc = unsafe {
                    ffi::tomoxide_cuda_memcpy_h2d(
                        m.ptr,
                        host.as_ptr() as *const c_void,
                        std::mem::size_of_val(host),
                    )
                };
                if rc != 0 {
                    return Err(Error::Backend(format!("cudaMemcpy H2D failed ({rc})")));
                }
                let nlines = (2 * tc * rows) as i64;
                unsafe {
                    ck(
                        ffi::tomoxide_frame_derivatives(
                            m.ptr,
                            d.ptr,
                            tc as i64,
                            rows as i32,
                            n as i32,
                            null,
                        ),
                        "frame_derivatives",
                    )?;
                    // The reconstruction's own filter, unshifted: the dot
                    // below puts column `center` where the band's axis is.
                    ck(
                        ffi::tomoxide_lam_ramp_pad(
                            d.ptr, buf.ptr, nlines, n as i32, ne as i32, pad as i32, null,
                        ),
                        "lam_ramp_pad",
                    )?;
                    ck(
                        ffi::tomoxide_fft_1d_async(buf.ptr, ne, nlines as usize, 0),
                        "lam_ramp_fft",
                    )?;
                    ck(
                        ffi::tomoxide_lam_ramp_mul(
                            buf.ptr,
                            filt_dev.ptr as *const f32,
                            nlines,
                            ne as i32,
                            0.0,
                            null,
                        ),
                        "lam_ramp_mul",
                    )?;
                    ck(
                        ffi::tomoxide_fft_1d_async(buf.ptr, ne, nlines as usize, 1),
                        "lam_ramp_ifft",
                    )?;
                    ck(
                        ffi::tomoxide_lam_ramp_crop(
                            buf.ptr, d.ptr, nlines, n as i32, ne as i32, pad as i32, null,
                        ),
                        "lam_ramp_crop",
                    )?;
                    ck(
                        ffi::tomoxide_framedot(
                            (out.ptr as *mut f64).add(2 * t0) as *mut c_void,
                            self.band.ptr,
                            d.ptr,
                            (d.ptr as *const f32).add(tc * rows * n) as *const c_void,
                            (theta_dev.ptr as *const f32).add(t0),
                            self.phi,
                            self.center,
                            self.z0 as i32,
                            self.nb as i32,
                            rows as i32,
                            n as i32,
                            self.depth as i32,
                            tc as i32,
                            null,
                        ),
                        "framedot",
                    )?;
                }
            }
            let rc = unsafe { ffi::tomoxide_cuda_sync() };
            if rc != 0 {
                return Err(Error::Backend(format!("cuda kernel sync failed ({rc})")));
            }
            ndarray::Array2::from_shape_vec((nproj, 2), out.to_host_f64(2 * nproj)?)
                .map_err(|e| Error::InvalidParam(format!("cuda shift gradient shape: {e}")))
        }
    }

    /// See [`super::LaminoBandFocus`].
    pub(super) struct LaminoBandFocus {
        dev: i32,
        nproj: usize,
        rows: usize,
        n: usize,
        z0: usize,
        nb: usize,
        depth: usize,
        phi: f32,
        filter: Vec<f32>,
        pad: usize,
        /// Pixels the focus disk keeps in a slice.
        cnt: usize,
        /// Each frame's `exp(−p)` spline coefficients, `[nproj, rows + 2·SPLINE_PAD,
        /// n + 2·SPLINE_PAD]`.
        coef: Coef,
        theta: DevBuf,
        mask: DevBuf,
        /// This evaluation's `dy` then `dx`.
        shift: DevBuf,
        /// The filter at this evaluation's centre, and its derivative by it.
        w: DevBuf,
        wc: DevBuf,
        vol: DevBuf,
        /// The band score's derivative by `vol`.
        resid: DevBuf,
        prof: DevBuf,
        dots: DevBuf,
        /// One angle chunk's moved frames and their shift derivatives, `[rows,
        /// len, n]`, and the padded frames the filter works in.
        m: DevBuf,
        dmx: DevBuf,
        dmy: DevBuf,
        gpad: DevBuf,
        chunks: Vec<(usize, usize)>,
        /// The filter and back-projection handles for each chunk length.
        handles: Vec<(usize, Handle, Handle)>,
    }

    /// Host memory for a stack's coefficients: page-locked where the driver
    /// grants that much, pageable otherwise.
    enum HostCoef {
        Pinned(PinnedBuf<f32>),
        Pageable(Vec<f32>),
    }

    impl HostCoef {
        fn new(len: usize) -> Self {
            match PinnedBuf::new(len) {
                Ok(b) => HostCoef::Pinned(b),
                Err(_) => HostCoef::Pageable(vec![0.0f32; len]),
            }
        }

        fn as_slice(&self) -> &[f32] {
            match self {
                HostCoef::Pinned(b) => b.as_slice(),
                HostCoef::Pageable(v) => v,
            }
        }

        fn as_mut_slice(&mut self) -> &mut [f32] {
            match self {
                HostCoef::Pinned(b) => b.as_mut_slice(),
                HostCoef::Pageable(v) => v,
            }
        }
    }

    /// A stack's coefficients where [`BandFrames`] keeps them.
    enum Coef {
        Device(DevBuf),
        /// `chunk` holds the angle chunk being moved.
        Host {
            all: HostCoef,
            chunk: DevBuf,
        },
    }

    // Device memory and handles of the runtime's primary context, valid on any
    // host thread; every evaluation selects its device and takes `&mut self`.
    unsafe impl Send for LaminoBandFocus {}

    impl LaminoBandFocus {
        pub(super) fn new(
            proj: ArrayView3<'_, f32>,
            theta: &[f32],
            filter: FilterName,
            tilt_deg: f32,
            z: (usize, usize),
            frames: BandFrames,
        ) -> Result<Self> {
            let (nproj, rows, n) = proj.dim();
            if nproj == 0 || theta.len() != nproj || rows < 2 || n < 3 {
                return Err(Error::InvalidParam(format!(
                    "band focus needs frames [nproj ≥ 1, rows ≥ 2, n ≥ 3] and an angle each; \
                     got {nproj}x{rows}x{n} and {} angles",
                    theta.len()
                )));
            }
            let depth = super::lamino_recon_height(rows, tilt_deg);
            let (z0, z1) = z;
            if z0 > z1 || z1 >= depth {
                return Err(Error::InvalidParam(format!(
                    "band focus: slices {z0}..={z1} are not inside depth {depth}"
                )));
            }
            let nb = z1 - z0 + 1;
            if nb * n * n > I32_INDEX_LIMIT {
                return Err(Error::InvalidParam(format!(
                    "band focus: a {nb}x{n}x{n} band exceeds the kernels' int indexing"
                )));
            }
            let dev = *selected_devices().first().unwrap_or(&0);
            ck(unsafe { ffi::tomoxide_cuda_set_device(dev) }, "set_device")?;
            let fsz = std::mem::size_of::<f32>();
            let (h, w) = (rows + 2 * SPLINE_PAD, n + 2 * SPLINE_PAD);
            // The coefficients of frames `b0 ..` into `out`.
            let fill = |b0: usize, out: &mut [f32]| {
                out.par_chunks_mut(h * w).enumerate().for_each_init(
                    || (vec![0.0f32; rows * n], vec![0.0f32; h]),
                    |(frame, line), (k, out)| {
                        let p = proj.index_axis(Axis(0), b0 + k);
                        for (t, &v) in frame.iter_mut().zip(p.iter()) {
                            *t = (-v).exp();
                        }
                        spline_coeffs(frame, rows, n, out, line);
                    },
                );
            };
            // The device's copy first: the angle chunks below take what it leaves.
            let (on_device, on_host) = match frames {
                BandFrames::Device => {
                    let coef = DevBuf::new(nproj * h * w * fsz)?;
                    // A batch of frames at a time, so the host never holds the
                    // stack's coefficients.
                    const BATCH: usize = 64;
                    let mut host = vec![0.0f32; BATCH.min(nproj) * h * w];
                    for b0 in (0..nproj).step_by(BATCH) {
                        let host = &mut host[..BATCH.min(nproj - b0) * h * w];
                        fill(b0, host);
                        ck(
                            unsafe {
                                ffi::tomoxide_cuda_memcpy_h2d(
                                    (coef.ptr as *mut f32).add(b0 * h * w) as *mut c_void,
                                    host.as_ptr() as *const c_void,
                                    std::mem::size_of_val(host),
                                )
                            },
                            "coef upload",
                        )?;
                    }
                    (Some(coef), None)
                }
                BandFrames::Host => {
                    let mut all = HostCoef::new(nproj * h * w);
                    fill(0, all.as_mut_slice());
                    (None, Some(all))
                }
            };
            // slice_focus's disk, in its own f32 arithmetic.
            let c = n as f32 / 2.0;
            let r2 = (0.46 * n as f32).powi(2);
            let inner = 1..n - 1;
            let mask: Vec<u8> = (0..n * n)
                .map(|p| {
                    let (y, x) = (p / n, p % n);
                    u8::from(
                        inner.contains(&y)
                            && inner.contains(&x)
                            && (x as f32 - c).powi(2) + (y as f32 - c).powi(2) < r2,
                    )
                })
                .collect();
            let cnt = mask.iter().filter(|&&k| k != 0).count();
            let mask_dev = DevBuf::new(n * n)?;
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_h2d(
                        mask_dev.ptr,
                        mask.as_ptr() as *const c_void,
                        n * n,
                    )
                },
                "mask upload",
            )?;
            let filter = make_fbp_filter(filter, n, RampShape::Wint)?;
            let pad = filter.len();
            let nfreq = pad / 2 + 1;
            let dsz = std::mem::size_of::<f64>();
            let vol = DevBuf::new(nb * n * n * fsz)?;
            let resid = DevBuf::new(nb * n * n * fsz)?;
            let prof = DevBuf::new(nb * dsz)?;
            let dots = DevBuf::new(3 * nproj * dsz)?;
            let shift = DevBuf::new(2 * nproj * fsz)?;
            let w_dev = DevBuf::new(rows * nfreq * 2 * fsz)?;
            let wc = DevBuf::new(rows * nfreq * 2 * fsz)?;
            let theta_dev = DevBuf::from_host_f32(theta)?;
            // Per angle: a frame, its two shift derivatives and its padded copy,
            // for each of the (at most two) filter handles its spectrum and a
            // cuFFT work area taken as large again, and the coefficients a host
            // stack uploads.
            let per = (3 * rows * n + rows * pad) * fsz
                + 2 * 2 * rows * nfreq * 2 * fsz
                + on_host.as_ref().map_or(0, |_| h * w * fsz);
            let by_mem = device_free_bytes() / 10 * 8 / per;
            let by_idx = I32_INDEX_LIMIT / 100 * 88 / (rows * pad);
            // backprojection_ker caches every angle's cos/sin in 48 KiB of shared memory.
            let alen = by_mem.min(by_idx).min(nproj).min(6144);
            if alen == 0 {
                return Err(Error::Backend(format!(
                    "band focus: no room on the device for one {rows}x{n} frame"
                )));
            }
            let chunks = even_z_chunks(nproj, nproj.div_ceil(alen));
            let alen = chunks.iter().map(|&(_, len)| len).max().unwrap_or(1);
            let m = DevBuf::new(rows * alen * n * fsz)?;
            let dmx = DevBuf::new(rows * alen * n * fsz)?;
            let dmy = DevBuf::new(rows * alen * n * fsz)?;
            let gpad = DevBuf::new(rows * alen * pad * fsz)?;
            let coef = match (on_device, on_host) {
                (Some(all), _) => Coef::Device(all),
                (None, Some(all)) => Coef::Host {
                    all,
                    chunk: DevBuf::new(alen * h * w * fsz)?,
                },
                (None, None) => unreachable!("frames are held on the device or the host"),
            };
            let mut handles: Vec<(usize, Handle, Handle)> = Vec::new();
            for &(_, len) in &chunks {
                if handles.iter().any(|(l, ..)| *l == len) {
                    continue;
                }
                handles.push((
                    len,
                    Handle::new(
                        unsafe { ffi::tomoxide_filter_new(len, rows, pad) },
                        ffi::tomoxide_filter_free,
                        "cfunc_filter",
                    )?,
                    Handle::new(
                        unsafe { ffi::tomoxide_linerec_new(nproj, rows, n, len, nb) },
                        ffi::tomoxide_linerec_free,
                        "cfunc_linerec",
                    )?,
                ));
            }
            Ok(Self {
                dev,
                nproj,
                rows,
                n,
                z0,
                nb,
                depth,
                phi: lamino_phi(tilt_deg),
                filter,
                pad,
                cnt,
                coef,
                theta: theta_dev,
                mask: mask_dev,
                shift,
                w: w_dev,
                wc,
                vol,
                resid,
                prof,
                dots,
                m,
                dmx,
                dmy,
                gpad,
                chunks,
                handles,
            })
        }

        pub(super) fn profile(&mut self, dy: &[f32], dx: &[f32], center: f32) -> Result<Vec<f64>> {
            self.reconstruct(dy, dx, center)?;
            self.focus()
        }

        pub(super) fn band(&mut self, dy: &[f32], dx: &[f32], center: f32) -> Result<Array3<f32>> {
            self.reconstruct(dy, dx, center)?;
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
            let mut host = vec![0.0f32; self.nb * self.n * self.n];
            self.vol.to_host_f32(&mut host)?;
            Array3::from_shape_vec((self.nb, self.n, self.n), host)
                .map_err(|e| Error::InvalidParam(format!("cuda band focus shape: {e}")))
        }

        pub(super) fn gradient(
            &mut self,
            dy: &[f32],
            dx: &[f32],
            center: f32,
        ) -> Result<super::BandFocusGradient> {
            self.reconstruct(dy, dx, center)?;
            let profile = self.focus()?;
            let null = std::ptr::null_mut::<c_void>();
            let (nb, n) = (self.nb as i32, self.n as i32);
            // The score is the profile's mean, each slice's sum over `cnt` pixels.
            let scale = 2.0 / (self.nb * self.cnt) as f32;
            unsafe {
                ck(
                    ffi::tomoxide_bf_focus_grad(
                        self.resid.ptr,
                        self.vol.ptr,
                        self.mask.ptr,
                        scale,
                        nb,
                        n,
                        null,
                    ),
                    "bf_focus_grad",
                )?;
                ck(
                    ffi::tomoxide_cuda_memset(self.dots.ptr, 0, self.dots.bytes),
                    "memset",
                )?;
            }
            for &(a0, len) in &self.chunks {
                let (fh, _) = self.handles(len);
                self.move_chunk(a0, len, true)?;
                self.filter_frames(self.dmx.ptr, self.w.ptr, len, fh)?;
                self.filter_frames(self.dmy.ptr, self.w.ptr, len, fh)?;
                self.filter_frames(self.m.ptr, self.wc.ptr, len, fh)?;
                unsafe {
                    ck(
                        ffi::tomoxide_bf_framedot3(
                            (self.dots.ptr as *mut f64).add(3 * a0) as *mut c_void,
                            self.resid.ptr,
                            self.dmx.ptr,
                            self.dmy.ptr,
                            self.m.ptr,
                            (self.theta.ptr as *const f32).add(a0),
                            self.phi,
                            (self.n / 2) as f32,
                            self.z0 as i32,
                            nb,
                            self.rows as i32,
                            n,
                            self.depth as i32,
                            len as i32,
                            null,
                        ),
                        "bf_framedot3",
                    )?;
                }
            }
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
            let dots = self.dots.to_host_f64(3 * self.nproj)?;
            let gain = self.gain() as f64;
            Ok(super::BandFocusGradient {
                profile,
                shift: ndarray::Array2::from_shape_fn((self.nproj, 2), |(t, k)| {
                    gain * dots[3 * t + k]
                }),
                center: gain * dots.as_chunks::<3>().0.iter().map(|d| d[2]).sum::<f64>(),
            })
        }

        /// The back-projection's angular quadrature weight.
        fn gain(&self) -> f32 {
            std::f32::consts::PI / self.nproj as f32
        }

        /// The filter and back-projection handles for a chunk of `len` angles.
        fn handles(&self, len: usize) -> (&Handle, &Handle) {
            let (_, fh, bh) = self
                .handles
                .iter()
                .find(|(l, ..)| *l == len)
                .expect("a handle per chunk length");
            (fh, bh)
        }

        /// Upload this evaluation's shifts and filters and back-project the band
        /// into `vol`.
        fn reconstruct(&mut self, dy: &[f32], dx: &[f32], center: f32) -> Result<()> {
            let nproj = self.nproj;
            if dy.len() != nproj || dx.len() != nproj {
                return Err(Error::InvalidParam(format!(
                    "band focus takes {nproj} dy and dx; got {} and {}",
                    dy.len(),
                    dx.len()
                )));
            }
            ck(
                unsafe { ffi::tomoxide_cuda_set_device(self.dev) },
                "set_device",
            )?;
            let geom = Geometry {
                center: Center::Scalar(center),
                ..Geometry::parallel(Angles(Vec::new()), self.n, self.rows, 1.0)
            };
            let w = build_filter_w(&self.filter, &geom, self.rows, self.n, self.pad);
            // The centre enters only through the phase −2π·k·(n/2 − center)/pad.
            let nfreq = self.pad / 2 + 1;
            let mut wc = vec![0.0f32; w.len()];
            let pairs = wc
                .as_chunks_mut::<2>()
                .0
                .iter_mut()
                .zip(w.as_chunks::<2>().0);
            for (i, (d, s)) in pairs.enumerate() {
                let sk = std::f32::consts::TAU * (i % nfreq) as f32 / self.pad as f32;
                d[0] = -sk * s[1];
                d[1] = sk * s[0];
            }
            self.w.copy_from_host_f32(&w)?;
            self.wc.copy_from_host_f32(&wc)?;
            self.shift.copy_from_host_f32(&[dy, dx].concat())?;
            ck(
                unsafe { ffi::tomoxide_cuda_memset(self.vol.ptr, 0, self.vol.bytes) },
                "memset",
            )?;
            let null = std::ptr::null_mut::<c_void>();
            for &(a0, len) in &self.chunks {
                let (fh, bh) = self.handles(len);
                self.move_chunk(a0, len, false)?;
                self.filter_frames(self.m.ptr, self.w.ptr, len, fh)?;
                unsafe {
                    ck(
                        ffi::tomoxide_linerec_backproject(
                            bh.ptr,
                            self.vol.ptr,
                            self.m.ptr,
                            (self.theta.ptr as *const f32).add(a0),
                            self.phi,
                            (self.n / 2) as f32,
                            self.gain(),
                            self.z0 as i32,
                            self.depth as i32,
                            null,
                        ),
                        "linerec_backproject",
                    )?;
                }
            }
            Ok(())
        }

        /// slice_focus of each slice of `vol`.
        fn focus(&self) -> Result<Vec<f64>> {
            unsafe {
                ck(
                    ffi::tomoxide_cuda_memset(self.prof.ptr, 0, self.prof.bytes),
                    "memset",
                )?;
                ck(
                    ffi::tomoxide_bf_focus(
                        self.prof.ptr,
                        self.vol.ptr,
                        self.mask.ptr,
                        self.nb as i32,
                        self.n as i32,
                        std::ptr::null_mut(),
                    ),
                    "bf_focus",
                )?;
                ck(ffi::tomoxide_cuda_sync(), "sync")?;
            }
            let cnt = self.cnt as f64;
            Ok(self
                .prof
                .to_host_f64(self.nb)?
                .into_iter()
                .map(|a| a / cnt)
                .collect())
        }

        /// Frames `a0 .. a0 + len` moved by this evaluation's shifts into `m`,
        /// with their shift derivatives into `dmx`/`dmy` when `grad`.
        fn move_chunk(&self, a0: usize, len: usize, grad: bool) -> Result<()> {
            let null = std::ptr::null_mut::<c_void>();
            let (dmx, dmy) = if grad {
                (self.dmx.ptr, self.dmy.ptr)
            } else {
                (null, null)
            };
            let dy = self.shift.ptr as *const f32;
            // The coefficients the kernel reads, and frame `a0`'s place in them.
            let (coef, c0) = match &self.coef {
                Coef::Device(all) => (all.ptr, a0),
                Coef::Host { all, chunk } => {
                    let hw = (self.rows + 2 * SPLINE_PAD) * (self.n + 2 * SPLINE_PAD);
                    let src = &all.as_slice()[a0 * hw..(a0 + len) * hw];
                    ck(
                        unsafe {
                            ffi::tomoxide_cuda_memcpy_h2d(
                                chunk.ptr,
                                src.as_ptr() as *const c_void,
                                std::mem::size_of_val(src),
                            )
                        },
                        "coef chunk upload",
                    )?;
                    (chunk.ptr, 0)
                }
            };
            ck(
                unsafe {
                    ffi::tomoxide_bf_move(
                        self.m.ptr,
                        dmx,
                        dmy,
                        coef,
                        dy,
                        dy.add(self.nproj),
                        a0 as i32,
                        c0 as i32,
                        len as i32,
                        self.rows as i32,
                        self.n as i32,
                        null,
                    )
                },
                "bf_move",
            )
        }

        /// `buf` (`[rows, len, n]`) filtered in place with `w` as the
        /// reconstruction filters its frames.
        fn filter_frames(
            &self,
            buf: *mut c_void,
            w: *const c_void,
            len: usize,
            fh: &Handle,
        ) -> Result<()> {
            let null = std::ptr::null_mut::<c_void>();
            let (rows, n, pad) = (self.rows, self.n, self.pad);
            let pad_side = pad / 2 - n / 2;
            unsafe {
                ck(
                    ffi::tomoxide_pad(buf, self.gpad.ptr, rows, len, n, pad, pad_side, null),
                    "pad",
                )?;
                ck(
                    ffi::tomoxide_filter_apply(fh.ptr, self.gpad.ptr, w, null),
                    "filter_apply",
                )?;
                ck(
                    ffi::tomoxide_crop(self.gpad.ptr, buf, rows, len, n, pad, pad_side, null),
                    "crop",
                )
            }
        }
    }

    /// See [`super::center_probe_sweep`].
    pub(super) fn center_probe_sweep(
        sino: &Tomo<f32>,
        geom: &Geometry,
        params: &crate::params::ReconParams,
        centers: &[f32],
        sz: i32,
        cancel: Option<&CancelToken>,
    ) -> Result<Array3<f32>> {
        if centers.is_empty() {
            return Err(Error::InvalidParam(
                "center_probe_sweep needs ≥1 centre".into(),
            ));
        }
        // Group by fractional part: two candidates can share one probe exactly
        // when they differ by a whole number of columns. The key quantises the
        // fraction so float noise in a generated grid (`c0 + k*step`) does not
        // split a lattice into singletons; anything coarser than this tolerance
        // is a genuinely different lattice and gets its own probe.
        const FRAC_TOL: f32 = 1e-4;
        let key_of = |c: f32| -> i64 {
            let frac = c - c.floor();
            let k = (frac / FRAC_TOL).round() as i64;
            // frac ≈ 1 and frac ≈ 0 are the same lattice.
            let m = (1.0 / FRAC_TOL) as i64;
            if k == m {
                0
            } else {
                k
            }
        };

        let mut groups: Vec<(i64, Vec<usize>)> = Vec::new();
        for (i, &c) in centers.iter().enumerate() {
            let k = key_of(c);
            match groups.iter_mut().find(|(gk, _)| *gk == k) {
                Some((_, idx)) => idx.push(i),
                None => groups.push((k, vec![i])),
            }
        }

        let n_out = params.num_gridx.unwrap_or(sino.n_cols());
        let mut out = Array3::<f32>::zeros((centers.len(), n_out, n_out));
        for (_, idx) in &groups {
            // Anchor on a member of the group: every other member is then an
            // exact integer shift away from it, which is the whole point.
            let nominal = centers[idx[0]];
            let g = Geometry {
                angles: geom.angles.clone(),
                center: Center::Scalar(nominal),
                beam: geom.beam,
                detector: geom.detector,
            };
            let cands: Vec<f32> = idx.iter().map(|&i| centers[i]).collect();
            let probe = center_probe(sino, &g, params, &cands, sz, cancel)?;
            for (j, &i) in idx.iter().enumerate() {
                out.index_axis_mut(Axis(0), i)
                    .assign(&probe.index_axis(Axis(0), j));
            }
        }
        Ok(out)
    }

    /// See [`super::lamino_tilt_probe`].
    pub(super) fn lamino_tilt_probe(
        sino: &Tomo<f32>,
        geom: &Geometry,
        params: &crate::params::ReconParams,
        tilts_deg: &[f32],
        sz: i32,
        cancel: Option<&CancelToken>,
    ) -> Result<Array3<f32>> {
        use crate::backend::make_fbp_filter;

        if tilts_deg.is_empty() {
            return Err(Error::InvalidParam(
                "lamino_tilt_probe needs ≥1 tilt".into(),
            ));
        }
        let raw = sinogram_view(sino);
        let (nz, nproj, ncols) = raw.dim();
        let n = params.num_gridx.unwrap_or(ncols);
        if n != ncols {
            return Err(Error::InvalidParam(format!(
                "cuda lamino_tilt_probe needs a square grid = detector width {ncols}; got {n}"
            )));
        }
        let theta = &geom.angles.0;
        if theta.len() != nproj {
            return Err(Error::ShapeMismatch {
                expected: format!("{nproj} angles"),
                found: theta.len().to_string(),
            });
        }

        // The rotation center rides in the filter (as every analytic CUDA path
        // does), so it comes from `geom`; only the tilt is swept here, and
        // `geom.beam` is ignored because these tilts replace it.
        let filter = make_fbp_filter(params.filter_name, ncols, RampShape::Wint)?;
        let pad = filter.len();
        let pad_side = pad / 2 - ncols / 2;
        let w = build_filter_w(&filter, geom, nz, ncols, pad);
        let phi: Vec<f32> = tilts_deg.iter().map(|&d| lamino_phi(d)).collect();
        // Per-tilt recon height: each candidate's slice `sz` is centred on the
        // height the full reconstruction at THAT tilt would use, so one volume z
        // means the same thing across the sweep and against the reconstruction.
        let rh: Vec<i32> = tilts_deg
            .iter()
            .map(|d| {
                params
                    .lamino_rh
                    .unwrap_or_else(|| super::lamino_recon_height(nz, *d)) as i32
            })
            .collect();

        let devices = selected_devices();
        ck(
            unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
            "set_device",
        )?;
        let out = try_probe_chunk(
            raw,
            &w,
            theta,
            TrySweep::Tilt { phi: &phi, rh: &rh },
            n,
            pad,
            pad_side,
            sz,
            cancel,
        )?;
        Array3::from_shape_vec((phi.len(), n, n), out)
            .map_err(|e| Error::InvalidParam(format!("cuda tilt-probe shape: {e}")))
    }

    /// Largest projection-angle chunk (`ncproj`) for streamed laminography on the
    /// current device. Unlike parallel-beam FBP — which chunks the *output* z axis
    /// because each detector row maps to one output slice — laminography's tilt
    /// couples every detector row into every output voxel, so the back-projection
    /// of any output slab needs the **whole** `nz` filtered stack. The stack is
    /// instead split along projection angles: `backprojection_ker` accumulates
    /// (`f[...] += …`), so summing per-angle-chunk back-projections reproduces the
    /// full sum. This is tomocupy's laminography strategy (`backproj_functions.py`,
    /// "note ncproj,nz!"): filter with `(ncproj, nz)`, loop angle chunks inside the
    /// output-tile loop.
    ///
    /// Bounded by (a) the 32-bit index ceiling in `backprojection_ker`, which
    /// addresses the filtered stack as `ur + t·n + vr·n·ncproj` with `vr < nz`, so
    /// `nz·n·ncproj` must stay under 2³¹; and (b) memory — the resident filtered
    /// angle chunk `nz·ncproj·ncols`, kept to ≲40 % of the budget so the output
    /// tile and the per-chunk filter scratch also fit. Always ≥ 1, ≤ `nproj`.
    fn lamino_ncproj(
        nz: usize,
        ncols: usize,
        n: usize,
        nproj: usize,
        pad: usize,
        free_bytes: usize,
    ) -> usize {
        let fsz = std::mem::size_of::<f32>();
        // (a) index: the kernel column stride is `n`; the analytic lamino path has
        //     ncols == n, but take the larger for a conservative bound.
        let stride = n.max(ncols);
        let by_idx = (I32_INDEX_LIMIT / 100 * 88) / (nz * stride).max(1);
        // (b) memory: resident filtered angle chunk `nz·ncproj·ncols` ≤ 40% budget.
        let per_ncproj = nz * ncols * fsz;
        let by_mem = (free_bytes / 100 * 40) / per_ncproj.max(1);
        // Filter must fit at ≥1 detector row per sub-chunk: 2·ncproj·pad ≤ 80% free.
        let by_filter = (free_bytes / 100 * 80) / (2 * pad * fsz).max(1);
        by_idx.min(by_mem).min(by_filter).min(nproj).max(1)
    }

    /// Largest output rh-tile (`ncz`) for streamed laminography, given the resident
    /// filtered angle chunk already claims `nz·ncproj·ncols·4` bytes. Bounded by
    /// (a) the 32-bit index ceiling on the output buffer `tz·n·n` (`tz < ncz`) and
    /// (b) the memory left after the angle chunk. Always ≥ 1, ≤ `rh`.
    fn lamino_ncz(n: usize, nz: usize, ncols: usize, ncproj: usize, free_bytes: usize) -> usize {
        let fsz = std::mem::size_of::<f32>();
        let by_idx = (I32_INDEX_LIMIT / 100 * 88) / (n * n).max(1);
        let gf_bytes = nz * ncproj * ncols * fsz;
        let left = free_bytes.saturating_sub(gf_bytes);
        let by_mem = (left / 100 * 80) / (n * n * fsz).max(1);
        by_idx.min(by_mem).max(1)
    }

    /// Streamed (out-of-core) laminography FBP/Linerec on the current device.
    /// Mirrors tomocupy's laminography chunking: filter once into a host-resident
    /// filtered stack (nz-sub-chunked so the padded scratch stays within VRAM and
    /// under the 32-bit index ceiling), laid out per projection-angle chunk; then a
    /// nested loop — output rh-tiles (outer) × angle chunks (inner) — uploads each
    /// filtered angle chunk and **accumulates** its back-projection into the tile
    /// via the `sz` output-row offset, downloading each finished tile.
    ///
    /// When the whole stack fits one chunk in both memory and the 32-bit index,
    /// delegates to [`analytic_lamino_chunk`] (byte-identical to the un-streamed
    /// path). When chunked, the result is *not* bit-identical: the nz-sub-chunked
    /// cuFFT filter picks its algorithm by batch size, and the angle-chunked
    /// back-projection sums partial results in a different float order — both agree
    /// with the single-shot path to the f32 rounding floor.
    #[allow(clippy::too_many_arguments)]
    fn analytic_lamino_stream(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
        phi: f32,
        rh: usize,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let free = device_free_bytes();

        // Fast path: whole stack indexes < 2³¹ on every kernel (filter pad stride,
        // filtered stack, output) AND fits one chunk in memory → single shot,
        // byte-identical to the un-streamed reconstruction.
        let idx_cap = I32_INDEX_LIMIT / 100 * 88;
        let stride = n.max(ncols);
        let idx_ok = nz.saturating_mul(nproj).saturating_mul(pad) < idx_cap
            && nz.saturating_mul(nproj).saturating_mul(stride) < idx_cap
            && rh.saturating_mul(n).saturating_mul(n) < idx_cap;
        // Single-shot peak: sino + gpad + filter internal (≈ padded again) + gf +
        // output volume, all coexisting until the function returns.
        let single_shot = (2 * nz * nproj * ncols + 2 * nz * nproj * pad + rh * n * n) * fsz;
        if idx_ok && single_shot <= free / 100 * 85 {
            return analytic_lamino_chunk(
                raw, w, theta, nz, nproj, ncols, n, pad, pad_side, phi, rh, 0,
            );
        }

        // ---- Out-of-core path: filter once to host, back-project the full rh ----
        let view = ArrayView3::from_shape((nz, nproj, ncols), raw)
            .map_err(|e| Error::InvalidParam(format!("cuda lamino sinogram shape: {e}")))?;
        let (host_gf, angle_chunks) = lamino_filter_to_host(view, w, pad, pad_side, free, None)?;
        lamino_backproject_shard(
            &host_gf,
            &angle_chunks,
            theta,
            nz,
            nproj,
            ncols,
            n,
            phi,
            0,
            rh,
            rh,
            free,
        )
    }

    /// Host-resident filtered laminography stack, angle-major: `.0[c]` holds
    /// angle chunk `c` as `[nz, alen, ncols]` (the layout `backprojection_ker`
    /// reads), `.1[c] = (a0, alen)`. Produced by [`lamino_filter_to_host`] and
    /// consumed read-only by [`lamino_backproject_shard`] (shared across GPUs).
    type LaminoHostStack = (Vec<Vec<f32>>, Vec<(usize, usize)>);

    /// `sino` as `[nz, nproj, ncols]` whichever layout it is stored in, without
    /// copying: a whole-stack transpose here is seconds of work no token can stop.
    fn sinogram_view(sino: &Tomo<f32>) -> ArrayView3<'_, f32> {
        match sino.layout {
            Layout::Sinogram => sino.array.view(),
            Layout::Projection => sino.array.view().permuted_axes([1, 0, 2]),
        }
    }

    /// Filter the whole projection stack into host memory, angle-major, for
    /// streamed laminography. Returns `(host_gf, angle_chunks)` where
    /// `host_gf[c]` is the filtered projections of angle chunk `c` as
    /// `[nz, alen, ncols]` contiguous (the exact layout `backprojection_ker`
    /// reads) and `angle_chunks[c] = (a0, alen)`. Filtering is nz-sub-chunked so
    /// the padded scratch stays within VRAM and under the 32-bit index ceiling.
    /// `raw` is `[nz, nproj, ncols]` in any strides; each tile gathers its own
    /// rows, so `cancel` is honoured per tile, not after the whole stack.
    /// Runs on the **current** device; the host result is device-independent, so
    /// a multi-GPU driver filters once here and shares it read-only across the
    /// per-device back-projection shards.
    fn lamino_filter_to_host(
        raw: ArrayView3<'_, f32>,
        w: &[f32],
        pad: usize,
        pad_side: usize,
        free: usize,
        cancel: Option<&CancelToken>,
    ) -> Result<LaminoHostStack> {
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let (nz, nproj, ncols) = raw.dim();
        let nfreq2 = (pad / 2 + 1) * 2; // floats per z row of `w`
                                        // Angle chunks: fixed count, even split ≤ ncproj so each stays under the
                                        // index/memory bound.
        let ncproj = lamino_ncproj(nz, ncols, ncols, nproj, pad, free);
        let ntchunk = nproj.div_ceil(ncproj);
        let angle_chunks = even_z_chunks(nproj, ntchunk);

        let mut host_gf: Vec<Vec<f32>> = Vec::with_capacity(angle_chunks.len());
        for &(a0, alen) in &angle_chunks {
            let mut gf_host = vec![0.0f32; nz * alen * ncols];
            let ztile = filter_tile_z(alen, pad, free).min(nz.max(1));
            let zk = nz.div_ceil(ztile.max(1));
            for &(z0, zlen) in &even_z_chunks(nz, zk.max(1)) {
                check_cancel(cancel)?;
                // Gather raw[z0:z0+zlen, a0:a0+alen, :] into a contiguous stage.
                let mut stage = Vec::with_capacity(zlen * alen * ncols);
                for row in raw.slice(s![z0..z0 + zlen, a0..a0 + alen, ..]).rows() {
                    match row.as_slice() {
                        Some(r) => stage.extend_from_slice(r),
                        None => stage.extend(row.iter().copied()),
                    }
                }
                let sino_dev = DevBuf::from_host_f32(&stage)?;
                let gpad = DevBuf::zeroed(zlen * alen * pad * fsz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_pad(
                            sino_dev.ptr,
                            gpad.ptr,
                            zlen,
                            alen,
                            ncols,
                            pad,
                            pad_side,
                            null,
                        )
                    },
                    "pad",
                )?;
                // `w` is [nz, nfreq2], angle-independent (mulw indexes it by
                // frequency and detector row only) → slice by z, reuse per chunk.
                let w_dev = DevBuf::from_host_f32(&w[z0 * nfreq2..(z0 + zlen) * nfreq2])?;
                let fh = Handle::new(
                    unsafe { ffi::tomoxide_filter_new(alen, zlen, pad) },
                    ffi::tomoxide_filter_free,
                    "cfunc_filter",
                )?;
                ck(
                    unsafe { ffi::tomoxide_filter_apply(fh.ptr, gpad.ptr, w_dev.ptr, null) },
                    "filter_apply",
                )?;
                drop(fh);
                let gf_dev = DevBuf::zeroed(zlen * alen * ncols * fsz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_crop(
                            gpad.ptr, gf_dev.ptr, zlen, alen, ncols, pad, pad_side, null,
                        )
                    },
                    "crop",
                )?;
                ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
                gf_dev.to_host_f32(&mut gf_host[z0 * alen * ncols..(z0 + zlen) * alen * ncols])?;
            }
            host_gf.push(gf_host);
        }
        Ok((host_gf, angle_chunks))
    }

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

        // The token is read before the first tile's gather and upload, so a
        // fired one returns without touching the device.
        #[test]
        fn a_fired_token_stops_the_filter_before_its_first_tile() {
            let (nz, nproj, ncols, pad) = (4usize, 6usize, 8usize, 32usize);
            let raw = Array3::<f32>::zeros((nz, nproj, ncols));
            let w = vec![0.0f32; nz * (pad / 2 + 1) * 2];
            let token = CancelToken::new();
            token.cancel();
            let r = lamino_filter_to_host(raw.view(), &w, pad, 12, 1 << 30, Some(&token));
            assert!(matches!(r, Err(Error::Cancelled)));
        }
    }

    /// Back-project the global output rows `[rh0, rh0+rh_len)` from an
    /// already-filtered host stack (`host_gf`/`angle_chunks` from
    /// [`lamino_filter_to_host`]) on the **current** device, returning
    /// `[rh_len, n, n]`. The shard is internally rh-tiled (bounded by memory and
    /// the `ncz·n·n < 2³¹` index ceiling); each tile is zeroed once and every
    /// angle chunk **accumulates** into it via the kernel's `+=`, with the global
    /// row offset `sz = rh0 + tile_local_start` so the shard lands on the correct
    /// output rows. This is the shardable unit: a multi-GPU driver runs one shard
    /// per device over disjoint rh ranges reading the shared `host_gf`.
    /// `rh_total` is the FULL reconstruction height the global rows are centred
    /// on (every shard passes the same value; a shard's own extent is `rh_len`).
    #[allow(clippy::too_many_arguments)]
    fn lamino_backproject_shard(
        host_gf: &[Vec<f32>],
        angle_chunks: &[(usize, usize)],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        phi: f32,
        rh0: usize,
        rh_len: usize,
        rh_total: usize,
        free: usize,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let ncproj_max = angle_chunks.iter().map(|&(_, l)| l).max().unwrap_or(0);
        let ncz = lamino_ncz(n, nz, ncols, ncproj_max, free);
        let nrchunk = rh_len.div_ceil(ncz.max(1));
        let rh_tiles = even_z_chunks(rh_len, nrchunk.max(1));

        let theta_dev = DevBuf::from_host_f32(theta)?;
        let ncz_max = rh_tiles.iter().map(|&(_, l)| l).max().unwrap_or(0);
        let gf_dev = DevBuf::new(nz * ncproj_max.max(1) * ncols * fsz)?;
        let f_dev = DevBuf::new(ncz_max.max(1) * n * n * fsz)?;
        let mut out = vec![0.0f32; rh_len * n * n];
        let gain = std::f32::consts::PI / nproj as f32; // analytic angular quadrature dθ

        for &(t_local, tlen) in &rh_tiles {
            // Zero the tile once; each angle chunk accumulates into it.
            ck(
                unsafe { ffi::tomoxide_cuda_memset(f_dev.ptr, 0, tlen * n * n * fsz) },
                "memset f",
            )?;
            let sz = (rh0 + t_local) as i32;
            for (c, &(a0, alen)) in angle_chunks.iter().enumerate() {
                gf_dev.copy_from_host_f32(&host_gf[c])?;
                let theta_ptr = unsafe { (theta_dev.ptr as *const f32).add(a0) };
                let h = Handle::new(
                    unsafe { ffi::tomoxide_linerec_new(nproj, nz, n, alen, tlen) },
                    ffi::tomoxide_linerec_free,
                    "cfunc_linerec",
                )?;
                unsafe {
                    ck(
                        ffi::tomoxide_linerec_backproject(
                            h.ptr,
                            f_dev.ptr,
                            gf_dev.ptr,
                            theta_ptr,
                            phi,
                            (n / 2) as f32, // centred sinogram: axis = n/2
                            gain,
                            sz,
                            rh_total as i32, // global rows centred on the full height
                            null,
                        ),
                        "linerec_backproject",
                    )?;
                }
                drop(h);
            }
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
            f_dev.to_host_f32(&mut out[t_local * n * n..(t_local + tlen) * n * n])?;
        }
        Ok(out)
    }

    /// Half-precision (`Dtype::F16`) FBP/Linerec on the **current** device, whole
    /// stack in one chunk. Mirrors [`analytic_fbp_chunk`] but the sinogram, filter
    /// weights, padded/filtered buffers and volume are `f16` (2 bytes/element) and
    /// the filter runs a half-precision cuFFT — so the padded width `pad` MUST be a
    /// power of two (enforced by the caller). theta stays f32. The result is the
    /// f32-widened volume; because the half cuFFT and the half back-projection
    /// accumulate in 16-bit, it matches the f32 path only by correlation, not
    /// bit-exactly (tomocupy `--dtype float16`).
    #[allow(clippy::too_many_arguments)]
    fn analytic_fbp_chunk_f16(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let hsz = std::mem::size_of::<half::f16>();
        let null = std::ptr::null_mut::<c_void>();
        let sino_dev = DevBuf::from_host_f16(raw)?;
        let w_dev = DevBuf::from_host_f16(w)?;
        let theta_dev = DevBuf::from_host_f32(theta)?;
        let gpad = DevBuf::zeroed(nz * nproj * pad * hsz)?;
        ck(
            unsafe {
                ffi::tomoxide_pad_fp16(
                    sino_dev.ptr,
                    gpad.ptr,
                    nz,
                    nproj,
                    ncols,
                    pad,
                    pad_side,
                    null,
                )
            },
            "pad_fp16",
        )?;
        let fh = Handle::new(
            unsafe { ffi::tomoxide_filter_fp16_new(nproj, nz, pad) },
            ffi::tomoxide_filter_fp16_free,
            "cfunc_filter (f16)",
        )?;
        ck(
            unsafe { ffi::tomoxide_filter_fp16_apply(fh.ptr, gpad.ptr, w_dev.ptr, null) },
            "filter_fp16_apply",
        )?;
        drop(fh);
        let gf = DevBuf::zeroed(nz * nproj * ncols * hsz)?;
        ck(
            unsafe {
                ffi::tomoxide_crop_fp16(gpad.ptr, gf.ptr, nz, nproj, ncols, pad, pad_side, null)
            },
            "crop_fp16",
        )?;
        let f = DevBuf::zeroed(nz * n * n * hsz)?;
        let h = Handle::new(
            unsafe { ffi::tomoxide_linerec_fp16_new(nproj, nz, n, nproj, nz) },
            ffi::tomoxide_linerec_fp16_free,
            "cfunc_linerec (f16)",
        )?;
        unsafe {
            ck(
                ffi::tomoxide_linerec_fp16_backproject(
                    h.ptr,
                    f.ptr,
                    gf.ptr,
                    theta_dev.ptr as *const f32,
                    std::f32::consts::FRAC_PI_2,
                    (n / 2) as f32, // centred sinogram: axis = n/2
                    std::f32::consts::PI / nproj as f32, // FBP angular quadrature dθ
                    0,
                    nz as i32, // parallel beam: rh == nz
                    null,
                ),
                "linerec_fp16_backproject",
            )?;
        }
        drop(h);
        ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        f.to_host_f16_as_f32(nz * n * n)
    }

    /// Handle-reusing fused FBP/Linerec reconstructor for streaming
    /// ([`StreamingAnalytic`]). The cuFFT filter plan (`filt`), the back-projection
    /// handle (`lrec`; for f16 this owns the layered texture array), the device
    /// buffers and the uploaded `theta` live for the whole stream, so an N-chunk
    /// job pays that setup **once** instead of the per-chunk new/free that
    /// [`analytic_fbp_chunk`]/[`analytic_fbp_chunk_f16`] do. Buffers and handles are
    /// sized to `max_nz` (the first/largest chunk); a smaller trailing chunk reuses
    /// them zero-padded to `max_nz` so the cuFFT batch stays fixed. Holds raw device
    /// pointers and is created/driven on a single compute thread — `!Send`/`!Sync`
    /// by construction (matches the per-thread-device contract of the chunk fns).
    struct CudaFbpStream {
        f16: bool,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
        max_nz: usize,
        filter: Vec<f32>, // ramp kernel (length `pad`), built once
        sino: DevBuf,
        gpad: DevBuf,
        gf: DevBuf,
        f: DevBuf,
        w: DevBuf,
        theta: DevBuf,
        // Device-resident raw path (`reconstruct_chunk_raw`): the raw projection
        // chunk lands here as f32 `[nproj, nz, ncols]`, is dark/flat-corrected and
        // minus-logged in place, then transposed into `sino`. Always f32 (the
        // darkflat/minuslog kernels are f32); the f16 cast happens at the
        // transpose step. `dark2d`/`denom` hold the host-averaged `[nz, ncols]`
        // correction frames (matching `CudaBackend::darkflat`).
        proj: DevBuf,
        dark2d: DevBuf,
        denom: DevBuf,
        // f16 only: device-side f32 staging so the host uploads/downloads f32 and
        // the f32↔f16 cast runs on the GPU (`f2h_ker`/`h2f_ker`), instead of the
        // host rayon convert. `sino_f32` receives the H2D'd f32 sinogram (cast →
        // `sino`); `f_f32` receives the GPU-cast f32 volume (← `f`) before D2H. None
        // on the f32 path, which needs no cast. Mirrors tomocupy's GPU-side astype.
        sino_f32: Option<DevBuf>,
        f_f32: Option<DevBuf>,
        // On-device stripe scratch (`tomoxide_stripe_ti`): `max_nz * 7 * ncols`
        // f64, allocated lazily on the first device-stripe chunk. None until a
        // chunk actually requests a GPU-ported stripe method.
        ti_scratch: Option<DevBuf>,
        // Vo all-stripe scratch (`vo_on_device`): all the per-chunk working
        // buffers, sized to `max_nz` and reused across chunks. Allocated lazily
        // on the first VoAll chunk (a stream not using VoAll never pays the
        // ~5.5 GB it holds at large dims). See [`VoScratch`] for the buffer
        // roles and the lifetime-disjoint aliasing that keeps the set small.
        vo_scratch: Option<VoScratch>,
        filt: *mut c_void,
        lrec: *mut c_void,
        // Fourierrec device-resident path (f32 and f16). When `fourier` is set the
        // back-projection tail of `finish_recon` is pack → `cfunc_fourierrec` →
        // unpack instead of `cfunc_linerec`, reusing the same raw-path normalize/
        // transpose/stripe machinery and the shared `filt` handle. `gc` holds the
        // packed complex sinogram `[max_nz/2, nproj, ncols]` and `fc` the complex
        // reconstruction `[max_nz/2, n, n]` (f16- or f32-wide per `f16`); `frec` is
        // the `cfunc_fourierrec` handle (built for `max_nz/2` pairs, f16 or f32
        // variant). All three are unused (None/null) on the FBP/Linerec path, which
        // keeps `lrec`.
        fourier: bool,
        gc: Option<DevBuf>,
        fc: Option<DevBuf>,
        frec: *mut c_void,
        // Log-polar device-resident path (f32 only). When `lprec` is set the
        // back-projection tail of `finish_recon` runs the [`LpRecDev`] runtime
        // (spline prefilter → per-span gather/FFT/scatter) on the filtered `gf`
        // instead of `cfunc_linerec`/`cfunc_fourierrec`, reusing the same raw-path
        // normalize/transpose/stripe machinery and the shared `filt` handle. The
        // grids are built once and held here (reused across chunks); `flc` is the
        // `[max_nz, nrho, ntheta]` complex work buffer. Both unused (None) on the
        // FBP/Linerec/Fourierrec paths. lprec/fourier/linerec are mutually exclusive.
        lprec: Option<LpRecDev>,
        flc: Option<DevBuf>,
        // Recycled host volume buffers handed back by the writer thread (see
        // `give_reuse_buffer` / `download_volume`). The pinned `out_pinned` is
        // reused across chunks, so the D2H'd volume must be copied into an owned
        // `Send` buffer for the writer. Allocating that buffer fresh each chunk
        // pays ~190 ms of page-faults on a 536 MB `[8, n, n]` chunk; reusing a
        // warm buffer from the writer drops the copy to ~34 ms. Symmetric to the
        // reader's pinned input pool. Empty until the writer returns the first
        // spent volume (the first few chunks still allocate fresh).
        reuse_pool: Vec<Vec<f32>>,
        // Pinned `[max_nz, n, n]` f32 host staging for the volume download. A D2H
        // into pageable memory is driver-staged at ~⅓ the PCIe rate and is
        // synchronous; downloading into this page-locked buffer (then moving it
        // into the writer's owned `Volume`) runs the copy at full bandwidth and
        // avoids the per-chunk `vec![0.0; …]` zero-then-overwrite. Reused across
        // chunks. See [`download_volume`].
        out_pinned: PinnedBuf,
    }

    /// Persistent device scratch for the Vo all-stripe pass, sized to the
    /// handle's fixed `max_nz` batch and reused across chunks (a smaller chunk
    /// uses the `nz`-prefix). Allocating once and reusing removes ~24 per-chunk
    /// `cudaMalloc`/`cudaFree` pairs — the large frees synchronise the device, so
    /// this is wall-clock, not just bookkeeping.
    ///
    /// The large `[max_nz,nproj,ncols]` buffers dominate the footprint, so roles
    /// with disjoint lifetimes share one buffer. The sharing is intra-function
    /// only (each function writes solely its own buffers); the one cross-function
    /// reuse is `big_a`, which `vo_rs_large` reads as its read-only input `s` and
    /// never writes, so the caller can reuse it afterwards. Large f32 roles:
    ///   big_a:     rs_dead `smooth` → `work` (input to rs_large) → rs_sort `sortedv`
    ///   big_b:     rs_sort `smoothed`
    ///   rl_out:    rs_large normalised `out` (returned as `dead_out`)
    ///   rl_sort:   rs_large `sinosort` → `sortdummy`
    ///   rl_smooth: rs_large `sinosmooth`
    /// Large i32: `perm` (rs_sort) and `perm2` (rs_large) kept separate. The
    /// `[max_nz,ncols]`/`[max_nz]` buffers are ~0.5 MB each, so each small role
    /// gets its own buffer (no aliasing); `detsort`/`detraw` are shared by the
    /// two `vo_detect_mask` calls, which never overlap.
    struct VoScratch {
        big_a: DevBuf,
        big_b: DevBuf,
        rl_out: DevBuf,
        rl_sort: DevBuf,
        rl_smooth: DevBuf,
        perm: DevBuf,
        perm2: DevBuf,
        listdiff: DevBuf,
        listdiffbck: DevBuf,
        listfact: DevBuf,
        mask_dead: DevBuf,
        lf64: DevBuf,
        lf32: DevBuf,
        mask_large: DevBuf,
        detsort: DevBuf,
        detraw: DevBuf,
        goodx: DevBuf,
        goodcount: DevBuf,
    }

    impl VoScratch {
        fn new(max_nz: usize, nproj: usize, ncols: usize) -> Result<Self> {
            let (f32sz, f64sz, i32sz) = (
                std::mem::size_of::<f32>(),
                std::mem::size_of::<f64>(),
                std::mem::size_of::<i32>(),
            );
            let vol = max_nz * nproj * ncols;
            let cols = max_nz * ncols;
            Ok(VoScratch {
                big_a: DevBuf::new(vol * f32sz)?,
                big_b: DevBuf::new(vol * f32sz)?,
                rl_out: DevBuf::new(vol * f32sz)?,
                rl_sort: DevBuf::new(vol * f32sz)?,
                rl_smooth: DevBuf::new(vol * f32sz)?,
                perm: DevBuf::new(vol * i32sz)?,
                perm2: DevBuf::new(vol * i32sz)?,
                listdiff: DevBuf::new(cols * f32sz)?,
                listdiffbck: DevBuf::new(cols * f32sz)?,
                listfact: DevBuf::new(cols * f32sz)?,
                mask_dead: DevBuf::new(cols * f32sz)?,
                lf64: DevBuf::new(cols * f64sz)?,
                lf32: DevBuf::new(cols * f32sz)?,
                mask_large: DevBuf::new(cols * f32sz)?,
                detsort: DevBuf::new(cols * f32sz)?,
                detraw: DevBuf::new(cols * f32sz)?,
                goodx: DevBuf::new(cols * i32sz)?,
                goodcount: DevBuf::new(max_nz * i32sz)?,
            })
        }
    }

    impl CudaFbpStream {
        /// Allocate the persistent buffers and `cfunc_filter`/`cfunc_linerec`
        /// handles for a `max_nz`-slice chunk. `filter` is the ramp kernel
        /// (`make_fbp_filter`), `theta` the chunk-invariant angles. The current
        /// device must already be selected (the caller binds it).
        #[allow(clippy::too_many_arguments)]
        fn new(
            filter: Vec<f32>,
            theta: &[f32],
            ncols: usize,
            n: usize,
            max_nz: usize,
            f16: bool,
            fourier: bool,
            lprec: Option<LpRecDev>,
        ) -> Result<Self> {
            let nproj = theta.len();
            let pad = filter.len();
            let pad_side = pad / 2 - ncols / 2;
            let esz = if f16 {
                std::mem::size_of::<half::f16>()
            } else {
                std::mem::size_of::<f32>()
            };
            let nfreq2 = (pad / 2 + 1) * 2;
            let sino = DevBuf::zeroed(max_nz * nproj * ncols * esz)?;
            let gpad = DevBuf::zeroed(max_nz * nproj * pad * esz)?;
            let gf = DevBuf::zeroed(max_nz * nproj * ncols * esz)?;
            let f = DevBuf::zeroed(max_nz * n * n * esz)?;
            let w = DevBuf::zeroed(max_nz * nfreq2 * esz)?;
            let theta_dev = DevBuf::from_host_f32(theta)?;
            // Raw-path staging (always f32): the projection chunk plus the small
            // per-chunk dark/denominator frames.
            let fsz_proj = std::mem::size_of::<f32>();
            let proj = DevBuf::zeroed(max_nz * nproj * ncols * fsz_proj)?;
            let dark2d = DevBuf::zeroed(max_nz * ncols * fsz_proj)?;
            let denom = DevBuf::zeroed(max_nz * ncols * fsz_proj)?;
            // f16: device f32 staging for the GPU-side cast (see field docs).
            let fsz = std::mem::size_of::<f32>();
            let (sino_f32, f_f32) = if f16 {
                (
                    Some(DevBuf::zeroed(max_nz * nproj * ncols * fsz)?),
                    Some(DevBuf::zeroed(max_nz * n * n * fsz)?),
                )
            } else {
                (None, None)
            };
            // The FBP filter handle is shared by both back-projection tails. The
            // tail handle is `cfunc_linerec` (FBP/Linerec) or `cfunc_fourierrec`
            // (Fourierrec, f16 or f32 — built for `max_nz/2` packed pairs). The
            // Fourierrec packed/complex scratch (`gc`/`fc`) is allocated only on
            // that path.
            let filt = unsafe {
                if f16 {
                    ffi::tomoxide_filter_fp16_new(nproj, max_nz, pad)
                } else {
                    ffi::tomoxide_filter_new(nproj, max_nz, pad)
                }
            };
            // lprec uses only the shared `filt` handle plus the uploaded grids; it
            // builds no back-projection tail handle. Its `[max_nz, nrho, ntheta]`
            // complex work buffer is allocated here and reused across chunks.
            let flc = match &lprec {
                Some(lp) => Some(DevBuf::zeroed(lp.flc_bytes(max_nz))?),
                None => None,
            };
            // Pinned host staging for the per-chunk volume D2H (see field docs).
            let out_pinned = PinnedBuf::<f32>::new(max_nz * n * n)?;
            let (lrec, frec, gc, fc) = if lprec.is_some() {
                (std::ptr::null_mut(), std::ptr::null_mut(), None, None)
            } else if fourier {
                // Packed/complex scratch sized to the element width (f16 or f32) and
                // the matching `max_nz/2`-pair handle. The f16 tail mirrors
                // `analytic_fourierrec_f16`.
                let gc = DevBuf::zeroed(max_nz * nproj * ncols * esz)?;
                let fc = DevBuf::zeroed(max_nz * n * n * esz)?;
                let frec = unsafe {
                    if f16 {
                        ffi::tomoxide_fourierrec_fp16_new(
                            nproj,
                            max_nz / 2,
                            n,
                            theta_dev.ptr as *const f32,
                        )
                    } else {
                        ffi::tomoxide_fourierrec_new(
                            nproj,
                            max_nz / 2,
                            n,
                            theta_dev.ptr as *const f32,
                        )
                    }
                };
                (std::ptr::null_mut(), frec, Some(gc), Some(fc))
            } else {
                let lrec = unsafe {
                    if f16 {
                        ffi::tomoxide_linerec_fp16_new(nproj, max_nz, n, nproj, max_nz)
                    } else {
                        ffi::tomoxide_linerec_new(nproj, max_nz, n, nproj, max_nz)
                    }
                };
                (lrec, std::ptr::null_mut(), None, None)
            };
            // lprec has no tail handle, so only `filt` must be non-null there.
            let tail = if fourier { frec } else { lrec };
            if filt.is_null() || (lprec.is_none() && tail.is_null()) {
                // Free whichever allocation succeeded so a partial failure leaks
                // nothing (the Drop guard only runs on a fully-built value).
                unsafe {
                    if !filt.is_null() {
                        if f16 {
                            ffi::tomoxide_filter_fp16_free(filt)
                        } else {
                            ffi::tomoxide_filter_free(filt)
                        }
                    }
                    if !lrec.is_null() {
                        if f16 {
                            ffi::tomoxide_linerec_fp16_free(lrec)
                        } else {
                            ffi::tomoxide_linerec_free(lrec)
                        }
                    }
                    if !frec.is_null() {
                        if f16 {
                            ffi::tomoxide_fourierrec_fp16_free(frec)
                        } else {
                            ffi::tomoxide_fourierrec_free(frec)
                        }
                    }
                }
                return Err(Error::Backend(
                    "cuda streaming reconstructor: cfunc handle allocation failed".into(),
                ));
            }
            Ok(Self {
                f16,
                nproj,
                ncols,
                n,
                pad,
                pad_side,
                max_nz,
                filter,
                sino,
                gpad,
                gf,
                f,
                w,
                theta: theta_dev,
                proj,
                dark2d,
                denom,
                sino_f32,
                f_f32,
                ti_scratch: None,
                vo_scratch: None,
                filt,
                lrec,
                fourier,
                gc,
                fc,
                frec,
                lprec,
                flc,
                out_pinned,
                reuse_pool: Vec::new(),
            })
        }
    }

    impl Drop for CudaFbpStream {
        fn drop(&mut self) {
            unsafe {
                if self.f16 {
                    ffi::tomoxide_filter_fp16_free(self.filt);
                } else {
                    ffi::tomoxide_filter_free(self.filt);
                }
                if self.lprec.is_some() {
                    // lprec builds no tail handle (only the shared `filt`); the
                    // grids/flc are freed by their own DevBuf/LpRecDev drops.
                } else if self.fourier {
                    if self.f16 {
                        ffi::tomoxide_fourierrec_fp16_free(self.frec);
                    } else {
                        ffi::tomoxide_fourierrec_free(self.frec);
                    }
                } else if self.f16 {
                    ffi::tomoxide_linerec_fp16_free(self.lrec);
                } else {
                    ffi::tomoxide_linerec_free(self.lrec);
                }
            }
        }
    }

    impl StreamingAnalytic for CudaFbpStream {
        fn reconstruct_chunk(&mut self, sino: &Tomo<f32>, geom: &Geometry) -> Result<Volume<f32>> {
            let s = sino.as_layout(Layout::Sinogram); // [nz, nproj, ncols]
            let (nz, nproj, ncols) = s.array.dim();
            if nproj != self.nproj || ncols != self.ncols {
                return Err(Error::ShapeMismatch {
                    expected: format!("nproj={} ncols={}", self.nproj, self.ncols),
                    found: format!("nproj={nproj} ncols={ncols}"),
                });
            }
            if nz > self.max_nz {
                return Err(Error::InvalidParam(format!(
                    "streaming reconstruct_chunk: nz={nz} exceeds max_nz={}",
                    self.max_nz
                )));
            }
            let std = s.array.as_standard_layout();
            let raw = std
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;
            let null = std::ptr::null_mut::<c_void>();
            let partial = nz < self.max_nz;
            // Zero the unused tail of a partial trailing chunk so the always-`max_nz`
            // kernels see zeros there (→ zero output we drop); full chunks overwrite
            // the whole `sino` so they skip the memset. (`w`'s tail is zeroed in
            // `finish_recon`.)
            if partial {
                ck(
                    unsafe { ffi::tomoxide_cuda_memset(self.sino.ptr, 0, self.sino.bytes) },
                    "memset sino",
                )?;
            }
            if self.f16 {
                // Upload f32 and cast f32→f16 on the GPU (no host rayon convert).
                // For a partial chunk only the valid `nz` rows are uploaded+cast;
                // the memset above already zeroed `sino`'s tail.
                let sino_f32 = self.sino_f32.as_ref().expect("f16 path has sino_f32");
                sino_f32.copy_from_host_f32(raw)?;
                ck(
                    unsafe {
                        ffi::tomoxide_cast_f32_to_f16(
                            sino_f32.ptr,
                            self.sino.ptr,
                            nz * nproj * ncols,
                            null,
                        )
                    },
                    "cast f32->f16 sino",
                )?;
            } else {
                self.sino.copy_from_host_f32(raw)?;
            }
            self.finish_recon(nz, geom)
        }

        fn reconstruct_chunk_raw(
            &mut self,
            data: &[f32],
            dims: (usize, usize, usize),
            flat: Option<&Frames<f32>>,
            dark: Option<&Frames<f32>>,
            geom: &Geometry,
            stripe: StripeMethod,
        ) -> Result<Option<Volume<f32>>> {
            // `data` is the caller's contiguous, C-order projection-layout chunk
            // `[nproj, nz, ncols]` (read straight into a pinned staging buffer);
            // no layout check is needed — the streaming pipeline only ever feeds
            // projection-order chunks here.
            //
            // Defer the whole chunk to the host when the requested stripe method
            // has no on-device port — checked before any GPU work so we don't
            // normalize on the device only to have the host redo it.
            if !gpu_supports_stripe(stripe) {
                return Ok(None);
            }
            let (nproj, nz, ncols) = dims;
            if nproj != self.nproj || ncols != self.ncols {
                return Err(Error::ShapeMismatch {
                    expected: format!("nproj={} ncols={}", self.nproj, self.ncols),
                    found: format!("nproj={nproj} ncols={ncols}"),
                });
            }
            if nz > self.max_nz {
                return Err(Error::InvalidParam(format!(
                    "streaming reconstruct_chunk_raw: nz={nz} exceeds max_nz={}",
                    self.max_nz
                )));
            }
            if data.len() != nproj * nz * ncols {
                return Err(Error::ShapeMismatch {
                    expected: format!("{} elems ([{nproj}, {nz}, {ncols}])", nproj * nz * ncols),
                    found: format!("{} elems", data.len()),
                });
            }
            let null = std::ptr::null_mut::<c_void>();
            // One H2D: the raw projection chunk as the contiguous [nproj, nz, ncols]
            // prefix of the max-sized f32 `proj` buffer. When `data` is pinned
            // (the streaming reader's staging buffer) this is a direct DMA with no
            // driver staging copy.
            self.proj.copy_from_host_f32(data)?;
            // Dark/flat correction on the device, mirroring `CudaBackend::darkflat`
            // (host-averaged `dark2d`, clamped `denom`, device broadcast) so the
            // output is bit-identical to the host normalize path. Skipped when
            // flat/dark are absent (already-normalized input).
            if let (Some(flat), Some(dark)) = (flat, dark) {
                let dark2d = dark
                    .array
                    .mean_axis(Axis(0))
                    .ok_or_else(|| Error::InvalidParam("empty dark stack".into()))?;
                let flat2d = flat
                    .array
                    .mean_axis(Axis(0))
                    .ok_or_else(|| Error::InvalidParam("empty flat stack".into()))?;
                if dark2d.dim() != (nz, ncols) {
                    return Err(Error::ShapeMismatch {
                        expected: format!("flat/dark frame [{nz}, {ncols}]"),
                        found: format!("{:?}", dark2d.dim()),
                    });
                }
                let mut denom = &flat2d - &dark2d;
                denom.mapv_inplace(|v| if v.abs() < 1e-6 { 1.0 } else { v });
                self.dark2d
                    .copy_from_host_f32(dark2d.as_slice().expect("contiguous dark2d"))?;
                self.denom
                    .copy_from_host_f32(denom.as_slice().expect("contiguous denom"))?;
                ck(
                    unsafe {
                        ffi::tomoxide_darkflat(
                            self.proj.ptr,
                            self.dark2d.ptr,
                            self.denom.ptr,
                            nproj,
                            nz,
                            ncols,
                            null,
                        )
                    },
                    "darkflat",
                )?;
            }
            // minus-log over the valid [nproj, nz, ncols] prefix.
            ck(
                unsafe { ffi::tomoxide_minuslog(self.proj.ptr, nproj * nz * ncols, null) },
                "minuslog",
            )?;
            // Transpose projection → sinogram on the device. The transpose writes
            // only the `nz` valid rows of the sinogram, so zero the tail first on a
            // partial chunk (as `reconstruct_chunk` does). Both paths transpose
            // into an f32 buffer (`sino` for f32, the `sino_f32` staging buffer for
            // f16) so on-device stripe removal runs on f32; the f16 cast follows.
            let partial = nz < self.max_nz;
            if partial {
                ck(
                    unsafe { ffi::tomoxide_cuda_memset(self.sino.ptr, 0, self.sino.bytes) },
                    "memset sino",
                )?;
            }
            let f32_target = if self.f16 {
                self.sino_f32.as_ref().expect("f16 path has sino_f32").ptr
            } else {
                self.sino.ptr
            };
            ck(
                unsafe {
                    ffi::tomoxide_transpose(self.proj.ptr, f32_target, nproj, nz, ncols, null)
                },
                "transpose",
            )?;
            // On-device stripe removal on the f32 sinogram (no-op for
            // `StripeMethod::None`). `gpu_supports_stripe` was checked above, so a
            // `false` here is a logic error rather than a silent host fallback.
            let handled = self.stripe_on_device(f32_target, nz, stripe)?;
            debug_assert!(handled, "gpu_supports_stripe accepted an unhandled method");
            if self.f16 {
                ck(
                    unsafe {
                        ffi::tomoxide_cast_f32_to_f16(
                            f32_target,
                            self.sino.ptr,
                            nz * nproj * ncols,
                            null,
                        )
                    },
                    "cast f32->f16 sino",
                )?;
            }
            Ok(Some(self.finish_recon(nz, geom)?))
        }

        fn give_reuse_buffer(&mut self, buf: Vec<f32>) {
            // The number of volume buffers in circulation is bounded by the
            // pipeline's channel depths, so the pool stays small; cap it anyway so
            // a buffer can never accumulate without limit.
            if self.reuse_pool.len() < 4 {
                self.reuse_pool.push(buf);
            }
        }
    }

    /// Whether the device-resident path can run `stripe` on the GPU. `None` is a
    /// no-op (always handled). Methods without a GPU port make the caller defer
    /// the whole chunk to the host. Kept in sync with [`CudaFbpStream::stripe_on_device`].
    fn gpu_supports_stripe(stripe: StripeMethod) -> bool {
        match stripe {
            StripeMethod::None | StripeMethod::Ti { nblock: 0, .. } | StripeMethod::Fw { .. } => {
                true
            }
            // Vo all-stripe: the on-device median filters keep their window in a
            // fixed 256-element thread-local buffer, so larger windows fall back
            // to the host route.
            StripeMethod::VoAll {
                la_size, sm_size, ..
            } => la_size <= 256 && sm_size <= 256,
            _ => false,
        }
    }

    /// Münch damping vector `D = ifftshift(damp)` (matches `stripe::damp_vector`),
    /// computed in f32 like tomopy and returned as f64 for the device multiply.
    fn fw_damp_vector(my: usize, sigma: f32) -> Vec<f64> {
        let two_sig2 = 2.0f32 * sigma * sigma;
        let damp: Vec<f32> = (0..my)
            .map(|k| {
                let y_hat = ((-(my as i64) + 2 * k as i64) as f32 + 1.0) / 2.0;
                1.0f32 - (-(y_hat * y_hat) / two_sig2).exp()
            })
            .collect();
        let half = my / 2;
        (0..my).map(|i| damp[(i + half) % my] as f64).collect()
    }

    impl CudaFbpStream {
        /// Apply on-device stripe removal to the f32 sinogram at `ptr` (the valid
        /// `[nz, nproj, ncols]` prefix), in place. Returns `Ok(true)` when the
        /// method was handled on the device, `Ok(false)` when it has no GPU port
        /// (kept consistent with [`gpu_supports_stripe`]).
        fn stripe_on_device(
            &mut self,
            ptr: *mut c_void,
            nz: usize,
            stripe: StripeMethod,
        ) -> Result<bool> {
            let null = std::ptr::null_mut::<c_void>();
            match stripe {
                StripeMethod::None => Ok(true),
                // Titarenko, whole-sinogram (nblock=0). nblock>0 uses `_ringb`,
                // which is not ported — leave it to the host.
                StripeMethod::Ti { nblock: 0, beta } => {
                    if self.ti_scratch.is_none() {
                        let bytes = self.max_nz * 7 * self.ncols * std::mem::size_of::<f64>();
                        self.ti_scratch = Some(DevBuf::zeroed(bytes)?);
                    }
                    let scratch = self.ti_scratch.as_ref().expect("ti_scratch allocated");
                    ck(
                        unsafe {
                            ffi::tomoxide_stripe_ti(
                                ptr,
                                nz,
                                self.nproj,
                                self.ncols,
                                beta,
                                scratch.ptr,
                                null,
                            )
                        },
                        "stripe_ti",
                    )?;
                    Ok(true)
                }
                // Fourier-Wavelet. Multi-level db5 DWT/IDWT with per-column FFT
                // damping of the vertical band; orchestrated below.
                StripeMethod::Fw { sigma, level } => {
                    self.fw_on_device(ptr, nz, sigma, level)?;
                    Ok(true)
                }
                // Vo all-stripe (rs_dead → rs_sort). Window sizes are gated to
                // <= 256 by `gpu_supports_stripe`.
                StripeMethod::VoAll {
                    snr,
                    la_size,
                    sm_size,
                } => {
                    if self.vo_scratch.is_none() {
                        self.vo_scratch =
                            Some(VoScratch::new(self.max_nz, self.nproj, self.ncols)?);
                    }
                    let sc = self.vo_scratch.as_ref().expect("vo_scratch allocated");
                    self.vo_on_device(ptr, nz, snr, la_size, sm_size, sc)?;
                    Ok(true)
                }
                _ => Ok(false),
            }
        }

        /// Multi-level Fourier-Wavelet stripe removal on the device f32 sinogram
        /// `ptr [nz, nproj, ncol]`, mirroring `stripe::fw_slice` /
        /// `remove_stripe_fw` for all `nz` slices at once: db5 DWT/IDWT in f64
        /// (each band rounded to f32 like tomopy's `pywt` float32 pass) with the
        /// vertical-detail band damped column-wise via the f32 cuFFT shim. Held
        /// to correlation parity with the CPU golden, not bit-exactness.
        ///
        /// Per-call device buffers are allocated fresh (the band shapes depend on
        /// the chunk's `nz` through `level`); reuse/caching is a later
        /// optimization, not a correctness concern.
        fn fw_on_device(
            &self,
            ptr: *mut c_void,
            nz: usize,
            sigma: f32,
            level: Option<usize>,
        ) -> Result<()> {
            let null = std::ptr::null_mut::<c_void>();
            let (nproj, ncol) = (self.nproj, self.ncols);
            if nproj == 0 || nz == 0 || ncol == 0 {
                return Ok(());
            }
            // Auto-level matches the CPU golden: ceil(log2(max(nproj, nz, ncol))),
            // where the chunk's `nz` plays tomopy's `nrows`.
            let level = level.unwrap_or_else(|| {
                let size = nproj.max(nz).max(ncol);
                (size as f64).log2().ceil() as usize
            });
            if level == 0 {
                return Ok(());
            }
            let nx = nproj + nproj / 8; // pad=True
            let xshift = (nx - nproj) / 2;
            let f64sz = std::mem::size_of::<f64>();

            // approx = pad(sino) → f64 [nz, nx, ncol].
            let mut approx = DevBuf::new(nz * nx * ncol * f64sz)?;
            ck(
                unsafe { ffi::tomoxide_fw_pad(ptr, approx.ptr, nz, nproj, ncol, nx, xshift, null) },
                "fw_pad",
            )?;

            // Per-level detail bands (kept for the inverse pass) and their shapes.
            let mut chs: Vec<DevBuf> = Vec::with_capacity(level);
            let mut cvs: Vec<DevBuf> = Vec::with_capacity(level);
            let mut cds: Vec<DevBuf> = Vec::with_capacity(level);
            let mut dims: Vec<(usize, usize)> = Vec::with_capacity(level);

            // Reusable interleaved-complex scratch for the damping FFT, sized for
            // the largest band (level 0); smaller levels use a contiguous prefix.
            let or0 = (nx + 9) / 2;
            let oc0 = (ncol + 9) / 2;
            let cplx = DevBuf::new(nz * or0 * oc0 * 2 * std::mem::size_of::<f32>())?;

            // Forward: `level`-deep db5 decomposition (rows pass then cols pass),
            // each band rounded to f32, vertical band damped.
            let (mut r, mut c) = (nx, ncol);
            for _ in 0..level {
                let or = (r + 9) / 2;
                let oc = (c + 9) / 2;
                // Rows pass (last axis): approx[nz,r,c] → cols_a, cols_d [nz,r,oc].
                let cols_a = DevBuf::new(nz * r * oc * f64sz)?;
                let cols_d = DevBuf::new(nz * r * oc * f64sz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_dwt_rows(
                            approx.ptr, cols_a.ptr, cols_d.ptr, nz, r, c, null,
                        )
                    },
                    "fw_dwt_rows",
                )?;
                // Cols pass (middle axis): cols_a → ca,ch; cols_d → cv,cd [nz,or,oc].
                let ca = DevBuf::new(nz * or * oc * f64sz)?;
                let ch = DevBuf::new(nz * or * oc * f64sz)?;
                let cv = DevBuf::new(nz * or * oc * f64sz)?;
                let cd = DevBuf::new(nz * or * oc * f64sz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_dwt_cols(cols_a.ptr, ca.ptr, ch.ptr, nz, r, oc, null)
                    },
                    "fw_dwt_cols(approx)",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_dwt_cols(cols_d.ptr, cv.ptr, cd.ptr, nz, r, oc, null)
                    },
                    "fw_dwt_cols(detail)",
                )?;
                // Round every band to f32 (tomopy band quantization).
                let n_band = nz * or * oc;
                ck(
                    unsafe { ffi::tomoxide_fw_round(ca.ptr, n_band, null) },
                    "fw_round(ca)",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fw_round(ch.ptr, n_band, null) },
                    "fw_round(ch)",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fw_round(cv.ptr, n_band, null) },
                    "fw_round(cv)",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fw_round(cd.ptr, n_band, null) },
                    "fw_round(cd)",
                )?;
                // Damp the vertical-detail band cv along axis 0 (my=or, mx=oc):
                // real(ifft(fft(col) · D)), D = ifftshift(damp).
                let d = DevBuf::from_host_f64(&fw_damp_vector(or, sigma))?;
                ck(
                    unsafe { ffi::tomoxide_fw_damp_gather(cv.ptr, cplx.ptr, nz, or, oc, null) },
                    "fw_damp_gather",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_1d(cplx.ptr, or, nz * oc, 0) },
                    "fw_damp_fft_fwd",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fw_damp_apply(cplx.ptr, d.ptr, nz, or, oc, null) },
                    "fw_damp_apply",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_1d(cplx.ptr, or, nz * oc, 1) },
                    "fw_damp_fft_inv",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fw_damp_scatter(cplx.ptr, cv.ptr, nz, or, oc, null) },
                    "fw_damp_scatter",
                )?;

                chs.push(ch);
                cvs.push(cv);
                cds.push(cd);
                dims.push((or, oc));
                approx = ca; // running approximation for the next level
                r = or;
                c = oc;
            }

            // Inverse: crop the running approximation to each level's band shape,
            // then idwt2 (cols pass then rows pass) with the damped details.
            let mut sli = approx;
            let (mut sr, mut sc) = (r, c);
            for n in (0..level).rev() {
                let (or, oc) = dims[n];
                let cropped = DevBuf::new(nz * or * oc * f64sz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_crop(sli.ptr, cropped.ptr, nz, sr, sc, or, oc, null)
                    },
                    "fw_crop",
                )?;
                // idwt2 cols pass (middle axis): combine (ca,ch) and (cv,cd).
                let rr = 2 * or + 2 - 10;
                let cols_a = DevBuf::new(nz * rr * oc * f64sz)?;
                let cols_d = DevBuf::new(nz * rr * oc * f64sz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_idwt_cols(
                            cropped.ptr,
                            chs[n].ptr,
                            cols_a.ptr,
                            nz,
                            or,
                            oc,
                            null,
                        )
                    },
                    "fw_idwt_cols(approx)",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_idwt_cols(
                            cvs[n].ptr, cds[n].ptr, cols_d.ptr, nz, or, oc, null,
                        )
                    },
                    "fw_idwt_cols(detail)",
                )?;
                // idwt2 rows pass (last axis): combine the two column results.
                let rc_ = 2 * oc + 2 - 10;
                let out = DevBuf::new(nz * rr * rc_ * f64sz)?;
                ck(
                    unsafe {
                        ffi::tomoxide_fw_idwt_rows(
                            cols_a.ptr, cols_d.ptr, out.ptr, nz, rr, oc, null,
                        )
                    },
                    "fw_idwt_rows",
                )?;
                sli = out;
                sr = rr;
                sc = rc_;
            }

            // Crop back to the sinogram region → write f32 into `ptr` in place.
            ck(
                unsafe {
                    ffi::tomoxide_fw_final(sli.ptr, ptr, nz, nproj, ncol, sr, sc, xshift, null)
                },
                "fw_final",
            )?;
            Ok(())
        }

        /// `_detect_stripe` + `binary_dilation` for a per-column `listfact`
        /// `[nz, nc]`, writing the dilated mask. `border_zero` protects the two
        /// outer columns each side (the `_rs_dead` rule); `_rs_large` passes
        /// `false`.
        fn vo_detect_mask(
            &self,
            listfact: &DevBuf,
            mask: &DevBuf,
            nz: usize,
            snr: f32,
            border_zero: bool,
            sc: &VoScratch,
        ) -> Result<()> {
            let null = std::ptr::null_mut::<c_void>();
            let nc = self.ncols;
            let (sorted, rawmask) = (&sc.detsort, &sc.detraw);
            ck(
                unsafe { ffi::tomoxide_vo_slicesort(listfact.ptr, sorted.ptr, nz, nc, 0, null) },
                "vo_slicesort",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_vo_detect_rawmask(
                        listfact.ptr,
                        sorted.ptr,
                        rawmask.ptr,
                        nz,
                        nc,
                        snr,
                        null,
                    )
                },
                "vo_detect_rawmask",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_vo_dilate(
                        rawmask.ptr,
                        mask.ptr,
                        nz,
                        nc,
                        if border_zero { 1 } else { 0 },
                        null,
                    )
                },
                "vo_dilate",
            )?;
            Ok(())
        }

        /// `_rs_large` (Vo algorithm 5) on `s [nz,nrow,nc]` with `norm=true`:
        /// replace detected large-stripe columns with the rank-smoothed profile,
        /// normalising by the per-column intensity factor first. Writes the result
        /// into `sc.rl_out` (the caller's `dead_out`). `s` may alias `sc.big_a`;
        /// it is only read (never written) here, so the caller may reuse it after.
        fn vo_rs_large(
            &self,
            s: &DevBuf,
            nz: usize,
            snr: f32,
            size: usize,
            drop_ratio: f32,
            sc: &VoScratch,
        ) -> Result<()> {
            let null = std::ptr::null_mut::<c_void>();
            let (nrow, nc) = (self.nproj, self.ncols);
            let dr = drop_ratio.clamp(0.0, 0.8) as f64;
            let ndrop = (0.5 * dr * nrow as f64) as usize;

            // sinosort = sort each column ascending (perm unused here).
            let sinosort = &sc.rl_sort;
            ck(
                unsafe {
                    ffi::tomoxide_vo_colsort(s.ptr, sinosort.ptr, null, nz, nrow, nc, 1, null)
                },
                "vo_colsort(sinosort)",
            )?;
            // sinosmooth = per-row median along columns.
            let sinosmooth = &sc.rl_smooth;
            ck(
                unsafe {
                    ffi::tomoxide_vo_median_axis1(
                        sinosort.ptr,
                        sinosmooth.ptr,
                        nz,
                        nrow,
                        nc,
                        size,
                        null,
                    )
                },
                "vo_median(sinosmooth)",
            )?;
            // Per-column intensity factor (f64 for normalise, f32 for detect).
            ck(
                unsafe {
                    ffi::tomoxide_vo_rs_large_listfact(
                        sinosort.ptr,
                        sinosmooth.ptr,
                        sc.lf64.ptr,
                        sc.lf32.ptr,
                        nz,
                        nrow,
                        nc,
                        ndrop,
                        null,
                    )
                },
                "vo_rs_large_listfact",
            )?;
            // Mask (no border protection in _rs_large). `sinosort`/`rl_sort` is
            // now free; it is reused as `sortdummy` below.
            self.vo_detect_mask(&sc.lf32, &sc.mask_large, nz, snr, false, sc)?;
            // Normalised result, written straight into `rl_out`. colsort reads it
            // (without modifying it) for the permutation, then scatter_masked
            // overwrites only the masked columns in place — no seeding copy.
            let out = &sc.rl_out;
            ck(
                unsafe {
                    ffi::tomoxide_vo_normalize(s.ptr, sc.lf64.ptr, out.ptr, nz, nrow, nc, null)
                },
                "vo_normalize",
            )?;
            // Sort the normalised copy for its permutation (sorted values unused,
            // dumped into `rl_sort` which `sinosort` has finished with).
            ck(
                unsafe {
                    ffi::tomoxide_vo_colsort(
                        out.ptr,
                        sc.rl_sort.ptr,
                        sc.perm2.ptr,
                        nz,
                        nrow,
                        nc,
                        1,
                        null,
                    )
                },
                "vo_colsort(out)",
            )?;
            // Overwrite masked columns of `out` with the smoothed profile.
            ck(
                unsafe {
                    ffi::tomoxide_vo_scatter_masked(
                        sc.perm2.ptr,
                        sinosmooth.ptr,
                        sc.mask_large.ptr,
                        out.ptr,
                        nz,
                        nrow,
                        nc,
                        null,
                    )
                },
                "vo_scatter_masked",
            )?;
            Ok(())
        }

        /// Vo all-stripe removal on the device f32 sinogram `ptr [nz,nproj,ncol]`,
        /// in place: `_rs_dead` (uniform-smooth → per-column L1 diff → median →
        /// detect+dilate → border-protect → bilinear dead-column fill →
        /// `_rs_large`) followed by `_rs_sort` (column sort → cross-column median
        /// → unsort). Mirrors `stripe::remove_all_stripe` for all `nz` at once;
        /// correlation parity with the CPU golden.
        fn vo_on_device(
            &self,
            ptr: *mut c_void,
            nz: usize,
            snr: f32,
            la_size: usize,
            sm_size: usize,
            sc: &VoScratch,
        ) -> Result<()> {
            let null = std::ptr::null_mut::<c_void>();
            let (nrow, nc) = (self.nproj, self.ncols);
            // Matches the CPU guard in `remove_all_stripe`.
            if nrow < 2 || nz == 0 || nc < 4 || la_size == 0 || sm_size == 0 {
                return Ok(());
            }

            // ---- _rs_dead ----
            // sinosmooth = uniform_filter1d along the projection axis (size 10).
            let smooth = &sc.big_a;
            ck(
                unsafe { ffi::tomoxide_vo_uniform_axis0(ptr, smooth.ptr, nz, nrow, nc, 10, null) },
                "vo_uniform_axis0",
            )?;
            // listdiff[z,c] = sum_r |sino - smooth|.
            ck(
                unsafe {
                    ffi::tomoxide_vo_absdiff_colsum(
                        ptr,
                        smooth.ptr,
                        sc.listdiff.ptr,
                        nz,
                        nrow,
                        nc,
                        null,
                    )
                },
                "vo_absdiff_colsum",
            )?;
            // `smooth`/`big_a` is now free; it is reused as `work` then `sortedv`.
            // listdiffbck = 1-D median of listdiff over columns (window la_size).
            ck(
                unsafe {
                    ffi::tomoxide_vo_median_axis1(
                        sc.listdiff.ptr,
                        sc.listdiffbck.ptr,
                        nz,
                        1,
                        nc,
                        la_size,
                        null,
                    )
                },
                "vo_median(listdiffbck)",
            )?;
            // listfact = listdiff / listdiffbck.
            let cols = nz * nc;
            ck(
                unsafe {
                    ffi::tomoxide_vo_ratio(
                        sc.listdiff.ptr,
                        sc.listdiffbck.ptr,
                        sc.listfact.ptr,
                        cols,
                        null,
                    )
                },
                "vo_ratio(listfact)",
            )?;
            // Dead-column mask with border protection.
            self.vo_detect_mask(&sc.listfact, &sc.mask_dead, nz, snr, true, sc)?;
            // Good-column lists, then bilinear fill of the dead columns.
            ck(
                unsafe {
                    ffi::tomoxide_vo_build_goodx(
                        sc.mask_dead.ptr,
                        sc.goodx.ptr,
                        sc.goodcount.ptr,
                        nz,
                        nc,
                        null,
                    )
                },
                "vo_build_goodx",
            )?;
            // `work` (reusing `big_a`) is written in full by interp_fill (good
            // columns copied from `ptr`, dead columns interpolated) — no seed copy.
            let work = &sc.big_a;
            ck(
                unsafe {
                    ffi::tomoxide_vo_interp_fill(
                        ptr,
                        work.ptr,
                        sc.mask_dead.ptr,
                        sc.goodx.ptr,
                        sc.goodcount.ptr,
                        nz,
                        nrow,
                        nc,
                        null,
                    )
                },
                "vo_interp_fill",
            )?;
            // Residual large-stripe pass (VoAll always runs it, norm=True). Reads
            // `work` only; result lands in `sc.rl_out`.
            self.vo_rs_large(work, nz, snr, la_size, 0.1, sc)?;
            let dead_out = &sc.rl_out;

            // ---- _rs_sort (dim=1) ----
            // Sort each column ascending, keeping the permutation. `work`/`big_a`
            // is free now (rs_large only read it), so reuse it for `sortedv`.
            let sortedv = &sc.big_a;
            ck(
                unsafe {
                    ffi::tomoxide_vo_colsort(
                        dead_out.ptr,
                        sortedv.ptr,
                        sc.perm.ptr,
                        nz,
                        nrow,
                        nc,
                        1,
                        null,
                    )
                },
                "vo_colsort(rs_sort)",
            )?;
            // Smooth the sorted profiles across columns (window sm_size).
            let smoothed = &sc.big_b;
            ck(
                unsafe {
                    ffi::tomoxide_vo_median_axis1(
                        sortedv.ptr,
                        smoothed.ptr,
                        nz,
                        nrow,
                        nc,
                        sm_size,
                        null,
                    )
                },
                "vo_median(rs_sort)",
            )?;
            // Unsort back into the original projection order, in place into `ptr`.
            ck(
                unsafe {
                    ffi::tomoxide_vo_unsort_scatter(
                        sc.perm.ptr,
                        smoothed.ptr,
                        ptr,
                        nz,
                        nrow,
                        nc,
                        null,
                    )
                },
                "vo_unsort_scatter",
            )?;
            Ok(())
        }
    }

    /// Download an `[nz, n, n]` f32 volume from `src` through the handle's pinned
    /// staging buffer and move it into an owned [`Volume`] for the writer thread.
    ///
    /// The destination being page-locked is what matters: a D2H into pageable
    /// host memory is driver-staged at ~⅓ the PCIe rate (and is synchronous, so
    /// it cannot overlap kernels), whereas the pinned copy runs at full
    /// bandwidth. The volume must then move into an owned `Send` buffer so the
    /// pinned staging can be reused by the next chunk. A fresh allocation for
    /// that buffer pays ~190 ms of first-touch page-faults on a 536 MB chunk, so
    /// `pool` supplies a warm buffer recycled from the writer (see
    /// `give_reuse_buffer`); the copy into it is ~34 ms. The pool is empty for
    /// the first few chunks (nothing returned yet), which fall back to a fresh
    /// allocation.
    fn download_volume(
        src: &DevBuf,
        pin: &mut PinnedBuf<f32>,
        pool: &mut Vec<Vec<f32>>,
        nz: usize,
        n: usize,
    ) -> Result<Volume<f32>> {
        let count = nz * n * n;
        src.to_host_f32(&mut pin.as_mut_slice()[..count])?;
        // Reuse a warm buffer from the writer if one is available, else allocate.
        let mut host = pool.pop().unwrap_or_default();
        host.resize(count, 0.0);
        host.copy_from_slice(&pin.as_slice()[..count]);
        Ok(Volume::new(
            Array3::from_shape_vec((nz, n, n), host).expect("nz*n*n volume length matches shape"),
        ))
    }

    impl CudaFbpStream {
        /// Shared back half of both streaming entry points. `self.sino` already
        /// holds the chunk's sinogram for the valid `nz` rows (f16-cast when
        /// `self.f16`; the tail zeroed by the caller when `nz < max_nz`). Builds
        /// and uploads the per-chunk filter weights, then runs pad → cuFFT filter
        /// → crop → back-project at the handle's fixed `max_nz` batch and downloads
        /// the `[nz, n, n]` volume.
        fn finish_recon(&mut self, nz: usize, geom: &Geometry) -> Result<Volume<f32>> {
            let (nproj, ncols) = (self.nproj, self.ncols);
            let w_host = build_filter_w(&self.filter, geom, nz, ncols, self.pad);
            let null = std::ptr::null_mut::<c_void>();
            let partial = nz < self.max_nz;
            // `w` is the only buffer `finish_recon` fills partially; zero its tail on
            // a partial chunk so the fixed-batch cuFFT sees zeros there.
            if partial {
                ck(
                    unsafe { ffi::tomoxide_cuda_memset(self.w.ptr, 0, self.w.bytes) },
                    "memset w",
                )?;
            }
            if self.f16 {
                self.w.copy_from_host_f16(&w_host)?;
            } else {
                self.w.copy_from_host_f32(&w_host)?;
            }
            // pad → cuFFT filter → crop → back-project, all at the handle's `max_nz`
            // batch. `cfunc_linerec` accumulates into `f`, so zero it each chunk.
            let m = self.max_nz;
            let (pad, ps, n) = (self.pad, self.pad_side, self.n);
            if self.f16 {
                ck(
                    unsafe {
                        ffi::tomoxide_pad_fp16(
                            self.sino.ptr,
                            self.gpad.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "pad_fp16",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_filter_fp16_apply(self.filt, self.gpad.ptr, self.w.ptr, null)
                    },
                    "filter_fp16_apply",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_crop_fp16(
                            self.gpad.ptr,
                            self.gf.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "crop_fp16",
                )?;
                if self.fourier {
                    // f16 Fourierrec tail: pack pairs → `cfunc_fourierrec` (f16) →
                    // unpack, mirroring the f32 fourier branch and
                    // `analytic_fourierrec_f16` at the handle's `max_nz/2`-pair batch.
                    let gc = self.gc.as_ref().expect("fourier path has gc");
                    let fc = self.fc.as_ref().expect("fourier path has fc");
                    ck(
                        unsafe {
                            ffi::tomoxide_pack_pairs_fp16(
                                self.gf.ptr,
                                gc.ptr,
                                m,
                                nproj,
                                ncols,
                                null,
                            )
                        },
                        "pack_fp16",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_fourierrec_fp16_backproject(
                                self.frec, fc.ptr, gc.ptr, null,
                            )
                        },
                        "fourierrec_fp16_backproject",
                    )?;
                    ck(
                        unsafe { ffi::tomoxide_unpack_pairs_fp16(fc.ptr, self.f.ptr, m, n, null) },
                        "unpack_fp16",
                    )?;
                } else {
                    ck(
                        unsafe { ffi::tomoxide_cuda_memset(self.f.ptr, 0, self.f.bytes) },
                        "memset f f16",
                    )?;
                    unsafe {
                        ck(
                            ffi::tomoxide_linerec_fp16_backproject(
                                self.lrec,
                                self.f.ptr,
                                self.gf.ptr,
                                self.theta.ptr as *const f32,
                                std::f32::consts::FRAC_PI_2,
                                (self.n / 2) as f32, // centred sinogram: axis = n/2
                                std::f32::consts::PI / nproj as f32, // FBP dθ weight
                                0,
                                self.max_nz as i32, // parallel: rh == the handle's nz
                                null,
                            ),
                            "linerec_fp16_backproject",
                        )?;
                    }
                }
                // Cast the f16 volume to f32 on the GPU, then D2H f32 (no host widen).
                let f_f32 = self.f_f32.as_ref().expect("f16 path has f_f32");
                ck(
                    unsafe {
                        ffi::tomoxide_cast_f16_to_f32(self.f.ptr, f_f32.ptr, nz * n * n, null)
                    },
                    "cast f16->f32 vol",
                )?;
                ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
                download_volume(f_f32, &mut self.out_pinned, &mut self.reuse_pool, nz, n)
            } else if self.lprec.is_some() {
                // Device-resident log-polar (f32): same pad → filter → crop as the
                // FBP tail produces the filtered sinogram in `gf`; the held
                // `LpRecDev` runtime (grids built once, reused across chunks) then
                // does spline prefilter → per-span gather/FFT/scatter into `f`.
                ck(
                    unsafe {
                        ffi::tomoxide_pad(
                            self.sino.ptr,
                            self.gpad.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "pad",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_filter_apply(self.filt, self.gpad.ptr, self.w.ptr, null)
                    },
                    "filter_apply",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_crop(
                            self.gpad.ptr,
                            self.gf.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "crop",
                )?;
                // The scatter accumulates over spans, so zero the output first.
                ck(
                    unsafe { ffi::tomoxide_cuda_memset(self.f.ptr, 0, self.f.bytes) },
                    "memset f",
                )?;
                let lp = self.lprec.as_ref().expect("lprec path has grids");
                let flc = self.flc.as_ref().expect("lprec path has flc");
                lp.run(self.gf.ptr, flc.ptr, self.f.ptr, nz, nproj, n)?;
                ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
                download_volume(&self.f, &mut self.out_pinned, &mut self.reuse_pool, nz, n)
            } else if self.fourier {
                // Device-resident Fourierrec (f32): same pad → filter → crop as the
                // FBP tail, then pack pairs → `cfunc_fourierrec` → unpack, mirroring
                // `analytic_fourierrec` but at the handle's fixed `max_nz` batch
                // (the `max_nz/2`-pair handle reuses the cuFFT plans across chunks).
                let gc = self.gc.as_ref().expect("fourier path has gc");
                let fc = self.fc.as_ref().expect("fourier path has fc");
                ck(
                    unsafe {
                        ffi::tomoxide_pad(
                            self.sino.ptr,
                            self.gpad.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "pad",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_filter_apply(self.filt, self.gpad.ptr, self.w.ptr, null)
                    },
                    "filter_apply",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_crop(
                            self.gpad.ptr,
                            self.gf.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "crop",
                )?;
                ck(
                    unsafe { ffi::tomoxide_pack_pairs(self.gf.ptr, gc.ptr, m, nproj, ncols, null) },
                    "pack",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_fourierrec_backproject(self.frec, fc.ptr, gc.ptr, null)
                    },
                    "fourierrec_backproject",
                )?;
                ck(
                    unsafe { ffi::tomoxide_unpack_pairs(fc.ptr, self.f.ptr, m, n, null) },
                    "unpack",
                )?;
                ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
                download_volume(&self.f, &mut self.out_pinned, &mut self.reuse_pool, nz, n)
            } else {
                ck(
                    unsafe {
                        ffi::tomoxide_pad(
                            self.sino.ptr,
                            self.gpad.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "pad",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_filter_apply(self.filt, self.gpad.ptr, self.w.ptr, null)
                    },
                    "filter_apply",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_crop(
                            self.gpad.ptr,
                            self.gf.ptr,
                            m,
                            nproj,
                            ncols,
                            pad,
                            ps,
                            null,
                        )
                    },
                    "crop",
                )?;
                ck(
                    unsafe { ffi::tomoxide_cuda_memset(self.f.ptr, 0, self.f.bytes) },
                    "memset f",
                )?;
                unsafe {
                    ck(
                        ffi::tomoxide_linerec_backproject(
                            self.lrec,
                            self.f.ptr,
                            self.gf.ptr,
                            self.theta.ptr as *const f32,
                            std::f32::consts::FRAC_PI_2,
                            (self.n / 2) as f32, // centred sinogram: axis = n/2
                            std::f32::consts::PI / nproj as f32, // FBP dθ weight
                            0,
                            self.max_nz as i32, // parallel: rh == the handle's nz
                            null,
                        ),
                        "linerec_backproject",
                    )?;
                }
                ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
                download_volume(&self.f, &mut self.out_pinned, &mut self.reuse_pool, nz, n)
            }
        }
    }

    /// State for one double-buffer slot of the async FBP pipeline: its own stream,
    /// device buffers sized to the largest chunk, pinned host staging for the
    /// sino-in / filter-weight / volume-out copies, and the per-chunk `cfunc_*`
    /// handles plus the chunk index currently in flight (released on drain).
    struct FbpSlot {
        stream: Stream,
        sino: DevBuf,
        gpad: DevBuf,
        gf: DevBuf,
        f: DevBuf,
        w: DevBuf,
        pin_in: PinnedBuf,
        pin_w: PinnedBuf,
        pin_out: PinnedBuf,
        inflight: Option<usize>,
        filt: Option<Handle>,
        lrec: Option<Handle>,
    }

    /// Asynchronous, double-buffered Fbp/Linerec back-projection over `chunks`
    /// (each `(z0, len)`, `len ≥ 2`), implementing the tomocupy JSR 2023 (Fig. 1)
    /// overlap: while chunk *k* computes on the GPU, chunk *k+1* is being uploaded
    /// (H2D) and chunk *k−1* downloaded (D2H). Two slots (`k % 2`) ping-pong; each
    /// slot's whole `H2D → pad → filter → crop → linerec → D2H` sequence runs on
    /// its own stream (ordering the data dependency), and the two streams plus
    /// pinned host staging let the copy engines and the SMs run concurrently.
    /// Numerically equivalent to [`analytic_fbp_chunk`] per chunk, so the result
    /// matches the sequential tiled path to the single-precision FFT floor.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fbp_pipeline(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        chunks: &[(usize, usize)],
        nz_total: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let nfreq2 = (pad / 2 + 1) * 2;
        let maxlen = chunks.iter().map(|&(_, l)| l).max().unwrap_or(0);
        if maxlen == 0 {
            return Ok(Vec::new());
        }
        // theta is read-only and shared by both streams — upload once.
        let theta_dev = DevBuf::from_host_f32(theta)?;

        let mut slots: Vec<FbpSlot> = Vec::with_capacity(2);
        for _ in 0..2 {
            slots.push(FbpSlot {
                stream: Stream::new()?,
                sino: DevBuf::new(maxlen * nproj * ncols * fsz)?,
                gpad: DevBuf::new(maxlen * nproj * pad * fsz)?,
                gf: DevBuf::new(maxlen * nproj * ncols * fsz)?,
                f: DevBuf::new(maxlen * n * n * fsz)?,
                w: DevBuf::new(maxlen * nfreq2 * fsz)?,
                pin_in: PinnedBuf::new(maxlen * nproj * ncols)?,
                pin_w: PinnedBuf::new(maxlen * nfreq2)?,
                pin_out: PinnedBuf::new(maxlen * n * n)?,
                inflight: None,
                filt: None,
                lrec: None,
            });
        }

        let mut out = vec![0.0f32; nz_total * n * n];

        for k in 0..chunks.len() {
            let s = k % 2;
            // Drain the chunk that previously held this slot (k−2): wait for its
            // stream, free its handles, copy its downloaded volume out — then the
            // buffers are free to reuse.
            if let Some(ci) = slots[s].inflight.take() {
                drain_fbp_slot(&mut slots[s], ci, chunks, n, &mut out)?;
            }

            let (z0, len) = chunks[k];
            let st = slots[s].stream.ptr;
            // Stage host inputs into this slot's pinned buffers (host→host).
            slots[s].pin_in.as_mut_slice()[..len * nproj * ncols]
                .copy_from_slice(&raw[z0 * nproj * ncols..(z0 + len) * nproj * ncols]);
            slots[s].pin_w.as_mut_slice()[..len * nfreq2]
                .copy_from_slice(&w[z0 * nfreq2..(z0 + len) * nfreq2]);

            // Async H2D, then the kernel chain, then async D2H — all ordered on the
            // slot's stream (intra-chunk dependency); cross-chunk overlap comes from
            // the other slot running on its own stream.
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_h2d_async(
                        slots[s].sino.ptr,
                        slots[s].pin_in.ptr,
                        len * nproj * ncols * fsz,
                        st,
                    )
                },
                "h2d sino",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_h2d_async(
                        slots[s].w.ptr,
                        slots[s].pin_w.ptr,
                        len * nfreq2 * fsz,
                        st,
                    )
                },
                "h2d w",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_pad(
                        slots[s].sino.ptr,
                        slots[s].gpad.ptr,
                        len,
                        nproj,
                        ncols,
                        pad,
                        pad_side,
                        st,
                    )
                },
                "pad",
            )?;
            let filt = slots[s]
                .filt
                .insert(Handle::new(
                    unsafe { ffi::tomoxide_filter_new(nproj, len, pad) },
                    ffi::tomoxide_filter_free,
                    "cfunc_filter",
                )?)
                .ptr;
            ck(
                unsafe { ffi::tomoxide_filter_apply(filt, slots[s].gpad.ptr, slots[s].w.ptr, st) },
                "filter_apply",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_crop(
                        slots[s].gpad.ptr,
                        slots[s].gf.ptr,
                        len,
                        nproj,
                        ncols,
                        pad,
                        pad_side,
                        st,
                    )
                },
                "crop",
            )?;
            // linerec accumulates into `f`, so zero it first (on the stream).
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memset_async(slots[s].f.ptr, 0, len * n * n * fsz, st)
                },
                "memset f",
            )?;
            let lrec = slots[s]
                .lrec
                .insert(Handle::new(
                    unsafe { ffi::tomoxide_linerec_new(nproj, len, n, nproj, len) },
                    ffi::tomoxide_linerec_free,
                    "cfunc_linerec",
                )?)
                .ptr;
            unsafe {
                ck(
                    ffi::tomoxide_linerec_backproject(
                        lrec,
                        slots[s].f.ptr,
                        slots[s].gf.ptr,
                        theta_dev.ptr as *const f32,
                        std::f32::consts::FRAC_PI_2,
                        (n / 2) as f32, // centred sinogram: axis = n/2
                        std::f32::consts::PI / nproj as f32, // FBP dθ weight
                        0,
                        len as i32, // parallel: rh == the chunk's nz
                        st,
                    ),
                    "linerec_backproject",
                )?;
            }
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_d2h_async(
                        slots[s].pin_out.ptr,
                        slots[s].f.ptr,
                        len * n * n * fsz,
                        st,
                    )
                },
                "d2h vol",
            )?;
            slots[s].inflight = Some(k);
        }

        // Drain the last (≤2) in-flight chunks.
        for slot in &mut slots {
            if let Some(ci) = slot.inflight.take() {
                drain_fbp_slot(slot, ci, chunks, n, &mut out)?;
            }
        }
        Ok(out)
    }

    /// Finish the chunk in flight on `slot`: wait for its stream, free its
    /// per-chunk `cfunc_*` handles, and copy its downloaded volume from pinned
    /// host memory into `out` at the chunk's z-range.
    fn drain_fbp_slot(
        slot: &mut FbpSlot,
        ci: usize,
        chunks: &[(usize, usize)],
        n: usize,
        out: &mut [f32],
    ) -> Result<()> {
        slot.stream.sync()?;
        slot.filt = None;
        slot.lrec = None;
        let (z0, len) = chunks[ci];
        out[z0 * n * n..(z0 + len) * n * n]
            .copy_from_slice(&slot.pin_out.as_slice()[..len * n * n]);
        Ok(())
    }

    /// Memory-safe driver for the fused Fbp/Linerec path: split the z-stack into
    /// tiles sized by [`fbp_tile_z`] (free device memory + the 32-bit index
    /// ceiling) and run [`analytic_fbp_chunk`] on each, concatenating the volumes.
    /// When the whole stack already fits in one tile this is a single chunk call
    /// (numerically identical to the un-streamed path). When it tiles, the cuFFT
    /// filter batch becomes the tile size, so — like the multi-GPU split — the
    /// result shifts at the single-precision FFT floor (~1e-7) and, since the
    /// tile size tracks free device memory, is not bit-reproducible across hosts
    /// with different free memory. The current device must already be selected.
    /// Returns the volume `[nz, n, n]`.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fbp_stream(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        // Whole stack fits in one tile at the full memory budget → no tiling and
        // no pipeline; one chunk, byte-identical to the un-streamed path.
        let tile_full = fbp_tile_z(nproj, ncols, n, pad, device_free_bytes(), false).min(nz.max(1));
        if tile_full >= nz {
            return analytic_fbp_chunk(raw, w, theta, nz, nproj, ncols, n, pad, pad_side);
        }
        // Tiling is needed. Size chunks so TWO are resident (half the memory
        // budget) and run them through the async H2D∥compute∥D2H pipeline. Chunks
        // are an even split that stays ≥2 slices (the cfunc_linerec invariant) —
        // a greedy `[tile, …, 1]` tail would silently zero its last slice.
        let tile = fbp_tile_z(nproj, ncols, n, pad, device_free_bytes() / 2, false).min(nz.max(1));
        let k = linerec_chunk_count(nz, nz.div_ceil(tile));
        let chunks = even_z_chunks(nz, k);
        analytic_fbp_pipeline(raw, w, theta, &chunks, nz, nproj, ncols, n, pad, pad_side)
    }

    /// f16 counterpart of [`FbpSlot`]: half device + pinned buffers. `theta` is
    /// shared (uploaded once) and stays f32, so it is not a slot field.
    struct FbpSlotF16 {
        stream: Stream,
        sino: DevBuf,
        gpad: DevBuf,
        gf: DevBuf,
        f: DevBuf,
        w: DevBuf,
        pin_in: PinnedBuf<half::f16>,
        pin_w: PinnedBuf<half::f16>,
        pin_out: PinnedBuf<half::f16>,
        inflight: Option<usize>,
        filt: Option<Handle>,
        lrec: Option<Handle>,
    }

    /// Half-precision counterpart of [`analytic_fbp_pipeline`]. Same double-
    /// buffered H2D∥compute∥D2H overlap, but device/pinned buffers are `f16` and
    /// the per-chunk host staging *converts* (f32→f16 into the pinned input, and
    /// f16→f32 out of the pinned output on drain). Those conversions — the single
    /// largest host cost of the f16 path — run on CPU worker threads while a
    /// previous chunk's kernels run on the GPU, so together with the halved
    /// transfers they are hidden behind compute. Numerically equal per chunk to
    /// [`analytic_fbp_chunk_f16`] (correlation vs f32, not bit-exact).
    #[allow(clippy::too_many_arguments)]
    fn analytic_fbp_pipeline_f16(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        chunks: &[(usize, usize)],
        nz_total: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let hsz = std::mem::size_of::<half::f16>();
        let nfreq2 = (pad / 2 + 1) * 2;
        let maxlen = chunks.iter().map(|&(_, l)| l).max().unwrap_or(0);
        if maxlen == 0 {
            return Ok(Vec::new());
        }
        let theta_dev = DevBuf::from_host_f32(theta)?;

        let mut slots: Vec<FbpSlotF16> = Vec::with_capacity(2);
        for _ in 0..2 {
            slots.push(FbpSlotF16 {
                stream: Stream::new()?,
                sino: DevBuf::new(maxlen * nproj * ncols * hsz)?,
                gpad: DevBuf::new(maxlen * nproj * pad * hsz)?,
                gf: DevBuf::new(maxlen * nproj * ncols * hsz)?,
                f: DevBuf::new(maxlen * n * n * hsz)?,
                w: DevBuf::new(maxlen * nfreq2 * hsz)?,
                pin_in: PinnedBuf::new(maxlen * nproj * ncols)?,
                pin_w: PinnedBuf::new(maxlen * nfreq2)?,
                pin_out: PinnedBuf::new(maxlen * n * n)?,
                inflight: None,
                filt: None,
                lrec: None,
            });
        }

        let mut out = vec![0.0f32; nz_total * n * n];

        for k in 0..chunks.len() {
            let s = k % 2;
            if let Some(ci) = slots[s].inflight.take() {
                drain_fbp_slot_f16(&mut slots[s], ci, chunks, n, &mut out)?;
            }

            let (z0, len) = chunks[k];
            let st = slots[s].stream.ptr;
            // Stage host inputs into pinned buffers, converting f32→f16 in
            // parallel. This runs while the other slot's chunk computes on the GPU.
            {
                let src = &raw[z0 * nproj * ncols..(z0 + len) * nproj * ncols];
                slots[s].pin_in.as_mut_slice()[..len * nproj * ncols]
                    .par_iter_mut()
                    .zip(src.par_iter())
                    .for_each(|(d, &x)| *d = half::f16::from_f32(x));
                let srcw = &w[z0 * nfreq2..(z0 + len) * nfreq2];
                slots[s].pin_w.as_mut_slice()[..len * nfreq2]
                    .par_iter_mut()
                    .zip(srcw.par_iter())
                    .for_each(|(d, &x)| *d = half::f16::from_f32(x));
            }

            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_h2d_async(
                        slots[s].sino.ptr,
                        slots[s].pin_in.ptr,
                        len * nproj * ncols * hsz,
                        st,
                    )
                },
                "h2d sino f16",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_h2d_async(
                        slots[s].w.ptr,
                        slots[s].pin_w.ptr,
                        len * nfreq2 * hsz,
                        st,
                    )
                },
                "h2d w f16",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_pad_fp16(
                        slots[s].sino.ptr,
                        slots[s].gpad.ptr,
                        len,
                        nproj,
                        ncols,
                        pad,
                        pad_side,
                        st,
                    )
                },
                "pad_fp16",
            )?;
            let filt = slots[s]
                .filt
                .insert(Handle::new(
                    unsafe { ffi::tomoxide_filter_fp16_new(nproj, len, pad) },
                    ffi::tomoxide_filter_fp16_free,
                    "cfunc_filter (f16)",
                )?)
                .ptr;
            ck(
                unsafe {
                    ffi::tomoxide_filter_fp16_apply(filt, slots[s].gpad.ptr, slots[s].w.ptr, st)
                },
                "filter_fp16_apply",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_crop_fp16(
                        slots[s].gpad.ptr,
                        slots[s].gf.ptr,
                        len,
                        nproj,
                        ncols,
                        pad,
                        pad_side,
                        st,
                    )
                },
                "crop_fp16",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memset_async(slots[s].f.ptr, 0, len * n * n * hsz, st)
                },
                "memset f f16",
            )?;
            let lrec = slots[s]
                .lrec
                .insert(Handle::new(
                    unsafe { ffi::tomoxide_linerec_fp16_new(nproj, len, n, nproj, len) },
                    ffi::tomoxide_linerec_fp16_free,
                    "cfunc_linerec (f16)",
                )?)
                .ptr;
            unsafe {
                ck(
                    ffi::tomoxide_linerec_fp16_backproject(
                        lrec,
                        slots[s].f.ptr,
                        slots[s].gf.ptr,
                        theta_dev.ptr as *const f32,
                        std::f32::consts::FRAC_PI_2,
                        (n / 2) as f32, // centred sinogram: axis = n/2
                        std::f32::consts::PI / nproj as f32, // FBP dθ weight
                        0,
                        len as i32, // parallel: rh == the chunk's nz
                        st,
                    ),
                    "linerec_fp16_backproject",
                )?;
            }
            ck(
                unsafe {
                    ffi::tomoxide_cuda_memcpy_d2h_async(
                        slots[s].pin_out.ptr,
                        slots[s].f.ptr,
                        len * n * n * hsz,
                        st,
                    )
                },
                "d2h vol f16",
            )?;
            slots[s].inflight = Some(k);
        }

        for slot in &mut slots {
            if let Some(ci) = slot.inflight.take() {
                drain_fbp_slot_f16(slot, ci, chunks, n, &mut out)?;
            }
        }
        Ok(out)
    }

    /// f16 counterpart of [`drain_fbp_slot`]: wait for the slot's stream, free its
    /// per-chunk handles, then widen its downloaded f16 volume into `out` (the
    /// f16→f32 round runs in parallel and overlaps later chunks' GPU work).
    fn drain_fbp_slot_f16(
        slot: &mut FbpSlotF16,
        ci: usize,
        chunks: &[(usize, usize)],
        n: usize,
        out: &mut [f32],
    ) -> Result<()> {
        slot.stream.sync()?;
        slot.filt = None;
        slot.lrec = None;
        let (z0, len) = chunks[ci];
        out[z0 * n * n..(z0 + len) * n * n]
            .par_iter_mut()
            .zip(slot.pin_out.as_slice()[..len * n * n].par_iter())
            .for_each(|(d, &h)| *d = h.to_f32());
        Ok(())
    }

    /// f16 driver for the fused Fbp/Linerec path, mirroring [`analytic_fbp_stream`]:
    /// when the whole stack fits one tile, a single [`analytic_fbp_chunk_f16`] —
    /// the fastest path, since the GPU back-projection (memory-bandwidth bound, so
    /// already ~2× faster in half) dominates and forcing tiles would only add
    /// per-tile cuFFT-plan and pinned-allocation overhead. Only when the stack is
    /// genuinely out-of-core does it tile and run the async pipeline, which there
    /// lets f16 process a z-stack 2× larger than f32 would before tiling. The
    /// current device must be selected.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fbp_stream_f16(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        // f16 elements are half the bytes of the f32 sizing `fbp_tile_z` assumes,
        // so double the budget handed to it; its 32-bit index ceiling is
        // element-count based and dtype-independent.
        let budget = device_free_bytes().saturating_mul(2);
        let tile_full = fbp_tile_z(nproj, ncols, n, pad, budget, true).min(nz.max(1));
        if tile_full >= nz {
            return analytic_fbp_chunk_f16(raw, w, theta, nz, nproj, ncols, n, pad, pad_side);
        }
        let tile = fbp_tile_z(nproj, ncols, n, pad, budget / 2, true).min(nz.max(1));
        let k = linerec_chunk_count(nz, nz.div_ceil(tile));
        let chunks = even_z_chunks(nz, k);
        analytic_fbp_pipeline_f16(raw, w, theta, &chunks, nz, nproj, ncols, n, pad, pad_side)
    }

    /// Pad → cuFFT filter → crop → pack pairs → `cfunc_fourierrec` → unpack for
    /// the whole stack on the **current** device. Returns the volume `[nz, n, n]`.
    ///
    /// Single-device only, by design. tomocupy's `gather`/`wrap` kernels scatter
    /// onto the oversampled grid with `atomicAdd` (overlapping Gaussian stencils),
    /// so float accumulation order — hence the low bits of the output — is
    /// **run-to-run nondeterministic** (~1e-7 relative, single-precision floor;
    /// the result is correlation-verified against the CPU `fourierrec`, not
    /// bit-exact). Because the output is already nondeterministic and the complex
    /// slice-pairing `(s, s+nz/2)` spans the whole z-axis, a multi-GPU split would
    /// add complexity without a verifiable benefit, so it is deliberately not
    /// done. Determinizing the gather would need a pull-based rewrite (no inverse
    /// index ⇒ O(n³·nproj) per grid point) that would also break parity with the
    /// vendored kernel; out of scope for this port.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fourierrec(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();
        let sino_dev = DevBuf::from_host_f32(raw)?;
        let w_dev = DevBuf::from_host_f32(w)?;
        let theta_dev = DevBuf::from_host_f32(theta)?;
        let gpad = DevBuf::zeroed(nz * nproj * pad * fsz)?;
        ck(
            unsafe {
                ffi::tomoxide_pad(
                    sino_dev.ptr,
                    gpad.ptr,
                    nz,
                    nproj,
                    ncols,
                    pad,
                    pad_side,
                    null,
                )
            },
            "pad",
        )?;
        let fh = Handle::new(
            unsafe { ffi::tomoxide_filter_new(nproj, nz, pad) },
            ffi::tomoxide_filter_free,
            "cfunc_filter",
        )?;
        ck(
            unsafe { ffi::tomoxide_filter_apply(fh.ptr, gpad.ptr, w_dev.ptr, null) },
            "filter_apply",
        )?;
        drop(fh);
        let gf = DevBuf::zeroed(nz * nproj * ncols * fsz)?;
        ck(
            unsafe { ffi::tomoxide_crop(gpad.ptr, gf.ptr, nz, nproj, ncols, pad, pad_side, null) },
            "crop",
        )?;
        let gc = DevBuf::zeroed(nz * nproj * ncols * fsz)?; // complex [nz/2,nproj,ncols]
        ck(
            unsafe { ffi::tomoxide_pack_pairs(gf.ptr, gc.ptr, nz, nproj, ncols, null) },
            "pack",
        )?;
        let fc = DevBuf::zeroed(nz * n * n * fsz)?; // complex [nz/2,n,n]
        let h = Handle::new(
            unsafe { ffi::tomoxide_fourierrec_new(nproj, nz / 2, n, theta_dev.ptr as *const f32) },
            ffi::tomoxide_fourierrec_free,
            "cfunc_fourierrec",
        )?;
        ck(
            unsafe { ffi::tomoxide_fourierrec_backproject(h.ptr, fc.ptr, gc.ptr, null) },
            "fourierrec_backproject",
        )?;
        drop(h);
        let vol_dev = DevBuf::zeroed(nz * n * n * fsz)?;
        ck(
            unsafe { ffi::tomoxide_unpack_pairs(fc.ptr, vol_dev.ptr, nz, n, null) },
            "unpack",
        )?;
        ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        let mut host = vec![0.0f32; nz * n * n];
        vol_dev.to_host_f32(&mut host)?;
        Ok(host)
    }

    /// Gaussian-USFFT half-width `m` and shape `mu` (tomocupy `EPS = 1e-3`),
    /// identical to `recon::lamino::usfft_params` so the GPU grids match the CPU
    /// golden exactly.
    fn lam_usfft_params(n: usize) -> (usize, f32) {
        let nf = n as f64;
        let neg_log_eps = -(1e-3_f64).ln();
        let mu = neg_log_eps / (2.0 * nf * nf);
        let inside = mu * neg_log_eps + (mu * nf) * (mu * nf) / 4.0;
        let m = (2.0 * nf / std::f64::consts::PI * inside.sqrt()).ceil() as usize;
        (m, mu as f32)
    }

    /// Device-resident Fourier/USFFT laminography (tomocupy `LamFourierRec`) — a
    /// full-complex GPU mirror of the CPU golden [`crate::recon::lamino::lamino`].
    /// The gridding + modulation stages run as the `tomoxide_lam_*` kernels and
    /// the FFTs reuse the device-resident `tomoxide_fft_1d/2d`, so the whole
    /// pipeline stays on the GPU. `proj` is `[nproj, deth, detw]` (projection
    /// layout, `detw == n`); returns the volume `[rh, n, n]`.
    ///
    /// Whole-volume (no streaming / no R2C-half), like the CPU port: the
    /// oversampled `(x,y)` grid `fdee2 [deth, gy, gx]` dominates VRAM, so this is
    /// bounded to grids that fit one device (≈ ≤512³ on a 16 GB card). Chunking to
    /// production scale (tomocupy's deth/ntheta/n1 streaming) is a follow-up.
    #[allow(clippy::too_many_arguments)]
    /// Streaming (chunked) Fourier/USFFT laminography, mirroring tomocupy's
    /// `BackprojLamFourierParallel` memory model: the full spectra (`p22`, `p11`)
    /// and output (`p00`) live in **host** RAM, and only chunk-sized slabs of the
    /// oversampled USFFT grids are ever resident on the GPU. This bounds peak VRAM
    /// to a fraction of a single grid (the whole-volume `fdee2` alone is ~30 GB at
    /// 1024², which no 32 GB card can hold). Each stage chunks along its own
    /// independent axis:
    ///   - stage 1 (ramp + centered 2-D FFT): over projections (`ntheta`),
    ///   - stage 2 (usfft2d_adj): over depth-frequency slices (`deth`/`nky`),
    ///   - stage 3 (usfft1d_adj): over the y-frequency rows (`n1`).
    ///
    /// `center` is applied in the ramp as tomocupy's `fbp_filter_center` linear
    /// phase (`shift = detw/2 - center`); `center == detw/2` ⇒ `shift == 0` and the
    /// result is bit-identical to the earlier whole-volume path (the golden anchor).
    ///
    /// This host-resident path bounds peak VRAM to a fraction of one grid but pays
    /// full-volume PCIe (`p22`/`p11`/`p00` shuttle host↔device between stages),
    /// leaving the GPU idle during transfers. When the spectra fit in VRAM,
    /// [`analytic_lamino_fourierrec_device`] keeps them resident and is preferred;
    /// the dispatcher [`analytic_lamino_fourierrec`] chooses between them.
    ///
    /// Fixed per-call parameters common to the three lamino-fourierrec entry
    /// points (everything but the projection data and the optional fused
    /// normalization): the tilt `phi`, the square grid `n`, the recon height
    /// `rh`, the rotation `center`, and the FBP apodisation `filter`.
    #[derive(Clone, Copy)]
    struct LamFourierParams {
        phi: f32,
        n: usize,
        rh: usize,
        center: f32,
        filter: FilterName,
    }

    fn analytic_lamino_fourierrec_host(
        proj: &[f32],
        theta: &[f32],
        p: LamFourierParams,
        norm: Option<&super::LamNorm>,
        cancel: Option<&CancelToken>,
        on_tile: &mut super::LaminoTileFn,
    ) -> Result<()> {
        let LamFourierParams {
            phi,
            n,
            rh,
            center,
            filter,
        } = p;
        let csz = 2 * std::mem::size_of::<f32>(); // bytes per complex
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();

        let nproj = theta.len();
        let detw = n;
        let deth = proj.len() / (nproj * n);
        if proj.len() != nproj * deth * detw {
            return Err(Error::InvalidParam(
                "lamino fourierrec: proj shape != [nproj, nz, n]".into(),
            ));
        }
        // usfft2d in-plane params (n0 = detw = n, n1 = n) and usfft1d depth params.
        let (n0, n1) = (detw, n);
        let (m0, mu0) = lam_usfft_params(n0);
        let (m1, mu1) = lam_usfft_params(n1);
        let (m2, mu2) = lam_usfft_params(rh);
        let gx = 2 * n0 + 2 * m0;
        let gy = 2 * n1 + 2 * m1;
        let ng = 2 * rh + 2 * m2;
        let (filt, pad) = crate::recon::lamino::projection_filter(filter, detw)?;
        let ne = filt.len();
        let shift = detw as f32 / 2.0 - center; // rotation-center linear phase

        let theta_dev = DevBuf::from_host_f32(theta)?;
        // FBP filter weights (ramp × apodisation window), uploaded once and
        // reused across every theta-chunk's stage-1 ramp multiply.
        let filt_dev = DevBuf::from_host_f32(&filt)?;

        // Per-chunk device footprint bounds the chunk count to ≤30% of free VRAM.
        // The conveyor double-buffers each stage's streamed input and output slab
        // (a copy stream uploads chunk ci+1 / drains chunk ci-1 while ci computes),
        // so those two slabs are counted twice; the compute scratch is single.
        let budget = (device_free_bytes() / 100 * 30).max(1);
        // stage 1: 2×dev_in (real) + rbuf + 2×dev_out (complex).
        let per_theta = 2 * deth * detw * fsz + deth * ne * csz + 2 * deth * detw * csz;
        let nthetac = (budget / per_theta.max(1)).clamp(1, nproj);
        // stage 2: 2×g_dev + xs/ys + fdee2 + win + 2×f11.
        let per_ky = gy * gx * csz
            + (2 * n1) * (2 * n0) * csz
            + 2 * n1 * n0 * csz
            + 2 * nproj * detw * csz
            + 2 * nproj * detw * fsz;
        let dethc = (budget / per_ky.max(1)).clamp(1, deth);
        // stage 3: 2×g_dev + fdee1 + lines + 2×f00.
        let per_ty = ng * n0 * csz + n0 * (2 * rh) * csz + 2 * deth * n0 * csz + 2 * rh * n0 * fsz;
        let n1c = (budget / per_ty.max(1)).clamp(1, n1);

        // Host-resident spectra / output (complex stored as interleaved f32 pairs).
        let mut p22 = vec![0.0f32; nproj * deth * detw * 2]; // [nproj, deth, detw]
        let mut p11 = vec![0.0f32; n1 * deth * n0 * 2]; // [n1, deth, n0]
        let mut p00 = vec![0.0f32; n1 * rh * n0]; // [n1, rh, n0] real

        // Per-stage chunk plans (each axis is independent; last chunk may be short).
        let chunks1 = chunk_ranges(nproj, nthetac);
        let chunks2 = chunk_ranges(deth, dethc);
        let chunks3 = chunk_ranges(n1, n1c);

        // --- stage 1: ramp_filter_center + centered 2-D FFT, chunked over ntheta ---
        // prep uploads a contiguous [tc, deth, detw] projection slab; compute runs the
        // ramp+2-D FFT in place; finalize stores the [tc, deth, detw] p22 slab. The
        // conveyor overlaps the next upload / previous download with this compute.
        {
            let rbuf = DevBuf::new(nthetac * deth * ne * csz)?;
            // Fused flat/dark + minus-log frames, uploaded once (broadcast over
            // every theta-chunk). `Some(_)` ⟹ normalize each raw chunk in stage 1.
            let fused = lam_upload_norm(norm, deth, detw)?;
            run_lam_conveyor(
                &chunks1,
                deth * detw * fsz,
                deth * detw * csz,
                cancel,
                |slab, ci| {
                    let (t0, tc) = chunks1[ci];
                    let base = t0 * deth * detw;
                    let len = tc * deth * detw;
                    par_copy(&mut slab[..len], &proj[base..base + len]);
                },
                |din, dout, ci| {
                    let tc = chunks1[ci].1;
                    let nlines = (tc * deth) as i64;
                    // Normalize the raw projection chunk in place before filtering.
                    if let Some(df) = &fused {
                        lam_fuse_normalize(din, tc, deth, detw, df.as_ref().map(|(d, e)| (d, e)))?;
                    }
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_ramp_pad(
                                din,
                                rbuf.ptr,
                                nlines,
                                detw as i32,
                                ne as i32,
                                pad as i32,
                                null,
                            )
                        },
                        "lam_ramp_pad",
                    )?;
                    ck(
                        unsafe { ffi::tomoxide_fft_1d_async(rbuf.ptr, ne, nlines as usize, 0) },
                        "lam_ramp_fft",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_ramp_mul(
                                rbuf.ptr,
                                filt_dev.ptr as *const f32,
                                nlines,
                                ne as i32,
                                shift,
                                null,
                            )
                        },
                        "lam_ramp_mul",
                    )?;
                    ck(
                        unsafe { ffi::tomoxide_fft_1d_async(rbuf.ptr, ne, nlines as usize, 1) },
                        "lam_ramp_ifft",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_ramp_crop(
                                rbuf.ptr,
                                din,
                                nlines,
                                detw as i32,
                                ne as i32,
                                pad as i32,
                                null,
                            )
                        },
                        "lam_ramp_crop",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_fft2d_pre(
                                din,
                                dout,
                                tc as i64,
                                deth as i32,
                                detw as i32,
                                null,
                            )
                        },
                        "lam_fft2d_pre",
                    )?;
                    ck(
                        unsafe { ffi::tomoxide_fft_2d_async(dout, deth, detw, tc, 0) },
                        "lam_fft2d",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_fft2d_post(
                                dout,
                                tc as i64,
                                deth as i32,
                                detw as i32,
                                null,
                            )
                        },
                        "lam_fft2d_post",
                    )?;
                    Ok(())
                },
                |slab, ci| {
                    let (t0, tc) = chunks1[ci];
                    let base = t0 * deth * detw * 2;
                    let len = tc * deth * detw * 2;
                    par_copy(&mut p22[base..base + len], &slab[..len]);
                },
            )?;
        }

        // --- stage 2: usfft2d_adj, chunked over depth-frequency ky (deth) ---
        // prep gathers p22[:, k0..k0+kc, :] into a contiguous [nproj, kc, detw] slab
        // (strided host copy); finalize scatters the [n1, kc, n0] f11 slab back into
        // p11[:, k0..k0+kc, :]. Compute scratch (xs/ys/fdee2/win) is allocated once,
        // sized for the largest chunk, with the accumulation grid async-zeroed per
        // chunk (gather2d atomicAdd-accumulates into it).
        {
            let (wy, wx) = (2 * n1, 2 * n0);
            let xs = DevBuf::new(nproj * dethc * detw * fsz)?;
            let ys = DevBuf::new(nproj * dethc * detw * fsz)?;
            let fdee2 = DevBuf::new(dethc * gy * gx * csz)?;
            let win = DevBuf::new(dethc * wy * wx * csz)?;
            run_lam_conveyor(
                &chunks2,
                nproj * detw * csz,
                n1 * n0 * csz,
                cancel,
                |slab, ci| {
                    let (k0, kc) = chunks2[ci];
                    // Strided gather p22[:, k0..k0+kc, :] → contiguous [nproj, kc, detw]
                    // slab; each tz-row is disjoint, so split the rows across cores.
                    let row = kc * detw * 2;
                    slab[..nproj * row]
                        .par_chunks_mut(row)
                        .enumerate()
                        .for_each(|(tz, out)| {
                            let src = (tz * deth + k0) * detw * 2;
                            out.copy_from_slice(&p22[src..src + row]);
                        });
                },
                |din, dout, ci| {
                    let kc = chunks2[ci].1;
                    let k0 = chunks2[ci].0;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_takexy2d(
                                theta_dev.ptr,
                                xs.ptr,
                                ys.ptr,
                                nproj as i64,
                                kc as i32,
                                detw as i32,
                                phi,
                                k0 as i32,
                                deth as i32,
                                null,
                            )
                        },
                        "lam_takexy2d",
                    )?;
                    // Zero only the kc grid; gather2d accumulates (atomicAdd) into it.
                    ck(
                        unsafe {
                            ffi::tomoxide_cuda_memset_async(fdee2.ptr, 0, kc * gy * gx * csz, null)
                        },
                        "lam_fdee2_zero",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_gather2d_adj(
                                din,
                                xs.ptr,
                                ys.ptr,
                                fdee2.ptr,
                                nproj as i64,
                                kc as i32,
                                detw as i32,
                                n0 as i32,
                                n1 as i32,
                                m0 as i32,
                                m1 as i32,
                                mu0,
                                mu1,
                                kc as i32, // g is a contiguous [nproj, kc, detw] chunk
                                0,
                                null,
                            )
                        },
                        "lam_gather2d_adj",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_wrap2d_adj(
                                fdee2.ptr, kc as i32, n0 as i32, n1 as i32, m0 as i32, m1 as i32,
                                null,
                            )
                        },
                        "lam_wrap2d_adj",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_win2d_extract(
                                fdee2.ptr, win.ptr, kc as i32, n0 as i32, n1 as i32, m0 as i32,
                                m1 as i32, null,
                            )
                        },
                        "lam_win2d_extract",
                    )?;
                    ck(
                        unsafe { ffi::tomoxide_fft_2d_async(win.ptr, wy, wx, kc, 1) },
                        "lam_usfft2d_ifft",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_win2d_scatter(
                                fdee2.ptr, win.ptr, kc as i32, n0 as i32, n1 as i32, m0 as i32,
                                m1 as i32, null,
                            )
                        },
                        "lam_win2d_scatter",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_divker2d_adj(
                                fdee2.ptr, dout, n1 as i32, kc as i32, n0 as i32, m0 as i32,
                                m1 as i32, mu0, mu1, kc as i32, 0, null,
                            )
                        },
                        "lam_divker2d_adj",
                    )?;
                    Ok(())
                },
                |slab, ci| {
                    let (k0, kc) = chunks2[ci];
                    // Strided scatter contiguous [n1, kc, n0] slab → p11[:, k0..k0+kc, :].
                    // p11 is n1 blocks of deth*n0*2; each ty-block is disjoint.
                    let blk = deth * n0 * 2;
                    let seg = kc * n0 * 2;
                    let off = k0 * n0 * 2;
                    p11.par_chunks_mut(blk).enumerate().for_each(|(ty, block)| {
                        let src = ty * seg;
                        block[off..off + seg].copy_from_slice(&slab[src..src + seg]);
                    });
                },
            )?;
        }
        drop(p22);

        // --- stage 3: usfft1d_adj, chunked over y-frequency rows (n1) ---
        // Each n1-chunk is a contiguous slab of p11 (prep) → a contiguous [yc, rh, n0]
        // real slab into p00 (finalize). `z` is chunk-independent, computed once;
        // fdee1 async-zeroed per chunk (gather1d atomicAdd-accumulates into it).
        {
            let z = DevBuf::new(deth * fsz)?;
            ck(
                unsafe { ffi::tomoxide_lam_takez1d(z.ptr, deth as i32, phi, null) },
                "lam_takez1d",
            )?;
            let fdee1 = DevBuf::new(ng * n1c * n0 * csz)?;
            let lines = DevBuf::new(n1c * n0 * (2 * rh) * csz)?;
            run_lam_conveyor(
                &chunks3,
                deth * n0 * csz,
                rh * n0 * fsz,
                cancel,
                |slab, ci| {
                    let (y0, yc) = chunks3[ci];
                    let base = y0 * deth * n0 * 2;
                    let len = yc * deth * n0 * 2;
                    par_copy(&mut slab[..len], &p11[base..base + len]);
                },
                |din, dout, ci| {
                    let yc = chunks3[ci].1;
                    // Zero only the yc grid; gather1d accumulates (atomicAdd) into it.
                    ck(
                        unsafe {
                            ffi::tomoxide_cuda_memset_async(fdee1.ptr, 0, ng * yc * n0 * csz, null)
                        },
                        "lam_fdee1_zero",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_gather1d_adj(
                                din,
                                z.ptr,
                                fdee1.ptr,
                                yc as i32,
                                deth as i32,
                                n0 as i32,
                                rh as i32,
                                m2 as i32,
                                mu2,
                                null,
                            )
                        },
                        "lam_gather1d_adj",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_wrap1d_adj(
                                fdee1.ptr, n0 as i32, yc as i32, rh as i32, m2 as i32, null,
                            )
                        },
                        "lam_wrap1d_adj",
                    )?;
                    let batch = (n0 * yc) as i64;
                    let len = 2 * rh;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_win1d_extract(
                                fdee1.ptr, lines.ptr, batch, rh as i32, m2 as i32, null,
                            )
                        },
                        "lam_win1d_extract",
                    )?;
                    ck(
                        unsafe { ffi::tomoxide_fft_1d_async(lines.ptr, len, batch as usize, 1) },
                        "lam_usfft1d_ifft",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_win1d_scatter(
                                fdee1.ptr, lines.ptr, batch, rh as i32, m2 as i32, null,
                            )
                        },
                        "lam_win1d_scatter",
                    )?;
                    ck(
                        unsafe {
                            ffi::tomoxide_lam_divker1d_adj(
                                fdee1.ptr, dout, yc as i32, rh as i32, n0 as i32, m2 as i32, mu2,
                                null,
                            )
                        },
                        "lam_divker1d_adj",
                    )?;
                    Ok(())
                },
                |slab, ci| {
                    let (y0, yc) = chunks3[ci];
                    let base = y0 * rh * n0;
                    let len = yc * rh * n0;
                    par_copy(&mut p00[base..base + len], &slab[..len]);
                },
            )?;
        }
        drop(p11);

        emit_p00_tiles(&p00, (n1, rh, n), LAM_FOURIER_TILE_BYTES, cancel, on_tile)
    }

    /// Host bytes per Fourierrec output tile: 16 planes at 2048², small beside
    /// the `p00` the tiles are transposed from.
    const LAM_FOURIER_TILE_BYTES: usize = 256 << 20;

    /// copyTransposed, a tile at a time: hand `p00` `[n1, rh, n]` to `on_tile`
    /// as ascending `[tlen, n1, n]` z-tiles of at most `tile_bytes`, each
    /// transposed as it is emitted, so the `[rh, n1, n]` volume is never held
    /// beside `p00`.
    fn emit_p00_tiles(
        p00: &[f32],
        (n1, rh, n): (usize, usize, usize),
        tile_bytes: usize,
        cancel: Option<&CancelToken>,
        on_tile: &mut super::LaminoTileFn,
    ) -> Result<()> {
        let rows = tile_bytes / (n1 * n * std::mem::size_of::<f32>()).max(1);
        for (z0, tlen) in chunk_ranges(rh, rows) {
            check_cancel(cancel)?;
            let mut tile = vec![0.0f32; tlen * n1 * n];
            // Planes are disjoint, so they transpose across cores (the gather
            // from p00 within a plane stays strided).
            tile.par_chunks_mut(n1 * n)
                .enumerate()
                .for_each(|(i, plane)| {
                    for ty in 0..n1 {
                        let src = (ty * rh + z0 + i) * n;
                        plane[ty * n..ty * n + n].copy_from_slice(&p00[src..src + n]);
                    }
                });
            let arr = Array3::from_shape_vec((tlen, n1, n), tile)
                .map_err(|e| Error::InvalidParam(format!("cuda lamino tile shape: {e}")))?;
            on_tile(z0, &Volume::new(arr))?;
        }
        Ok(())
    }

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

        // Tiles of 3 planes over rh = 8 (a short last tile) reassemble to the
        // whole-volume transpose, ascending and each plane once.
        #[test]
        fn p00_tiles_reassemble_the_transposed_volume() {
            let (n1, rh, n) = (5usize, 8usize, 4usize);
            let p00: Vec<f32> = (0..n1 * rh * n).map(|i| i as f32).collect();
            let plane = n1 * n * std::mem::size_of::<f32>();
            let mut tiles = Vec::new();
            let mut vol = Vec::<f32>::new();
            emit_p00_tiles(&p00, (n1, rh, n), 3 * plane + 1, None, &mut |z0, tile| {
                tiles.push((z0, tile.array.dim()));
                vol.extend(tile.array.iter());
                Ok(())
            })
            .unwrap();
            assert_eq!(tiles, [(0, (3, n1, n)), (3, (3, n1, n)), (6, (2, n1, n))]);
            for z in 0..rh {
                for y in 0..n1 {
                    for x in 0..n {
                        assert_eq!(vol[(z * n1 + y) * n + x], p00[(y * rh + z) * n + x]);
                    }
                }
            }
        }
    }

    /// Parallel `dst.copy_from_slice(src)` for the large contiguous host-spectrum
    /// copies in the laminography conveyor. Single-threaded memcpy of the ~100 GB
    /// host spectra (the `prep_in`/`finalize` gather/scatter) is the host path's
    /// dominant cost — the GPU sits idle waiting on it — so these copies are split
    /// across cores. `dst` and `src` must have equal length.
    fn par_copy(dst: &mut [f32], src: &[f32]) {
        const CH: usize = 1 << 21; // 2 Mi f32 = 8 MiB per rayon task
        dst.par_chunks_mut(CH)
            .zip(src.par_chunks(CH))
            .for_each(|(d, s)| d.copy_from_slice(s));
    }

    /// Fused flat/dark + minus-log on a raw projection chunk `din`
    /// (`[tc, deth, detw]`, projection layout) in place, on the per-thread stream,
    /// immediately before ramp filtering. These are the same darkflat/minus-log
    /// kernels `normalize_dataset` runs on the whole stack, applied per stage-1
    /// chunk so the standalone full-stack GPU round-trip (upload → normalize →
    /// download → re-upload) is skipped. `darkflat` is the uploaded `[deth·detw]`
    /// `(dark2d, denom)` frames (broadcast over the `tc` projections) or `None`
    /// for already-normalized input; minus-log always runs (matching
    /// `normalize_dataset`). Enqueued on the same null/per-thread stream as the
    /// ramp kernels, so it is ordered before them without an extra sync.
    fn lam_fuse_normalize(
        din: *mut c_void,
        tc: usize,
        deth: usize,
        detw: usize,
        darkflat: Option<(&DevBuf, &DevBuf)>,
    ) -> Result<()> {
        let null = std::ptr::null_mut::<c_void>();
        if let Some((dark, denom)) = darkflat {
            ck(
                unsafe { ffi::tomoxide_darkflat(din, dark.ptr, denom.ptr, tc, deth, detw, null) },
                "lam_fuse_darkflat",
            )?;
        }
        ck(
            unsafe { ffi::tomoxide_minuslog(din, tc * deth * detw, null) },
            "lam_fuse_minuslog",
        )?;
        Ok(())
    }

    /// Upload a [`LamNorm`]'s darkflat frames to the device once (they broadcast
    /// over every theta-chunk), validating their `[deth·detw]` shape. `Some(_)` ⟹
    /// stage 1 applies minus-log; the inner `Option` is the uploaded darkflat
    /// frames. Returns `None` when no fused normalization was requested.
    #[allow(clippy::type_complexity)]
    fn lam_upload_norm(
        norm: Option<&super::LamNorm>,
        deth: usize,
        detw: usize,
    ) -> Result<Option<Option<(DevBuf, DevBuf)>>> {
        match norm {
            None => Ok(None),
            Some(nrm) => match &nrm.darkflat {
                None => Ok(Some(None)),
                Some((dark2d, denom)) => {
                    if dark2d.len() != deth * detw || denom.len() != deth * detw {
                        return Err(Error::InvalidParam(
                            "lamino fused normalize: dark2d/denom must be [deth, detw]".into(),
                        ));
                    }
                    Ok(Some(Some((
                        DevBuf::from_host_f32(dark2d)?,
                        DevBuf::from_host_f32(denom)?,
                    ))))
                }
            },
        }
    }

    /// Split `0..total` into consecutive `[start, count)` chunks of at most `step`
    /// (the last is short when `total` is not a multiple of `step`). Used to plan
    /// each laminography stage's independent chunk axis.
    fn chunk_ranges(total: usize, step: usize) -> Vec<(usize, usize)> {
        let step = step.max(1);
        let mut v = Vec::new();
        let mut i = 0;
        while i < total {
            let c = step.min(total - i);
            v.push((i, c));
            i += c;
        }
        v
    }

    /// Drive a single-thread, async-overlapped conveyor over `chunks` for one
    /// host-resident laminography stage. The dominant cost of the host path is not
    /// the H2D/D2H transfers but the single-threaded CPU gather/scatter that
    /// shuttles the ~100 GB host spectra through the pinned staging slabs. Because
    /// `compute` issues its stage kernels and FFTs **asynchronously** on the
    /// per-thread stream (the `tomoxide_fft_*_async` variants enqueue without a host
    /// sync), the host returns from it immediately and runs the CPU gather (chunk
    /// `k`) and scatter (chunk `k-2`) while the GPU computes chunk `k-1` — the same
    /// overlap CuPy gives tomocupy's `*_chunks` loops for free, without the extra
    /// worker thread the blocking-FFT design required.
    ///
    /// - `prep_in(slab, idx)` fills the pinned input slab for chunk `idx`
    ///   (a contiguous or strided gather from the host spectrum).
    /// - `compute(din, dout, idx)` issues the stage kernels + async FFTs on the
    ///   per-thread/null stream, reading device input `din`, writing `dout`.
    /// - `finalize(slab, idx)` stores the drained pinned output slab for chunk
    ///   `idx` (a contiguous or strided scatter into the host spectrum).
    ///
    /// `in_stride`/`out_stride` are the per-chunk-unit byte sizes: chunk `idx`
    /// transfers `chunks[idx].1 * stride` bytes; the double-buffered device/pinned
    /// slabs are sized `max_count * stride`. The loop is a 3-deep software pipeline
    /// (compute `k-1` ∥ upload `k` ∥ drain `k-2`). Within one iteration the async
    /// compute overlaps both CPU copies and the two transfers; the end-of-iteration
    /// barrier (`ev_done` + `cstream.sync`) then bounds every buffer reuse to two
    /// slots, so no cross-stream reuse event is needed. The one device→host order
    /// the host awaits mid-iteration is `ev_drained` (chunk `k-2`'s D2H) before its
    /// scatter, so that scatter overlaps `compute(k-1)` instead of the barrier.
    /// That barrier also leaves nothing in flight at the top of an iteration,
    /// which is where `cancel` is checked.
    fn run_lam_conveyor(
        chunks: &[(usize, usize)],
        in_stride: usize,
        out_stride: usize,
        cancel: Option<&CancelToken>,
        mut prep_in: impl FnMut(&mut [f32], usize),
        mut compute: impl FnMut(*mut c_void, *mut c_void, usize) -> Result<()>,
        mut finalize: impl FnMut(&[f32], usize),
    ) -> Result<()> {
        let n = chunks.len();
        if n == 0 {
            return Ok(());
        }
        let fsz = std::mem::size_of::<f32>();
        let maxc = chunks.iter().map(|c| c.1).max().unwrap_or(0);
        let dev_in = [
            DevBuf::new(maxc * in_stride)?,
            DevBuf::new(maxc * in_stride)?,
        ];
        let dev_out = [
            DevBuf::new(maxc * out_stride)?,
            DevBuf::new(maxc * out_stride)?,
        ];
        let mut pin_in = [
            PinnedBuf::<f32>::new(maxc * in_stride / fsz)?,
            PinnedBuf::<f32>::new(maxc * in_stride / fsz)?,
        ];
        // D2H writes into pin_out through its raw `ptr`, so the binding need not be
        // `mut` (we only ever `as_slice` it on the host to read the drained chunk).
        let pin_out = [
            PinnedBuf::<f32>::new(maxc * out_stride / fsz)?,
            PinnedBuf::<f32>::new(maxc * out_stride / fsz)?,
        ];
        let cstream = Stream::new()?;
        let ev_done = [Event::new()?, Event::new()?]; // compute(slot) finished
        let ev_drained = [Event::new()?, Event::new()?]; // D2H(slot) finished

        for k in 0..n + 2 {
            check_cancel(cancel)?;
            // Launch compute(k-1) on the per-thread stream; the async FFTs mean this
            // returns at once, freeing the host to run the CPU copies below.
            if (1..=n).contains(&k) {
                let c = k - 1;
                let s = c % 2;
                compute(dev_in[s].ptr, dev_out[s].ptr, c)?;
                ev_done[s].record_compute()?;
            }
            // Drain chunk k-2's device output to its pinned slab (its compute was
            // completed by the previous iteration's barrier).
            if k >= 2 {
                let c = k - 2;
                let s = c % 2;
                let count = chunks[c].1;
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memcpy_d2h_async(
                            pin_out[s].ptr,
                            dev_out[s].ptr as *const c_void,
                            count * out_stride,
                            cstream.ptr,
                        )
                    },
                    "lam_conv_d2h",
                )?;
                ev_drained[s].record_on(&cstream)?;
            }
            // Gather chunk k into its pinned slab (CPU — overlaps compute(k-1)), then
            // upload it. dev_in[s]/pin_in[s] last held chunk k-2, whose compute/H2D
            // the previous barriers completed, so the reuse is safe.
            if k < n {
                let s = k % 2;
                let count = chunks[k].1;
                prep_in(pin_in[s].as_mut_slice(), k);
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memcpy_h2d_async(
                            dev_in[s].ptr,
                            pin_in[s].ptr as *const c_void,
                            count * in_stride,
                            cstream.ptr,
                        )
                    },
                    "lam_conv_h2d",
                )?;
            }
            // Scatter chunk k-2 to the host spectrum once its D2H has landed (CPU —
            // overlaps compute(k-1)).
            if k >= 2 {
                let c = k - 2;
                let s = c % 2;
                ck(
                    unsafe { ffi::tomoxide_cuda_event_sync(ev_drained[s].ptr) },
                    "lam_conv_drain",
                )?;
                finalize(pin_out[s].as_slice(), c);
            }
            // Barrier: compute(k-1) and this iteration's copies (H2D k, D2H k-2) must
            // finish before their two-slot buffers are reused two iterations on.
            if (1..=n).contains(&k) {
                ck(
                    unsafe { ffi::tomoxide_cuda_event_sync(ev_done[(k - 1) % 2].ptr) },
                    "lam_conv_compute_sync",
                )?;
            }
            cstream.sync()?;
        }
        Ok(())
    }

    /// Device-resident Fourier/USFFT laminography: the two large intermediate
    /// spectra `p22` (post-2-D-FFT projections) and `p11` (post-usfft2d) stay
    /// resident on the GPU across all three stages, so the only host↔device traffic
    /// is the input projections in and the output slabs out. This removes the
    /// ~48 GB of intermediate `p22`/`p11` shuttling that the host-resident path
    /// pays between stages — the shuttling is exactly what leaves the GPU idle in
    /// bursts — so utilization stays high without the tomocupy conveyor's explicit
    /// stream/double-buffer plumbing.
    ///
    /// `p00` is streamed to the host per stage-3 chunk rather than kept resident:
    /// the final transpose to output tiles runs on the host anyway, and holding only
    /// `p22`+`p11` (~24 GB at 1024²) leaves comfortable headroom for large grid
    /// chunks and cuFFT plan scratch, where all-three-resident (~30 GB) would leave
    /// almost none. The dispatcher [`analytic_lamino_fourierrec`] falls back to
    /// [`analytic_lamino_fourierrec_host`] when `p22`+`p11` do not fit.
    ///
    /// Numerically identical to the host path (same kernels, same chunk-independent
    /// axes); the strided `gdeth`/`ky0` gather2d/divker2d parameters let stage 2
    /// read and write the resident spectra in place instead of a contiguous copy.
    fn analytic_lamino_fourierrec_device(
        proj: &[f32],
        theta: &[f32],
        p: LamFourierParams,
        norm: Option<&super::LamNorm>,
        cancel: Option<&CancelToken>,
        on_tile: &mut super::LaminoTileFn,
    ) -> Result<()> {
        let LamFourierParams {
            phi,
            n,
            rh,
            center,
            filter,
        } = p;
        let csz = 2 * std::mem::size_of::<f32>(); // bytes per complex
        let fsz = std::mem::size_of::<f32>();
        let null = std::ptr::null_mut::<c_void>();

        let nproj = theta.len();
        let detw = n;
        let deth = proj.len() / (nproj * n);
        if proj.len() != nproj * deth * detw {
            return Err(Error::InvalidParam(
                "lamino fourierrec: proj shape != [nproj, nz, n]".into(),
            ));
        }
        let (n0, n1) = (detw, n);
        let (m0, mu0) = lam_usfft_params(n0);
        let (m1, mu1) = lam_usfft_params(n1);
        let (m2, mu2) = lam_usfft_params(rh);
        let gx = 2 * n0 + 2 * m0;
        let gy = 2 * n1 + 2 * m1;
        let ng = 2 * rh + 2 * m2;
        let (filt, pad) = crate::recon::lamino::projection_filter(filter, detw)?;
        let ne = filt.len();
        let shift = detw as f32 / 2.0 - center; // rotation-center linear phase

        let theta_dev = DevBuf::from_host_f32(theta)?;
        // FBP filter weights (ramp × apodisation window), uploaded once and
        // reused across every theta-chunk's stage-1 ramp multiply.
        let filt_dev = DevBuf::from_host_f32(&filt)?;

        // Resident spectra (complex, interleaved f32 pairs). p00 is streamed to a
        // pinned host buffer in stage 3. No memset: stage 1 fully overwrites p22 and
        // stage 2 fully overwrites p11.
        let p22 = DevBuf::new(nproj * deth * detw * csz)?; // [nproj, deth, detw]
        let p11 = DevBuf::new(n1 * deth * n0 * csz)?; // [n1, deth, n0]

        // Chunk sizes are bounded by what is left after the resident spectra: only
        // the transient USFFT grids and the input/output slabs compete for it. The
        // stage-1 input and stage-3 output slabs are double-buffered for the copy
        // conveyor, so their per-chunk cost counts two slabs (the doubled slab is
        // inside the budget, so cuFFT plan scratch keeps the same untracked margin).
        let budget = (device_free_bytes() / 100 * 60).max(1);
        let per_theta = 2 * deth * detw * fsz + deth * ne * csz;
        let nthetac = (budget / per_theta.max(1)).clamp(1, nproj);
        let per_ky = gy * gx * csz + (2 * n1) * (2 * n0) * csz + 2 * nproj * detw * fsz;
        let dethc = (budget / per_ky.max(1)).clamp(1, deth);
        let per_ty = ng * n0 * csz + n0 * (2 * rh) * csz + 2 * rh * n0 * fsz;
        let n1c = (budget / per_ty.max(1)).clamp(1, n1);

        // --- stage 1: ramp_filter_center + centered 2-D FFT, chunked over ntheta ---
        // Conveyor: chunk ci+1's projections upload on a copy stream while chunk ci's
        // ramp+FFT runs on the compute (per-thread) stream; CUDA events order the
        // shared double buffer so a copy never overwrites a slab still being read.
        // Uploads stage `proj` through a [`PinnedStage`].
        // Each theta-chunk is a contiguous slab of p22, written in place (no download).
        {
            let chunks: Vec<(usize, usize)> = {
                let (mut v, mut t0) = (Vec::new(), 0);
                while t0 < nproj {
                    let tc = nthetac.min(nproj - t0);
                    v.push((t0, tc));
                    t0 += tc;
                }
                v
            };
            let mut stage = PinnedStage::new(nthetac * deth * detw)?;
            let dev_in = [
                DevBuf::new(nthetac * deth * detw * fsz)?,
                DevBuf::new(nthetac * deth * detw * fsz)?,
            ];
            let rbuf = DevBuf::new(nthetac * deth * ne * csz)?;
            // Fused flat/dark + minus-log frames, uploaded once (broadcast over
            // every theta-chunk). `Some(_)` ⟹ normalize each raw chunk in stage 1.
            let fused = lam_upload_norm(norm, deth, detw)?;
            let cstream = Stream::new()?;
            let ev_uploaded = [Event::new()?, Event::new()?];
            let ev_consumed = [Event::new()?, Event::new()?];

            // H2D one theta-chunk into `dev_in[slot]` on the copy stream.
            let mut h2d = |slot: usize, t0: usize, tc: usize| -> Result<()> {
                let frame = deth * detw;
                stage.upload(
                    dev_in[slot].ptr,
                    &proj[t0 * frame..][..tc * frame],
                    &cstream,
                )
            };

            // Prime: upload chunk 0.
            let (t0, tc) = chunks[0];
            h2d(0, t0, tc)?;
            ev_uploaded[0].record_on(&cstream)?;

            for (ci, &(t0, tc)) in chunks.iter().enumerate() {
                check_cancel_drained(cancel)?;
                let slot = ci % 2;
                // Compute waits for this chunk's upload, then runs on the per-thread stream.
                ev_uploaded[slot].wait_compute()?;
                let din = &dev_in[slot];
                let nlines = (tc * deth) as i64;
                // Normalize the raw projection chunk in place before filtering.
                if let Some(df) = &fused {
                    lam_fuse_normalize(din.ptr, tc, deth, detw, df.as_ref().map(|(d, e)| (d, e)))?;
                }
                ck(
                    unsafe {
                        ffi::tomoxide_lam_ramp_pad(
                            din.ptr,
                            rbuf.ptr,
                            nlines,
                            detw as i32,
                            ne as i32,
                            pad as i32,
                            null,
                        )
                    },
                    "lam_ramp_pad",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_1d(rbuf.ptr, ne, nlines as usize, 0) },
                    "lam_ramp_fft",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_ramp_mul(
                            rbuf.ptr,
                            filt_dev.ptr as *const f32,
                            nlines,
                            ne as i32,
                            shift,
                            null,
                        )
                    },
                    "lam_ramp_mul",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_1d(rbuf.ptr, ne, nlines as usize, 1) },
                    "lam_ramp_ifft",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_ramp_crop(
                            rbuf.ptr,
                            din.ptr,
                            nlines,
                            detw as i32,
                            ne as i32,
                            pad as i32,
                            null,
                        )
                    },
                    "lam_ramp_crop",
                )?;
                // Offset pointer into resident p22 for this theta-chunk.
                let p22_off =
                    unsafe { (p22.ptr as *mut u8).add(t0 * deth * detw * csz) as *mut c_void };
                ck(
                    unsafe {
                        ffi::tomoxide_lam_fft2d_pre(
                            din.ptr,
                            p22_off,
                            tc as i64,
                            deth as i32,
                            detw as i32,
                            null,
                        )
                    },
                    "lam_fft2d_pre",
                )?;
                // din is fully consumed; let the copy stream reuse this slot.
                ev_consumed[slot].record_compute()?;
                ck(
                    unsafe { ffi::tomoxide_fft_2d(p22_off, deth, detw, tc, 0) },
                    "lam_fft2d",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_fft2d_post(
                            p22_off,
                            tc as i64,
                            deth as i32,
                            detw as i32,
                            null,
                        )
                    },
                    "lam_fft2d_post",
                )?;
                // Prefetch the next chunk into the other slot while this one
                // computes; queued after it, so the host-side staging overlaps it.
                if ci + 1 < chunks.len() {
                    let nslot = (ci + 1) % 2;
                    let (nt0, ntc) = chunks[ci + 1];
                    // Don't overwrite a slab whose compute has not consumed it yet.
                    if ci + 1 >= 2 {
                        cstream.wait_event(&ev_consumed[nslot])?;
                    }
                    h2d(nslot, nt0, ntc)?;
                    ev_uploaded[nslot].record_on(&cstream)?;
                }
            }
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        }

        // --- stage 2: usfft2d_adj, chunked over depth-frequency ky (deth) ---
        // gather2d reads the resident p22 in place with (gdeth=deth, ky0=k0) and
        // divker2d writes the resident p11 in place with (fdeth=deth, ky0=k0); no
        // host gather/scatter copies. All buffers are allocated once (sized for the
        // largest chunk) and reused, with an async zero of the accumulation grid per
        // chunk — the per-chunk malloc/free was a source of the inter-chunk GPU stall.
        {
            let (wy, wx) = (2 * n1, 2 * n0);
            let xs = DevBuf::new(nproj * dethc * detw * fsz)?;
            let ys = DevBuf::new(nproj * dethc * detw * fsz)?;
            let fdee2 = DevBuf::new(dethc * gy * gx * csz)?;
            let win = DevBuf::new(dethc * wy * wx * csz)?;
            let mut k0 = 0;
            while k0 < deth {
                check_cancel_drained(cancel)?;
                let kc = dethc.min(deth - k0);
                ck(
                    unsafe {
                        ffi::tomoxide_lam_takexy2d(
                            theta_dev.ptr,
                            xs.ptr,
                            ys.ptr,
                            nproj as i64,
                            kc as i32,
                            detw as i32,
                            phi,
                            k0 as i32,
                            deth as i32,
                            null,
                        )
                    },
                    "lam_takexy2d",
                )?;
                // Zero only the kc grid; gather2d accumulates (atomicAdd) into it.
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memset_async(fdee2.ptr, 0, kc * gy * gx * csz, null)
                    },
                    "lam_fdee2_zero",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_gather2d_adj(
                            p22.ptr,
                            xs.ptr,
                            ys.ptr,
                            fdee2.ptr,
                            nproj as i64,
                            kc as i32,
                            detw as i32,
                            n0 as i32,
                            n1 as i32,
                            m0 as i32,
                            m1 as i32,
                            mu0,
                            mu1,
                            deth as i32, // p22 is the full [nproj, deth, detw] spectrum
                            k0 as i32,
                            null,
                        )
                    },
                    "lam_gather2d_adj",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_wrap2d_adj(
                            fdee2.ptr, kc as i32, n0 as i32, n1 as i32, m0 as i32, m1 as i32, null,
                        )
                    },
                    "lam_wrap2d_adj",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_win2d_extract(
                            fdee2.ptr, win.ptr, kc as i32, n0 as i32, n1 as i32, m0 as i32,
                            m1 as i32, null,
                        )
                    },
                    "lam_win2d_extract",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_2d(win.ptr, wy, wx, kc, 1) },
                    "lam_usfft2d_ifft",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_win2d_scatter(
                            fdee2.ptr, win.ptr, kc as i32, n0 as i32, n1 as i32, m0 as i32,
                            m1 as i32, null,
                        )
                    },
                    "lam_win2d_scatter",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_divker2d_adj(
                            fdee2.ptr,
                            p11.ptr,
                            n1 as i32,
                            kc as i32,
                            n0 as i32,
                            m0 as i32,
                            m1 as i32,
                            mu0,
                            mu1,
                            deth as i32,
                            k0 as i32,
                            null,
                        )
                    },
                    "lam_divker2d_adj",
                )?;
                k0 += kc;
            }
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        }

        // --- stage 3: usfft1d_adj, chunked over y-frequency rows (n1) ---
        // Conveyor mirror of stage 1: chunk ci-1's finished f00 slab drains into
        // `p00` through a [`PinnedStage`] on a copy stream while chunk ci computes.
        // The drain returns before chunk ci+1, which reuses that slab, is queued.
        // Each n1-chunk is a contiguous slab of the resident p11, read in place at
        // its offset (no upload).
        let mut p00 = vec![0.0f32; n1 * rh * n0]; // [n1, rh, n0] real
        {
            let z = DevBuf::new(deth * fsz)?;
            ck(
                unsafe { ffi::tomoxide_lam_takez1d(z.ptr, deth as i32, phi, null) },
                "lam_takez1d",
            )?;
            let chunks: Vec<(usize, usize)> = {
                let (mut v, mut y0) = (Vec::new(), 0);
                while y0 < n1 {
                    let yc = n1c.min(n1 - y0);
                    v.push((y0, yc));
                    y0 += yc;
                }
                v
            };
            let fdee1 = DevBuf::new(ng * n1c * n0 * csz)?;
            let lines = DevBuf::new(n1c * n0 * (2 * rh) * csz)?;
            let f00 = [
                DevBuf::new(n1c * rh * n0 * fsz)?,
                DevBuf::new(n1c * rh * n0 * fsz)?,
            ];
            let stage = PinnedStage::new(n1c * rh * n0)?;
            let cstream = Stream::new()?;
            let ev_computed = [Event::new()?, Event::new()?];
            // D2H chunk `c` into `p00` once computed; its f00 slab is free on return.
            let mut drain = |c: usize| -> Result<()> {
                let (y0, yc) = chunks[c];
                cstream.wait_event(&ev_computed[c % 2])?;
                let plane = rh * n0;
                stage.download(
                    &mut p00[y0 * plane..][..yc * plane],
                    f00[c % 2].ptr,
                    &cstream,
                )
            };

            for (ci, &(y0, yc)) in chunks.iter().enumerate() {
                check_cancel_drained(cancel)?;
                let slot = ci % 2;
                let g_off =
                    unsafe { (p11.ptr as *mut u8).add(y0 * deth * n0 * csz) as *mut c_void };
                // Zero only the yc grid; gather1d accumulates (atomicAdd) into it.
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memset_async(fdee1.ptr, 0, ng * yc * n0 * csz, null)
                    },
                    "lam_fdee1_zero",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_gather1d_adj(
                            g_off,
                            z.ptr,
                            fdee1.ptr,
                            yc as i32,
                            deth as i32,
                            n0 as i32,
                            rh as i32,
                            m2 as i32,
                            mu2,
                            null,
                        )
                    },
                    "lam_gather1d_adj",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_wrap1d_adj(
                            fdee1.ptr, n0 as i32, yc as i32, rh as i32, m2 as i32, null,
                        )
                    },
                    "lam_wrap1d_adj",
                )?;
                let batch = (n0 * yc) as i64;
                let len = 2 * rh;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_win1d_extract(
                            fdee1.ptr, lines.ptr, batch, rh as i32, m2 as i32, null,
                        )
                    },
                    "lam_win1d_extract",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_1d(lines.ptr, len, batch as usize, 1) },
                    "lam_usfft1d_ifft",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_win1d_scatter(
                            fdee1.ptr, lines.ptr, batch, rh as i32, m2 as i32, null,
                        )
                    },
                    "lam_win1d_scatter",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lam_divker1d_adj(
                            fdee1.ptr,
                            f00[slot].ptr,
                            yc as i32,
                            rh as i32,
                            n0 as i32,
                            m2 as i32,
                            mu2,
                            null,
                        )
                    },
                    "lam_divker1d_adj",
                )?;
                // f00[slot] is ready for the copy stream.
                ev_computed[slot].record_compute()?;
                if ci >= 1 {
                    drain(ci - 1)?;
                }
            }
            drain(chunks.len() - 1)?;
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        }
        drop(p11);
        drop(p22);

        emit_p00_tiles(&p00, (n1, rh, n), LAM_FOURIER_TILE_BYTES, cancel, on_tile)
    }

    /// [`check_cancel`] inside a loop that leaves copies and kernels in flight
    /// across iterations: the device finishes them before the early return
    /// frees the buffers they use.
    fn check_cancel_drained(cancel: Option<&CancelToken>) -> Result<()> {
        if cancel.is_some_and(CancelToken::is_cancelled) {
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        }
        check_cancel(cancel)
    }

    /// Fourier/USFFT laminography dispatcher: prefers the device-resident path
    /// ([`analytic_lamino_fourierrec_device`]) — spectra stay on the GPU, GPU
    /// utilization stays high — whenever the two resident spectra (`p22`+`p11`)
    /// fit in ~80 % of free VRAM (leaving ≥20 % for the transient USFFT grids and
    /// cuFFT plan scratch). Otherwise it falls back to the host-resident streaming
    /// path ([`analytic_lamino_fourierrec_host`]), which bounds peak VRAM to a
    /// fraction of one grid at the cost of full-volume PCIe shuttling.
    ///
    /// Setting `TOMOXIDE_LAM_FOURIERREC_HOST=1` forces the host-resident path
    /// regardless of the fit test — an escape hatch for a shared card where the
    /// device path's ~95 % VRAM peak would collide with another process.
    ///
    /// Either path hands the `[rh, n, n]` volume to `on_tile` as ascending
    /// z-tiles, and only once all three stages are done: no stage is separable
    /// over the output rows, so the whole output is first held as `p00`.
    fn analytic_lamino_fourierrec(
        proj: &[f32],
        theta: &[f32],
        p: LamFourierParams,
        norm: Option<&super::LamNorm>,
        cancel: Option<&CancelToken>,
        on_tile: &mut super::LaminoTileFn,
    ) -> Result<()> {
        let n = p.n;
        let csz = 2 * std::mem::size_of::<f32>();
        let nproj = theta.len();
        let detw = n;
        let deth = proj.len() / (nproj * n).max(1);
        // p22 [nproj, deth, detw] + p11 [n1=n, deth, n0=detw], both complex.
        let base = nproj
            .saturating_mul(deth)
            .saturating_mul(detw)
            .saturating_mul(csz)
            .saturating_add(
                n.saturating_mul(deth)
                    .saturating_mul(detw)
                    .saturating_mul(csz),
            );
        let free = device_free_bytes();
        let force_host = std::env::var_os("TOMOXIDE_LAM_FOURIERREC_HOST").is_some_and(|v| v == "1");
        if !force_host && base.saturating_mul(5) <= free.saturating_mul(4) {
            analytic_lamino_fourierrec_device(proj, theta, p, norm, cancel, on_tile)
        } else {
            analytic_lamino_fourierrec_host(proj, theta, p, norm, cancel, on_tile)
        }
    }

    /// Half-precision (`Dtype::F16`) Fourierrec on the **current** device, whole
    /// stack in one chunk. Mirrors [`analytic_fourierrec`] with `f16` buffers and a
    /// half-precision cuFFT filter (`pad` must be a power of two; enforced by the
    /// caller). theta stays f32. Like the vendored f32 path the gather scatters with
    /// `atomicAdd`, so the low bits are nondeterministic; in f16 the precision floor
    /// is coarser — correlation-verified against f32, not bit-exact.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fourierrec_f16(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let hsz = std::mem::size_of::<half::f16>();
        let null = std::ptr::null_mut::<c_void>();
        let sino_dev = DevBuf::from_host_f16(raw)?;
        let w_dev = DevBuf::from_host_f16(w)?;
        let theta_dev = DevBuf::from_host_f32(theta)?;
        let gpad = DevBuf::zeroed(nz * nproj * pad * hsz)?;
        ck(
            unsafe {
                ffi::tomoxide_pad_fp16(
                    sino_dev.ptr,
                    gpad.ptr,
                    nz,
                    nproj,
                    ncols,
                    pad,
                    pad_side,
                    null,
                )
            },
            "pad_fp16",
        )?;
        let fh = Handle::new(
            unsafe { ffi::tomoxide_filter_fp16_new(nproj, nz, pad) },
            ffi::tomoxide_filter_fp16_free,
            "cfunc_filter (f16)",
        )?;
        ck(
            unsafe { ffi::tomoxide_filter_fp16_apply(fh.ptr, gpad.ptr, w_dev.ptr, null) },
            "filter_fp16_apply",
        )?;
        drop(fh);
        let gf = DevBuf::zeroed(nz * nproj * ncols * hsz)?;
        ck(
            unsafe {
                ffi::tomoxide_crop_fp16(gpad.ptr, gf.ptr, nz, nproj, ncols, pad, pad_side, null)
            },
            "crop_fp16",
        )?;
        let gc = DevBuf::zeroed(nz * nproj * ncols * hsz)?; // complex [nz/2,nproj,ncols]
        ck(
            unsafe { ffi::tomoxide_pack_pairs_fp16(gf.ptr, gc.ptr, nz, nproj, ncols, null) },
            "pack_fp16",
        )?;
        let fc = DevBuf::zeroed(nz * n * n * hsz)?; // complex [nz/2,n,n]
        let h = Handle::new(
            unsafe {
                ffi::tomoxide_fourierrec_fp16_new(nproj, nz / 2, n, theta_dev.ptr as *const f32)
            },
            ffi::tomoxide_fourierrec_fp16_free,
            "cfunc_fourierrec (f16)",
        )?;
        ck(
            unsafe { ffi::tomoxide_fourierrec_fp16_backproject(h.ptr, fc.ptr, gc.ptr, null) },
            "fourierrec_fp16_backproject",
        )?;
        drop(h);
        let vol_dev = DevBuf::zeroed(nz * n * n * hsz)?;
        ck(
            unsafe { ffi::tomoxide_unpack_pairs_fp16(fc.ptr, vol_dev.ptr, nz, n, null) },
            "unpack_fp16",
        )?;
        ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync")?;
        vol_dev.to_host_f16_as_f32(nz * n * n)
    }

    /// Memory-safe driver for the fused Fourierrec path: split the z-stack into
    /// **even** tiles sized by [`fourierrec_tile_z`] and run [`analytic_fourierrec`]
    /// on each. Pairing `(s, s+nz/2)` is just a real-FFT packing trick, so
    /// re-pairing within each contiguous tile reconstructs the same per-slice
    /// volume; tiles concatenate in z-order. `nz` is even (checked by the caller).
    /// The current device must already be selected. Returns volume `[nz, n, n]`.
    #[allow(clippy::too_many_arguments)]
    fn analytic_fourierrec_stream(
        raw: &[f32],
        w: &[f32],
        theta: &[f32],
        nz: usize,
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        pad_side: usize,
    ) -> Result<Vec<f32>> {
        let nfreq2 = (pad / 2 + 1) * 2;
        let tile = fourierrec_tile_z(nproj, n, pad, device_free_bytes()).min(nz.max(2));
        if tile >= nz {
            return analytic_fourierrec(raw, w, theta, nz, nproj, ncols, n, pad, pad_side);
        }
        let mut out = Vec::with_capacity(nz * n * n);
        let mut z0 = 0;
        while z0 < nz {
            let t = tile.min(nz - z0); // even: even tile, even remainder
            let v = analytic_fourierrec(
                &raw[z0 * nproj * ncols..(z0 + t) * nproj * ncols],
                &w[z0 * nfreq2..(z0 + t) * nfreq2],
                theta,
                t,
                nproj,
                ncols,
                n,
                pad,
                pad_side,
            )?;
            out.extend(v);
            z0 += t;
        }
        Ok(out)
    }

    /// Disk-streaming laminography: reconstruct the output rh volume tile-by-tile
    /// and hand each finished tile to `on_tile(rh0, tlen, data)` (`data` is
    /// `[tlen, n, n]`) instead of assembling the whole `[rh, n, n]` volume in
    /// host RAM. Returns `(rh, n, n)`.
    ///
    /// Lamino cannot band its *input* (the tilt couples every detector row into
    /// every output voxel, so the whole nz stack is needed), so this streams the
    /// *output*: filter the whole stack once into host memory, then process the
    /// output rh-tiles in rounds of `k = device count` — each round back-projects
    /// up to `k` tiles concurrently (one GPU each, reading the shared read-only
    /// filtered stack), then `on_tile` is called on the **main thread** in row
    /// order and each tile is dropped. Host peak is `sino + filtered stack + k
    /// tiles`, never the whole output. `on_tile` runs single-threaded, so the
    /// caller's writer never crosses threads (H5File is `!Send`).
    ///
    /// Numerically equal to the whole-volume [`CudaBackend::reconstruct`]
    /// laminography path (same filter-to-host + accumulate-per-angle-chunk), which
    /// itself matches the un-streamed single shot to the f32 floor.
    ///
    /// Fourierrec is not separable over the output rows: it reconstructs the
    /// whole volume into host `p00` before the first tile, so its host peak is
    /// `p00` plus one tile and `on_tile` is first called after all of the work.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn reconstruct_lamino_streaming(
        sino: &Tomo<f32>,
        geom: &Geometry,
        algorithm: crate::params::Algorithm,
        params: &crate::params::ReconParams,
        norm: Option<&super::LamNorm>,
        cancel: Option<&CancelToken>,
        on_tile: &mut super::LaminoTileFn,
    ) -> Result<(usize, usize, usize)> {
        use crate::params::Algorithm;

        let Beam::Laminography { phi } = geom.beam else {
            return Err(Error::InvalidParam(
                "reconstruct_lamino_streaming requires a laminography beam".into(),
            ));
        };
        if params.dtype == crate::dtype::Dtype::F16 {
            return Err(Error::InvalidParam(
                "cuda laminography f16 path is not implemented; use the default f32 dtype".into(),
            ));
        }
        let raw = sinogram_view(sino);
        let (nz, nproj, ncols) = raw.dim();
        let n = params.num_gridx.unwrap_or(ncols);
        if n != ncols {
            return Err(Error::InvalidParam(format!(
                "cuda analytic reconstruct needs a square grid = detector width {ncols}; got {n}"
            )));
        }
        let theta = &geom.angles.0;
        if theta.len() != nproj {
            return Err(Error::ShapeMismatch {
                expected: format!("{nproj} angles"),
                found: theta.len().to_string(),
            });
        }
        // Fourier/USFFT laminography holds the whole output as `p00` and
        // emits its tiles from there; host peak is `p00` plus one tile.
        if matches!(algorithm, Algorithm::Fourierrec) {
            let lamino_angle_deg = lamino_tilt_deg(phi);
            let rh = params
                .lamino_rh
                .unwrap_or_else(|| super::lamino_recon_height(nz, lamino_angle_deg));
            let pj = sino.as_layout(Layout::Projection); // [nproj, nz, ncols]
            let proj = pj
                .array
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous projection stack".into()))?;
            let devices = selected_devices();
            ck(
                unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                "set_device",
            )?;
            analytic_lamino_fourierrec(
                proj,
                theta,
                LamFourierParams {
                    phi,
                    n,
                    rh,
                    center: geom.center.at(0),
                    filter: params.filter_name,
                },
                norm,
                cancel,
                on_tile,
            )?;
            return Ok((rh, n, n));
        }
        if !matches!(algorithm, Algorithm::Fbp | Algorithm::Linerec) {
            return Err(Error::InvalidParam(format!(
                "cuda laminography supports Fbp/Linerec/Fourierrec only; got {algorithm:?}"
            )));
        }
        // Fbp/Linerec have no stage-1 upload to fuse into; they require a
        // pre-normalized sinogram (the caller runs `normalize_dataset` for them).
        if norm.is_some() {
            return Err(Error::InvalidParam(
                "cuda laminography fused normalization (LamNorm) is Fourierrec-only".into(),
            ));
        }
        let filter = make_fbp_filter(params.filter_name, ncols, RampShape::Wint)?;
        let pad = filter.len();
        let pad_side = pad / 2 - ncols / 2;
        let w = build_filter_w(&filter, geom, nz, ncols, pad);
        let lamino_angle_deg = lamino_tilt_deg(phi);
        let rh = params
            .lamino_rh
            .unwrap_or_else(|| super::lamino_recon_height(nz, lamino_angle_deg));

        let devices = selected_devices();
        ck(
            unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
            "set_device",
        )?;
        let (host_gf, angle_chunks) =
            lamino_filter_to_host(raw, &w, pad, pad_side, device_free_bytes(), cancel)?;
        let host_gf: &[Vec<f32>] = &host_gf;
        let angle_chunks: &[(usize, usize)] = &angle_chunks;

        // Tile the output rh axis (device-0 budget/index bound), then process the
        // tiles in rounds of `k` — one tile per GPU per round.
        let ncproj_max = angle_chunks.iter().map(|&(_, l)| l).max().unwrap_or(0);
        let ncz = lamino_ncz(n, nz, ncols, ncproj_max, device_free_bytes());
        let tiles = even_z_chunks(rh, rh.div_ceil(ncz.max(1)).max(1));
        let k = devices.len().max(1);

        for round in tiles.chunks(k) {
            check_cancel(cancel)?;
            let parts: Vec<Result<Vec<f32>>> = std::thread::scope(|scope| {
                round
                    .iter()
                    .copied()
                    .zip(devices.iter().copied())
                    .map(|((tz0, tlen), dev)| {
                        scope.spawn(move || -> Result<Vec<f32>> {
                            ck(unsafe { ffi::tomoxide_cuda_set_device(dev) }, "set_device")?;
                            lamino_backproject_shard(
                                host_gf,
                                angle_chunks,
                                theta,
                                nz,
                                nproj,
                                ncols,
                                n,
                                phi,
                                tz0,
                                tlen,
                                rh,
                                device_free_bytes(),
                            )
                        })
                    })
                    .collect::<Vec<_>>()
                    .into_iter()
                    .map(|h| {
                        h.join().unwrap_or_else(|_| {
                            Err(Error::Backend("cuda lamino worker panicked".into()))
                        })
                    })
                    .collect()
            });
            for (&(tz0, tlen), part) in round.iter().zip(parts) {
                let arr = Array3::from_shape_vec((tlen, n, n), part?)
                    .map_err(|e| Error::InvalidParam(format!("cuda lamino tile shape: {e}")))?;
                on_tile(tz0, &Volume::new(arr))?;
            }
        }
        Ok((rh, n, n))
    }

    impl crate::backend::AnalyticReconstruct for CudaBackend {
        /// Fused, device-resident analytic reconstruction: upload the raw
        /// sinogram once, then pad → cuFFT filter → crop → back-projection
        /// (`Fbp`/`Linerec` via `cfunc_linerec`) or pack → `cfunc_fourierrec` →
        /// unpack (`Fourierrec`) — all on the device — and download the volume
        /// once. No per-stage host round-trips. Square grid (`n == ncols`).
        fn reconstruct(
            &self,
            sino: &Tomo<f32>,
            geom: &Geometry,
            algorithm: crate::params::Algorithm,
            params: &crate::params::ReconParams,
        ) -> Result<Volume<f32>> {
            use crate::backend::make_fbp_filter;
            use crate::params::Algorithm;

            // Parallel beam and laminography (tilted axis) are both handled here;
            // cone beam is not. Laminography routes to a dedicated out-of-core
            // single-GPU path below (its output z-extent and detector-row coupling
            // break the per-slice chunking the parallel path uses).
            if !matches!(geom.beam, Beam::Parallel | Beam::Laminography { .. }) {
                return Err(Error::InvalidParam(
                    "cuda analytic reconstruct supports parallel beam and laminography only".into(),
                ));
            }
            let s = sino.as_layout(Layout::Sinogram); // [nz, nproj, ncols], no copy if already
            let (nz, nproj, ncols) = s.array.dim();
            let n = params.num_gridx.unwrap_or(ncols);
            if n != ncols {
                return Err(Error::InvalidParam(format!(
                    "cuda analytic reconstruct needs a square grid = detector width {ncols}; got {n}"
                )));
            }
            let theta = &geom.angles.0;
            if theta.len() != nproj {
                return Err(Error::ShapeMismatch {
                    expected: format!("{nproj} angles"),
                    found: theta.len().to_string(),
                });
            }
            let raw = s
                .array
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

            let filter = make_fbp_filter(params.filter_name, ncols, RampShape::Wint)?;
            let pad = filter.len();
            let pad_side = pad / 2 - ncols / 2;
            let w = build_filter_w(&filter, geom, nz, ncols, pad);
            let nfreq2 = (pad / 2 + 1) * 2; // floats per z row of `w`

            // Laminography (tilted rotation axis): single GPU, out-of-core via
            // `analytic_lamino_stream`. The tilt couples every detector row into
            // every output voxel, so the parallel-beam per-slice/multi-GPU z-split
            // does not apply; the stack is instead chunked over projection angles
            // (accumulated) and output rh-tiles, and `rh` (recon height) differs
            // from the detector-row count `nz`. Only Fbp/Linerec (the direct
            // back-projector) and f32 are supported for now — fourierrec-lamino and
            // f16 are not wired.
            if let Beam::Laminography { phi } = geom.beam {
                if params.dtype == crate::dtype::Dtype::F16 {
                    return Err(Error::InvalidParam(
                        "cuda laminography f16 path is not implemented; use the default f32 dtype"
                            .into(),
                    ));
                }
                // Fourier/USFFT laminography (tomocupy `LamFourierRec`) — a distinct
                // whole-volume algorithm (not the linerec back-projector), so it
                // routes to its own device-resident orchestrator with the raw
                // (unfiltered; it ramp-filters internally) projections in projection
                // layout `[nproj, nz, n]`.
                if matches!(algorithm, Algorithm::Fourierrec) {
                    let lamino_angle_deg = lamino_tilt_deg(phi);
                    let rh = params
                        .lamino_rh
                        .unwrap_or_else(|| super::lamino_recon_height(nz, lamino_angle_deg));
                    let pj = sino.as_layout(Layout::Projection); // [nproj, nz, ncols]
                    let proj = pj.array.as_slice().ok_or_else(|| {
                        Error::InvalidParam("non-contiguous projection stack".into())
                    })?;
                    let devices = selected_devices();
                    ck(
                        unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                        "set_device",
                    )?;
                    // In-memory AnalyticReconstruct receives an already-normalized
                    // sinogram, so no fused correction (norm = None).
                    let mut vol = Vec::with_capacity(rh * n * n);
                    analytic_lamino_fourierrec(
                        proj,
                        theta,
                        LamFourierParams {
                            phi,
                            n,
                            rh,
                            center: geom.center.at(0),
                            filter: params.filter_name,
                        },
                        None,
                        None,
                        &mut |_, tile| {
                            vol.extend(tile.array.iter());
                            Ok(())
                        },
                    )?;
                    return Ok(Volume::new(
                        Array3::from_shape_vec((rh, n, n), vol)
                            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?,
                    ));
                }
                if !matches!(algorithm, Algorithm::Fbp | Algorithm::Linerec) {
                    return Err(Error::InvalidParam(format!(
                        "cuda laminography supports Fbp/Linerec/Fourierrec only; got {algorithm:?}"
                    )));
                }
                let lamino_angle_deg = lamino_tilt_deg(phi);
                let rh = params
                    .lamino_rh
                    .unwrap_or_else(|| super::lamino_recon_height(nz, lamino_angle_deg));
                let devices = selected_devices();
                // Multi-GPU: shard the OUTPUT rh axis across devices. Unlike
                // parallel-beam FBP (which shards detector rows = output slices),
                // laminography needs the whole nz filtered stack for any output
                // slab, so filter ONCE on device 0 into a host-resident stack, then
                // back-project disjoint rh ranges concurrently, one GPU each, each
                // reading the shared (read-only) filtered stack. Like the FBP split
                // this differs from single-GPU at the cuFFT floor (chunked filter
                // batch) but is internally deterministic. Require ≥2 output rows per
                // device so a tiny rh does not spawn idle threads.
                let k = devices.len().min(rh / 2).max(1);
                if k <= 1 {
                    ck(
                        unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                        "set_device",
                    )?;
                    let vol = analytic_lamino_stream(
                        raw, &w, theta, nz, nproj, ncols, n, pad, pad_side, phi, rh,
                    )?;
                    return Ok(Volume::new(
                        Array3::from_shape_vec((rh, n, n), vol)
                            .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?,
                    ));
                }
                ck(
                    unsafe { ffi::tomoxide_cuda_set_device(devices[0]) },
                    "set_device",
                )?;
                let (host_gf, angle_chunks) = lamino_filter_to_host(
                    s.array.view(),
                    &w,
                    pad,
                    pad_side,
                    device_free_bytes(),
                    None,
                )?;
                let host_gf: &[Vec<f32>] = &host_gf;
                let angle_chunks: &[(usize, usize)] = &angle_chunks;
                let parts: Vec<Result<Vec<f32>>> = std::thread::scope(|scope| {
                    even_z_chunks(rh, k)
                        .into_iter()
                        .zip(devices.iter().copied())
                        .map(|((rh0, rh_len), dev)| {
                            scope.spawn(move || -> Result<Vec<f32>> {
                                ck(unsafe { ffi::tomoxide_cuda_set_device(dev) }, "set_device")?;
                                lamino_backproject_shard(
                                    host_gf,
                                    angle_chunks,
                                    theta,
                                    nz,
                                    nproj,
                                    ncols,
                                    n,
                                    phi,
                                    rh0,
                                    rh_len,
                                    rh,
                                    device_free_bytes(),
                                )
                            })
                        })
                        .collect::<Vec<_>>()
                        .into_iter()
                        .map(|h| {
                            h.join().unwrap_or_else(|_| {
                                Err(Error::Backend("cuda lamino worker panicked".into()))
                            })
                        })
                        .collect()
                });
                let mut vol = Vec::with_capacity(rh * n * n);
                for p in parts {
                    vol.extend(p?);
                }
                return Ok(Volume::new(
                    Array3::from_shape_vec((rh, n, n), vol)
                        .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?,
                ));
            }

            // Kernel batch-domain minimums, same rule as `streaming()`: the
            // z-bilinear back-projection samples slice pairs (vr, vr+1), so a
            // 1-slice stack back-projects to zero (kernels_linerec.cuh
            // `vr < nz-1`), and Fourierrec packs slice pairs (s, s+nz/2) for
            // the real-FFT path, so it needs an even count. Pad the sinogram
            // (and its per-row filter weights) with zero rows and drop the pad
            // rows from the output volume.
            let nz_out = nz;
            let mut nz = nz.max(2);
            if matches!(algorithm, Algorithm::Fourierrec) && nz % 2 != 0 {
                nz += 1;
            }
            let padded: Vec<f32>;
            let raw = if nz != nz_out {
                let mut v = Vec::with_capacity(nz * nproj * ncols);
                v.extend_from_slice(raw);
                v.resize(nz * nproj * ncols, 0.0);
                padded = v;
                &padded[..]
            } else {
                raw
            };
            let mut w = w;
            w.resize(nz * nfreq2, 0.0);

            // Half-precision path (tomocupy `--dtype float16`): single GPU, whole
            // stack in one chunk. The half cuFFT filter needs a power-of-two
            // transform width, so `pad` must be a power of two. f16 tiling, the
            // async pipeline, and the multi-GPU split are not implemented here yet
            // (f16 already doubles the per-GPU capacity); a stack too large for one
            // device surfaces as a `cudaMalloc` failure.
            if params.dtype == crate::dtype::Dtype::F16 {
                if !pad.is_power_of_two() {
                    return Err(Error::InvalidParam(format!(
                        "cuda f16 analytic path needs a power-of-two padded width (half cuFFT); \
                         filter pad={pad}. Use a power-of-two detector width, or the default f32 dtype."
                    )));
                }
                let devices = selected_devices();
                ck(
                    unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                    "set_device",
                )?;
                let vol = match algorithm {
                    Algorithm::Fbp | Algorithm::Linerec => {
                        analytic_fbp_stream_f16(raw, &w, theta, nz, nproj, ncols, n, pad, pad_side)?
                    }
                    Algorithm::Fourierrec => {
                        // nz is even here by the batch-domain pad above.
                        analytic_fourierrec_f16(raw, &w, theta, nz, nproj, ncols, n, pad, pad_side)?
                    }
                    other => {
                        return Err(Error::InvalidParam(format!(
                            "cuda f16 analytic reconstruct: unsupported algorithm {other:?}"
                        )))
                    }
                };
                let mut vol = vol;
                vol.truncate(nz_out * n * n);
                return Ok(Volume::new(
                    Array3::from_shape_vec((nz_out, n, n), vol)
                        .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?,
                ));
            }

            let vol = match algorithm {
                Algorithm::Fbp | Algorithm::Linerec => {
                    let devices = selected_devices();
                    // cfunc_linerec interpolates across z, so each device's chunk
                    // must hold ≥2 slices or it back-projects to zeros. Cap the
                    // split at nz/2 GPUs: a 4-GPU nz=4 job would otherwise hand
                    // every GPU a single slice and reconstruct an all-zero volume.
                    let k = linerec_chunk_count(nz, devices.len());
                    if k <= 1 {
                        ck(
                            unsafe {
                                ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0))
                            },
                            "set_device",
                        )?;
                        analytic_fbp_stream(raw, &w, theta, nz, nproj, ncols, n, pad, pad_side)?
                    } else {
                        // Contiguous z-chunks (sizes differ by ≤1), one GPU each,
                        // run concurrently; each thread owns its device's buffers.
                        //
                        // The back-projection is deterministic and per-slice
                        // independent, but the cuFFT filter batch is nz_chunk·nproj
                        // — cuFFT picks its algorithm by batch size, so chunked vs
                        // whole-stack filtering round differently. Multi-GPU output
                        // therefore differs from single-GPU at the single-precision
                        // FFT floor (~1e-7 relative); each device is bit-identical
                        // to the others and every config is internally
                        // deterministic. Bit-exactness across device counts would
                        // require filtering the full stack on every device (4×
                        // redundant filter+upload) and is intentionally not paid.
                        //
                        // Capture as shared slices so each `move` worker copies a
                        // reference rather than moving the owned buffers.
                        let w: &[f32] = &w;
                        let parts: Vec<Result<Vec<f32>>> = std::thread::scope(|scope| {
                            even_z_chunks(nz, k)
                                .into_iter()
                                .zip(devices.iter().copied())
                                .map(|((a, len), dev)| {
                                    scope.spawn(move || -> Result<Vec<f32>> {
                                        ck(
                                            unsafe { ffi::tomoxide_cuda_set_device(dev) },
                                            "set_device",
                                        )?;
                                        analytic_fbp_stream(
                                            &raw[a * nproj * ncols..(a + len) * nproj * ncols],
                                            &w[a * nfreq2..(a + len) * nfreq2],
                                            theta,
                                            len,
                                            nproj,
                                            ncols,
                                            n,
                                            pad,
                                            pad_side,
                                        )
                                    })
                                })
                                .collect::<Vec<_>>()
                                .into_iter()
                                .map(|h| {
                                    h.join().unwrap_or_else(|_| {
                                        Err(Error::Backend("cuda analytic worker panicked".into()))
                                    })
                                })
                                .collect()
                        });
                        let mut vol = Vec::with_capacity(nz * n * n);
                        for p in parts {
                            vol.extend(p?);
                        }
                        vol
                    }
                }
                Algorithm::Fourierrec => {
                    // nz is even here by the batch-domain pad above.
                    let devices = selected_devices();
                    ck(
                        unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                        "set_device",
                    )?;
                    analytic_fourierrec_stream(raw, &w, theta, nz, nproj, ncols, n, pad, pad_side)?
                }
                other => {
                    return Err(Error::InvalidParam(format!(
                        "cuda analytic reconstruct: unsupported algorithm {other:?}"
                    )))
                }
            };

            let mut vol = vol;
            vol.truncate(nz_out * n * n);
            Ok(Volume::new(
                Array3::from_shape_vec((nz_out, n, n), vol)
                    .map_err(|e| Error::InvalidParam(format!("cuda volume shape: {e}")))?,
            ))
        }

        /// Reuse one set of device handles + uploaded grids across all streaming
        /// chunks (see `CudaFbpStream`). Handle-reusing for FBP/Linerec
        /// (`cfunc_filter`/`cfunc_linerec`), Fourierrec (`cfunc_fourierrec`), and
        /// lprec (the `LpRecDev` grids — built once here, not per chunk). Gridrec
        /// returns `None` and the caller falls back to per-chunk
        /// [`reconstruct`](crate::backend::AnalyticReconstruct::reconstruct).
        /// Binds the first selected device, as the f16 one-shot path does, since
        /// the handles are device-resident.
        fn streaming(
            &self,
            algorithm: crate::params::Algorithm,
            params: &crate::params::ReconParams,
            geom: &Geometry,
            ncols: usize,
            max_nz: usize,
        ) -> Result<Option<Box<dyn StreamingAnalytic>>> {
            use crate::params::Algorithm;
            if geom.beam != Beam::Parallel
                || !matches!(
                    algorithm,
                    Algorithm::Fbp | Algorithm::Linerec | Algorithm::Fourierrec | Algorithm::Lprec
                )
            {
                return Ok(None);
            }
            let n = params.num_gridx.unwrap_or(ncols);
            if n != ncols {
                return Ok(None); // square-grid only, like `reconstruct`
            }
            let f16 = params.dtype == crate::dtype::Dtype::F16;
            let fourier = matches!(algorithm, Algorithm::Fourierrec);
            let is_lprec = matches!(algorithm, Algorithm::Lprec);
            // The device kernels have batch-domain minimums the stream capacity
            // must respect: the z-bilinear back-projection samples slice pairs
            // (vr, vr+1), so a 1-slice batch back-projects to zero
            // (kernels_linerec.cuh `vr < nz-1`), and Fourierrec packs slice
            // pairs (s, s+max_nz/2) for the real-FFT path, so it needs an even
            // count. Allocate the stream at the padded capacity; chunks smaller
            // than capacity go through the existing partial-chunk path (zeroed
            // sino tail in `reconstruct_chunk*`, tail rows dropped in
            // `finish_recon`), which never reads the pad rows as data.
            let mut max_nz = max_nz.max(2);
            if fourier && !max_nz.is_multiple_of(2) {
                max_nz += 1;
            }
            // lprec's gather/scatter + spline runtime is f32-only (no f16 port);
            // f16 lprec falls back to the per-chunk host-interp path.
            if is_lprec && f16 {
                return Ok(None);
            }
            // `make_fbp_filter` pads to `(4·ncols).next_power_of_two()`, always a
            // power of two, so the f16 half-cuFFT width constraint holds by
            // construction (mirrors the assert in `reconstruct`).
            let filter = make_fbp_filter(params.filter_name, ncols, RampShape::Wint)?;
            let devices = selected_devices();
            ck(
                unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                "set_device",
            )?;
            // Build + upload the lprec grids once for the whole stream (the chunk
            // loop reuses them); other methods carry no grids.
            let lprec = if is_lprec {
                Some(LpRecDev::new(n, geom.angles.0.len())?)
            } else {
                None
            };
            let recon = CudaFbpStream::new(
                filter,
                &geom.angles.0,
                ncols,
                n,
                max_nz,
                f16,
                fourier,
                lprec,
            )?;
            Ok(Some(Box::new(recon)))
        }
    }

    impl FbpFilter for CudaBackend {
        /// FBP filter via the shared [`make_fbp_filter`] with
        /// [`RampShape::Wint`] — the CUDA backend ports tomocupy, so it builds
        /// tomocupy's `_wint` quadrature ramp (the CPU/wgpu backends build
        /// tomopy's linear ramp). Apodization/padding/layout are shared.
        fn make_filter(&self, name: FilterName, n: usize) -> Result<Vec<f32>> {
            make_fbp_filter(name, n, RampShape::Wint)
        }

        /// FBP filtering on the GPU via tomocupy's `cfunc_filter` (cuFFT R2C →
        /// ×w → C2R). The complex weight `w` folds the same ramp, signed-
        /// frequency centre-shift phase, and `1/ne` normalization the CPU
        /// `FbpFilter` uses, so the result matches the CPU filter (to the FFT
        /// f32 floor). Edge-replicate padding to `ne = filter.len()`.
        fn apply(&self, sino: &mut Tomo<f32>, filter: &[f32], geom: &Geometry) -> Result<()> {
            let pad = filter.len();
            if pad == 0 {
                return Err(Error::InvalidParam("empty filter".into()));
            }
            let orig = sino.layout;
            let s = sino.as_layout(Layout::Sinogram); // [nz, nproj, ncols], no copy if already
            let (nz, nproj, ncols) = s.array.dim();
            if pad < ncols {
                return Err(Error::ShapeMismatch {
                    expected: format!(">= {ncols} (n_cols)"),
                    found: pad.to_string(),
                });
            }
            let pad_side = pad / 2 - ncols / 2;
            let src = s
                .array
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

            // Complex weight `w` [nz, pad/2+1] — small (≈ nz·pad·8 B) and
            // per-z (folds `geom.center.at(z)`). Built whole once, then sliced by
            // z-tile so each tile keeps its own slices' centre-shift phases.
            let nfreq = pad / 2 + 1;
            let w = build_filter_w(filter, geom, nz, ncols, pad);

            // The padded device buffer `tile·nproj·pad` and the filter's internal
            // R2C buffer index in 32-bit `int`, so the z-stack is processed in
            // tiles kept strictly under 2³¹ elements and inside free memory (same
            // overflow class the fused path tiles via `analytic_fbp_stream`).
            // Unfiltered `nz·nproj·pad` faulted lprec at nd=2048, nz=256 (= 2³¹).
            let tile = filter_tile_z(nproj, pad, device_free_bytes()).min(nz.max(1));
            let mut out = vec![0.0f32; nz * nproj * ncols];
            let mut z0 = 0;
            while z0 < nz {
                let tz = tile.min(nz - z0);

                // Padded real sinogram for this z-tile [tz, nproj, pad],
                // edge-replicated borders.
                let mut g = vec![0.0f32; tz * nproj * pad];
                for z in 0..tz {
                    for p in 0..nproj {
                        let row = ((z0 + z) * nproj + p) * ncols;
                        let first = src[row];
                        let last = src[row + ncols - 1];
                        let dst = (z * nproj + p) * pad;
                        for x in 0..pad_side {
                            g[dst + x] = first;
                        }
                        for x in 0..ncols {
                            g[dst + pad_side + x] = src[row + x];
                        }
                        for x in (pad_side + ncols)..pad {
                            g[dst + x] = last;
                        }
                    }
                }

                let g_dev = DevBuf::from_host_f32(&g)?;
                let w_dev = DevBuf::from_host_f32(&w[z0 * nfreq * 2..(z0 + tz) * nfreq * 2])?;
                let handle = Handle::new(
                    unsafe { ffi::tomoxide_filter_new(nproj, tz, pad) },
                    ffi::tomoxide_filter_free,
                    "cfunc_filter",
                )?;
                unsafe {
                    ck(
                        ffi::tomoxide_filter_apply(
                            handle.ptr,
                            g_dev.ptr,
                            w_dev.ptr,
                            std::ptr::null_mut(),
                        ),
                        "filter_apply",
                    )?;
                }
                let rc = unsafe { ffi::tomoxide_cuda_sync() };
                drop(handle);
                if rc != 0 {
                    return Err(Error::Backend(format!("cuda filter sync failed ({rc})")));
                }
                g_dev.to_host_f32(&mut g)?;

                // Crop the centred [pad_side, pad_side+ncols) window back to ncols
                // into this tile's z-slices of the output.
                for z in 0..tz {
                    for p in 0..nproj {
                        let dst = ((z0 + z) * nproj + p) * ncols;
                        let srcp = (z * nproj + p) * pad + pad_side;
                        out[dst..dst + ncols].copy_from_slice(&g[srcp..srcp + ncols]);
                    }
                }
                z0 += tz;
            }

            let arr = Array3::from_shape_vec((nz, nproj, ncols), out)
                .map_err(|e| Error::InvalidParam(format!("cuda filter shape: {e}")))?;
            *sino = Tomo::new(arr, Layout::Sinogram).to_layout(orig);
            Ok(())
        }
    }

    /// Devices to spread the per-slice loop over. Default is **all** visible
    /// devices (multi-GPU); `TOMOXIDE_CUDA_DEVICES` overrides with a
    /// comma-separated index list — e.g. `0` pins a single GPU, `0,2` uses two.
    /// Out-of-range / unparsable entries are dropped; an empty result falls back
    /// to device 0.
    pub(super) fn selected_devices() -> Vec<i32> {
        let count = unsafe { ffi::tomoxide_cuda_device_count() }.max(0);
        if let Ok(s) = std::env::var("TOMOXIDE_CUDA_DEVICES") {
            if !s.trim().is_empty() {
                let v: Vec<i32> = s
                    .split(',')
                    .filter_map(|t| t.trim().parse::<i32>().ok())
                    .filter(|&d| d >= 0 && d < count)
                    .collect();
                return if v.is_empty() { vec![0] } else { v };
            }
        }
        if count <= 0 {
            vec![0]
        } else {
            (0..count).collect()
        }
    }

    /// Hard ceiling on a single CUDA buffer's element count. The vendored
    /// tomocupy kernels compute linear indices in 32-bit `int`, so any buffer
    /// whose element count reaches 2³¹ overflows to a negative index and writes
    /// out of bounds (SIGSEGV). Streaming keeps every tile's largest buffer
    /// strictly under this — independent of how much memory is free.
    const I32_INDEX_LIMIT: usize = i32::MAX as usize; // 2³¹ − 1

    /// Free memory (bytes) on the **current** device. Caller must have already
    /// `cudaSetDevice`'d the device it means to allocate on. Falls back to a
    /// conservative 2 GiB if the query fails, so streaming still makes progress.
    fn device_free_bytes() -> usize {
        // Test/debug hook: cap the reported free memory to force the streaming
        // tiler + async pipeline onto stacks that would otherwise fit one chunk
        // (the only way to exercise the out-of-core path on a large GPU).
        if let Some(v) = std::env::var_os("TOMOXIDE_CUDA_MAX_FREE_BYTES") {
            if let Some(n) = v.to_str().and_then(|s| s.trim().parse::<usize>().ok()) {
                return n;
            }
        }
        let mut free: usize = 0;
        let mut total: usize = 0;
        let rc = unsafe { ffi::tomoxide_cuda_mem_info(&mut free, &mut total) };
        if rc == 0 && free > 0 {
            free
        } else {
            2 * 1024 * 1024 * 1024
        }
    }

    /// Total memory (bytes) on the **current** device. Caller must have already
    /// `cudaSetDevice`'d the device it means to query. Falls back to a
    /// conservative 8 GiB if the query fails.
    ///
    /// Used to size the per-slice worker pool: unlike free memory, total is a
    /// stable property of the GPU and does not shrink as thread-local cuFFT plan
    /// caches fill up, so the in-flight cap it yields is the same on every
    /// reconstruction (free memory would collapse the cap once plans are cached).
    fn device_total_bytes() -> usize {
        let mut free: usize = 0;
        let mut total: usize = 0;
        let rc = unsafe { ffi::tomoxide_cuda_mem_info(&mut free, &mut total) };
        if rc == 0 && total > 0 {
            total
        } else {
            8 * 1024 * 1024 * 1024
        }
    }

    /// Largest z-tile for the fused Fbp/Linerec path on the current device.
    /// Bounded by BOTH (a) the 32-bit index ceiling on the padded buffer
    /// `tile·nproj·pad`, and (b) ~80% of free device memory against the
    /// per-z footprint (sino + padded + cropped + volume + the filter's own
    /// internal R2C buffers, ≈ padded again). When `tex_array` is set (the f16
    /// path), one more cropped-sinogram-sized buffer is added for
    /// cfunc_linerec's hardware-interpolation texture array. Always ≥ 1.
    fn fbp_tile_z(
        nproj: usize,
        ncols: usize,
        n: usize,
        pad: usize,
        free_bytes: usize,
        tex_array: bool,
    ) -> usize {
        let fsz = std::mem::size_of::<f32>();
        // Per-z device bytes (conservative: cfunc_filter allocates ~one more
        // padded buffer internally, so count `nproj·pad` twice). The trailing
        // `nproj·ncols` (f16 only) is cfunc_linerec's layered texture array,
        // a second copy of the cropped filtered sinogram, so tiling does not
        // OOM on it.
        let tex = if tex_array { nproj * ncols } else { 0 };
        let per_z = (nproj * ncols + 2 * nproj * pad + nproj * ncols + n * n + tex) * fsz;
        let by_mem = (free_bytes / 100 * 80) / per_z.max(1);
        // 88% of 2³¹ over the dominant per-z stride leaves >200M headroom for the
        // in-plane offset terms the kernels add on top of `z·nproj·pad`.
        let by_idx = (I32_INDEX_LIMIT / 100 * 88) / (nproj * pad).max(1);
        by_mem.min(by_idx).max(1)
    }

    /// Single owner of cfunc_linerec's "chunk needs ≥2 z-slices" invariant: the
    /// kernel interpolates the back-projection vertically across slices, so a
    /// chunk holding a single slice reconstructs to **all zeros**. Given a desired
    /// number of contiguous z-chunks `want` (device count for the multi-GPU split,
    /// or the memory/index tile count for single-GPU streaming), returns a count
    /// that keeps an even split at ≥2 slices per chunk — capped at `nz/2`, floored
    /// at 1. `nz < 4` collapses to a single whole-stack chunk (two ≥2 chunks don't
    /// fit); `nz < 2` is the kernel's own single-slice degenerate case, closed by
    /// the batch-domain zero-pad in `reconstruct`/`streaming` (both hand the
    /// kernels ≥2 slices).
    fn linerec_chunk_count(nz: usize, want: usize) -> usize {
        want.min(nz / 2).max(1)
    }

    /// Split `nz` into `k` contiguous chunks whose lengths differ by at most one
    /// (the first `nz % k` chunks get one extra slice), as `(start, len)` pairs
    /// summing to `nz`. With `k` from [`linerec_chunk_count`] every chunk holds
    /// ≥2 slices, so no chunk back-projects to zeros.
    fn even_z_chunks(nz: usize, k: usize) -> Vec<(usize, usize)> {
        let base = nz / k;
        let rem = nz % k;
        let mut chunks = Vec::with_capacity(k);
        let mut z0 = 0;
        for i in 0..k {
            let len = base + if i < rem { 1 } else { 0 };
            chunks.push((z0, len));
            z0 += len;
        }
        chunks
    }

    /// Largest z-tile for the **composed** FBP filter (`FbpFilter::apply`, used by
    /// the gridrec/lprec path, which filters before its own back-projection).
    /// Same 32-bit ceiling as the fused path: the padded device buffer
    /// `tile·nproj·pad` and the filter's internal R2C complex buffer both index
    /// in `int`, so a single tile of `nz·nproj·pad ≥ 2³¹` overflows (lprec at
    /// nd=2048, nz=256 hits exactly 2³¹ and SIGSEGVs). Bound by 88% of 2³¹ over
    /// `nproj·pad` and ~80% of free memory over the per-z device footprint
    /// (padded buffer + the internal R2C buffer, ≈ padded again).
    fn filter_tile_z(nproj: usize, pad: usize, free_bytes: usize) -> usize {
        let fsz = std::mem::size_of::<f32>();
        let per_z = 2 * nproj * pad * fsz;
        let by_mem = (free_bytes / 100 * 80) / per_z.max(1);
        let by_idx = (I32_INDEX_LIMIT / 100 * 88) / (nproj * pad).max(1);
        by_mem.min(by_idx).max(1)
    }

    /// Largest z-tile (in real slices) for the fused Fourierrec path. The
    /// oversampled grid is `(2n+2m)²` complex per *pair* (= 2 real slices), and
    /// `cfunc_fourierrec` indexes it with `int`, so the pair count
    /// `tile/2 · (2n+2m)²` must stay under the 32-bit ceiling; memory is bounded
    /// by the same grid (`fde`) which dominates. Returned value is **even**
    /// (pairs) and ≥ 2.
    fn fourierrec_tile_z(nproj: usize, n: usize, pad: usize, free_bytes: usize) -> usize {
        let fsz = std::mem::size_of::<f32>();
        // m = ceil(2n·(1/π)·sqrt(-mu·ln eps + (mu·n)²/4)) with eps=1e-3; for the
        // sizes we run this is 4, so 2n+2m = 2n+8.
        let stride = 2 * n + 8;
        let grid_pair = stride * stride * 2 * fsz; // real2 grid per pair (fde)
                                                   // Per-pair device bytes: fde grid + padded/cropped/packed/output buffers
                                                   // (≈ 2·nproj·pad real for the padded stages, plus n·n complex output).
        let per_pair = grid_pair + (2 * nproj * pad + 4 * n * n) * fsz;
        let by_mem = (free_bytes / 100 * 80) / per_pair.max(1); // pairs
                                                                // 88% of 2³¹, in *pairs*, bounded by BOTH index-bearing stages: the
                                                                // padded buffer (`z·nproj·pad`, z = 2·pairs real slices) and the
                                                                // oversampled grid (`pair·stride²`). The grid's gather adds an in-plane
                                                                // offset up to ~6n·stride on top, which the 12% headroom absorbs.
        let margin = I32_INDEX_LIMIT / 100 * 88;
        let by_pad = margin / (2 * nproj * pad).max(1);
        let by_grid = margin / (stride * stride).max(1);
        let pairs = by_mem.min(by_pad).min(by_grid).max(1);
        (pairs * 2).max(2)
    }

    /// One device-pinned rayon pool per selected GPU, built once. Each pool's
    /// worker threads call `cudaSetDevice` at startup, so their `cudaMalloc`,
    /// cuFFT plans (thread-local cache), and per-thread default stream all land
    /// on that GPU. Host cores are split evenly across the pools.
    struct DevicePools {
        devices: Vec<i32>,
        pools: Vec<ThreadPool>,
    }

    fn device_pools() -> &'static DevicePools {
        static POOLS: OnceLock<DevicePools> = OnceLock::new();
        POOLS.get_or_init(|| {
            let devices = selected_devices();
            let total = std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1);
            let per = (total / devices.len().max(1)).max(1);
            let pools = devices
                .iter()
                .map(|&dev| {
                    ThreadPoolBuilder::new()
                        .num_threads(per)
                        .start_handler(move |_| {
                            // A start handler cannot return an error and `dev` is in
                            // range (`selected_devices`); a refused bind leaves the
                            // worker on device 0.
                            let _ = unsafe { ffi::tomoxide_cuda_set_device(dev) };
                        })
                        .build()
                        .expect("build cuda device pool")
                })
                .collect();
            DevicePools { devices, pools }
        })
    }

    /// A device-pinned rayon pool sized to exactly `nthreads`, built once per
    /// `(device, nthreads)` and cached for the process lifetime.
    ///
    /// The per-slice loop runs here instead of on the full host-core pool so that
    /// the number of *distinct* worker threads equals the in-flight cap. That
    /// matters because each worker lazily creates a **thread-local cuFFT plan**
    /// (see `cuda/fft.cu`) that is never destroyed: if the loop fanned across all
    /// 96 host cores, up to 96 oversampled `(2n)²` plan workspaces would
    /// accumulate and exhaust VRAM at large `n` (one GPU OOMs, or the next
    /// reconstruction sees no free memory and collapses to a serial cap). Pinning
    /// the loop to `nthreads = max_inflight` makes plan-count == concurrency ==
    /// cap by construction — one number governs both. Pools are leaked (process
    /// lifetime, like `device_pools`) so plans persist and are reused; only a
    /// handful of distinct `(device, nthreads)` keys arise per run.
    fn slice_pool(device: i32, nthreads: usize) -> &'static ThreadPool {
        static REG: OnceLock<Mutex<HashMap<(i32, usize), &'static ThreadPool>>> = OnceLock::new();
        let reg = REG.get_or_init(|| Mutex::new(HashMap::new()));
        let mut m = reg.lock().unwrap();
        if let Some(p) = m.get(&(device, nthreads)) {
            return p;
        }
        let pool: &'static ThreadPool = Box::leak(Box::new(
            ThreadPoolBuilder::new()
                .num_threads(nthreads.max(1))
                .start_handler(move |_| {
                    // A start handler cannot return an error and `device` is in
                    // range; a refused bind leaves the worker on device 0.
                    let _ = unsafe { ffi::tomoxide_cuda_set_device(device) };
                })
                .build()
                .expect("build cuda slice pool"),
        ));
        m.insert((device, nthreads), pool);
        pool
    }

    /// How many per-slice reconstructions may run concurrently on one device —
    /// which is also the worker-thread count handed to [`slice_pool`], so it
    /// bounds VRAM by construction (one thread ⇒ one in-flight slice ⇒ one
    /// persistent cuFFT plan).
    ///
    /// Each worker holds, for the lifetime of the process, an oversampled `(2n)²`
    /// cuFFT plan workspace, plus — while a slice is in flight — its `(2n)²`
    /// complex grid and padded staging buffers. The persistent plan dominates at
    /// large `n`, so the budget is taken against **total** device memory (a stable
    /// figure) rather than free memory: free memory shrinks as plans are cached,
    /// which would make the cap collapse on the second reconstruction. Cap at
    /// ~70% of total over a per-slice footprint of 6× the `(2n)²` grid (grid +
    /// plan workspace + staging), clamped to the host-core budget. Smaller `n`
    /// clamps to the pool size (plans are tiny, full host parallelism is kept).
    /// `TOMOXIDE_CUDA_MAX_INFLIGHT` overrides the computed value.
    fn max_inflight(n: usize, total_bytes: usize, pool_threads: usize) -> usize {
        if let Ok(s) = std::env::var("TOMOXIDE_CUDA_MAX_INFLIGHT") {
            if let Ok(v) = s.trim().parse::<usize>() {
                if v >= 1 {
                    return v.min(pool_threads);
                }
            }
        }
        // 6× the (2n)² complex grid covers the persistent plan workspace + the
        // in-flight grid + padded staging; calibrated so large-n fits VRAM with
        // headroom (e.g. n=2048 → ~27 of 32 GB) while small-n stays pool-bound.
        let per_slice = 6 * (2 * n) * (2 * n) * std::mem::size_of::<crate::dtype::Complex32>();
        let by_mem = (total_bytes / 100 * 70) / per_slice.max(1);
        by_mem.clamp(1, pool_threads.max(1))
    }

    impl crate::backend::Fft for CudaBackend {
        /// Fan the per-slice loop across the selected GPUs (and host cores).
        /// Slices are partitioned into one contiguous chunk per device; each
        /// chunk runs on that device's `slice_pool` — a pinned pool sized to the
        /// device's in-flight cap — all devices concurrently.
        ///
        /// Bit-identical regardless of device count: each slice's cuFFT uses a
        /// fixed per-slice batch (independent of how slices are spread), and the
        /// host gather/deapodize is deterministic f32 — so gridrec/lprec/phase
        /// give max|Δ|=0 single-GPU vs multi-GPU. (This is *not* true of the
        /// fused filter path, whose batch scales with the chunk; see
        /// `analytic_fbp_chunk`'s caller.) Note gridrec is host-gather bound:
        /// one GPU already saturates the host cores, so extra GPUs help the
        /// GPU-heavier lprec/phase far more than gridrec.
        fn for_each_slice(
            &self,
            out: &mut Array3<f32>,
            f: &(dyn Fn(usize, ArrayViewMut2<f32>) -> Result<()> + Sync),
        ) -> Result<()> {
            let dp = device_pools();
            let d = dp.devices.len();
            let n = out.shape()[1]; // square recon grid width, before `out` is borrowed
            let slabs: Vec<ArrayViewMut2<f32>> = out.axis_iter_mut(Axis(0)).collect();
            let nz = slabs.len();

            // Single device: run on a pinned pool sized to `max_inflight`, so the
            // in-flight slice count == worker count == persistent cuFFT plan count
            // (see `slice_pool` / `max_inflight`). Total VRAM (queried on a pinned
            // worker) gives a stable cap that does not collapse once plans cache.
            if d <= 1 {
                let threads = dp.pools[0].current_num_threads();
                let total = dp.pools[0].install(device_total_bytes);
                let inflight = max_inflight(n, total, threads);
                let pool = slice_pool(dp.devices[0], inflight);
                return pool.install(move || {
                    slabs
                        .into_par_iter()
                        .enumerate()
                        .try_for_each(|(row, slab)| f(row, slab))
                });
            }

            // Multi-GPU: contiguous chunks (sizes differ by ≤1), one per device.
            let base = nz / d;
            let rem = nz % d;
            let mut chunks: Vec<(usize, Vec<ArrayViewMut2<f32>>)> = Vec::with_capacity(d);
            let mut remaining = slabs;
            let mut offset = 0;
            for i in 0..d {
                let len = base + if i < rem { 1 } else { 0 };
                let tail = remaining.split_off(len);
                chunks.push((offset, remaining));
                remaining = tail;
                offset += len;
            }

            std::thread::scope(|scope| -> Result<()> {
                let handles: Vec<_> = chunks
                    .into_iter()
                    .zip(dp.pools.iter())
                    .zip(dp.devices.iter())
                    .map(|(((off, chunk), pool), &dev)| {
                        scope.spawn(move || -> Result<()> {
                            // Size this device's per-slice pool to its in-flight
                            // cap (total VRAM queried on a worker pinned to `dev`),
                            // matching the single-GPU path so plan-count == cap.
                            let threads = pool.current_num_threads();
                            let total = pool.install(device_total_bytes);
                            let inflight = max_inflight(n, total, threads);
                            let spool = slice_pool(dev, inflight);
                            spool.install(|| {
                                chunk
                                    .into_par_iter()
                                    .enumerate()
                                    .try_for_each(|(i, slab)| f(off + i, slab))
                            })
                        })
                    })
                    .collect();
                for h in handles {
                    h.join()
                        .map_err(|_| Error::Backend("cuda slice worker panicked".into()))??;
                }
                Ok(())
            })
        }

        fn fft_1d(
            &self,
            buf: &mut [crate::dtype::Complex32],
            len: usize,
            batch: usize,
            inverse: bool,
        ) -> Result<()> {
            if len == 0 || batch == 0 {
                return Ok(());
            }
            if buf.len() != len * batch {
                return Err(Error::ShapeMismatch {
                    expected: (len * batch).to_string(),
                    found: buf.len().to_string(),
                });
            }
            let flat = complex_as_f32_mut(buf);
            with_fft_scratch(std::mem::size_of_val(flat), |d| {
                d.copy_from_host_f32(flat)?;
                ck(
                    unsafe { ffi::tomoxide_fft_1d(d.ptr, len, batch, inverse as i32) },
                    "fft_1d",
                )?;
                d.to_host_f32(flat)
            })
        }

        fn fft_2d(
            &self,
            buf: &mut [crate::dtype::Complex32],
            rows: usize,
            cols: usize,
            batch: usize,
            inverse: bool,
        ) -> Result<()> {
            if rows == 0 || cols == 0 || batch == 0 {
                return Ok(());
            }
            if buf.len() != rows * cols * batch {
                return Err(Error::ShapeMismatch {
                    expected: (rows * cols * batch).to_string(),
                    found: buf.len().to_string(),
                });
            }
            let flat = complex_as_f32_mut(buf);
            with_fft_scratch(std::mem::size_of_val(flat), |d| {
                d.copy_from_host_f32(flat)?;
                ck(
                    unsafe { ffi::tomoxide_fft_2d(d.ptr, rows, cols, batch, inverse as i32) },
                    "fft_2d",
                )?;
                d.to_host_f32(flat)
            })
        }
    }

    /// Reinterpret a `Complex32` slice as the equivalent interleaved
    /// `[re, im, …]` f32 slice — zero-copy, both for upload and for receiving the
    /// transform back in place.
    ///
    /// Sound because `Complex32 = num_complex::Complex<f32>` is `#[repr(C)]` with
    /// fields `{ re: f32, im: f32 }`, so `N` complex values occupy exactly the
    /// same bytes as `2N` contiguous f32 (matching cuFFT's `cufftComplex`). This
    /// replaces the per-call interleave/deinterleave `Vec<f32>` allocate-and-copy
    /// in `fft_1d`/`fft_2d` — the dominant host overhead of the composed path.
    fn complex_as_f32_mut(buf: &mut [crate::dtype::Complex32]) -> &mut [f32] {
        let len = buf.len() * 2;
        unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut f32, len) }
    }

    impl Elementwise for CudaBackend {
        /// `(data − mean(dark)) / max(mean(flat) − mean(dark), 1e-6)` on the GPU
        /// (tomocupy `darkflat_correction`). Frame averages and the clamped
        /// denominator are computed host-side; the per-projection broadcast runs
        /// on the device.
        fn darkflat(
            &self,
            data: &mut Tomo<f32>,
            flat: &Frames<f32>,
            dark: &Frames<f32>,
        ) -> Result<()> {
            let (dark2d, denom) = crate::prep::normalize::darkflat_frames(flat, dark)?;

            let restore = data.layout == Layout::Sinogram;
            if restore {
                *data = data.to_layout(Layout::Projection);
            }
            let (nproj, nz, nx) = data.array.dim();
            {
                let host = data
                    .array
                    .as_slice()
                    .ok_or_else(|| Error::InvalidParam("non-contiguous data".into()))?;
                let d_data = DevBuf::from_host_f32(host)?;
                let d_dark = DevBuf::from_host_f32(dark2d.as_slice().expect("contiguous dark2d"))?;
                let d_denom = DevBuf::from_host_f32(denom.as_slice().expect("contiguous denom"))?;
                let rc = unsafe {
                    ffi::tomoxide_darkflat(
                        d_data.ptr,
                        d_dark.ptr,
                        d_denom.ptr,
                        nproj,
                        nz,
                        nx,
                        std::ptr::null_mut(),
                    )
                };
                if rc != 0 {
                    return Err(Error::Backend(format!("cuda darkflat failed ({rc})")));
                }
                let sync = unsafe { ffi::tomoxide_cuda_sync() };
                if sync != 0 {
                    return Err(Error::Backend(format!(
                        "cuda darkflat sync failed ({sync})"
                    )));
                }
                let out = data
                    .array
                    .as_slice_mut()
                    .ok_or_else(|| Error::InvalidParam("non-contiguous data".into()))?;
                d_data.to_host_f32(out)?;
            }
            if restore {
                *data = data.to_layout(Layout::Sinogram);
            }
            Ok(())
        }

        /// In-place `−ln(max(x, 1e-6))` (non-finite → 0) on the GPU.
        fn minus_log(&self, data: &mut Tomo<f32>) -> Result<()> {
            let n = data.array.len();
            let host = data
                .array
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous data".into()))?;
            let d_data = DevBuf::from_host_f32(host)?;
            let rc = unsafe { ffi::tomoxide_minuslog(d_data.ptr, n, std::ptr::null_mut()) };
            if rc != 0 {
                return Err(Error::Backend(format!("cuda minus_log failed ({rc})")));
            }
            let sync = unsafe { ffi::tomoxide_cuda_sync() };
            if sync != 0 {
                return Err(Error::Backend(format!(
                    "cuda minus_log sync failed ({sync})"
                )));
            }
            let out = data
                .array
                .as_slice_mut()
                .ok_or_else(|| Error::InvalidParam("non-contiguous data".into()))?;
            d_data.to_host_f32(out)?;
            Ok(())
        }
    }

    impl FourierReconstruct for CudaBackend {
        /// Fourier-gridding reconstruction via tomocupy's `cfunc_fourierrec`.
        ///
        /// The kernel processes `nz/2` **complex** slice-pairs: slice `s` and
        /// `s + nz/2` of the filtered sinogram are packed into the real/imag of
        /// one complex slice (tomocupy `FourierRec.backprojection`), and the
        /// output volume is de-interleaved the same way. Requires an even slice
        /// count and a square grid `n == ncols`. The FBP filter (incl. the
        /// rotation-centre shift) is applied by the caller, so the kernel is
        /// centre-agnostic. Output carries tomocupy's grid convention (verified
        /// by scale/flip-invariant correlation vs the CPU `fourierrec`).
        fn reconstruct(
            &self,
            filtered: &Tomo<f32>,
            geom: &Geometry,
            n: usize,
        ) -> Result<Volume<f32>> {
            let s = filtered.as_layout(Layout::Sinogram); // [nz, nproj, ncols], no copy if already
            let nz_out = s.n_rows();
            let nproj = s.n_angles();
            let ncols = s.n_cols();
            // The complex pairing needs an even slice count; pad an odd stack
            // with one zero slice (same batch-domain rule as the analytic
            // paths) and drop the pad row from the output.
            let nz = nz_out + nz_out % 2;
            if n != ncols {
                return Err(Error::InvalidParam(format!(
                    "cuda fourierrec needs a square grid = detector width {ncols}; got {n}"
                )));
            }
            let theta = &geom.angles.0;
            if theta.len() != nproj {
                return Err(Error::ShapeMismatch {
                    expected: format!("{nproj} angles"),
                    found: theta.len().to_string(),
                });
            }
            let src = s
                .array
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

            // Pack slice pairs (s, s+nz/2) into interleaved complex: for each
            // complex element [s, p, x], re = filtered[s], im = filtered[s+nz/2].
            let half = nz / 2;
            // Rows at or past `nz_out` are the zero pad of an odd stack.
            let at = |row: usize, p: usize, x: usize| {
                if row < nz_out {
                    src[row * nproj * ncols + p * ncols + x]
                } else {
                    0.0
                }
            };
            let mut g = vec![0.0f32; nz * nproj * ncols];
            for sp in 0..half {
                for p in 0..nproj {
                    for x in 0..ncols {
                        let idx = sp * nproj * ncols + p * ncols + x;
                        g[2 * idx] = at(sp, p, x);
                        g[2 * idx + 1] = at(sp + half, p, x);
                    }
                }
            }

            let g_dev = DevBuf::from_host_f32(&g)?;
            let theta_dev = DevBuf::from_host_f32(theta)?;
            // Output: complex [nz/2, n, n] = nz*n*n floats.
            let f_dev = DevBuf::zeroed(nz * n * n * std::mem::size_of::<f32>())?;

            let handle = Handle::new(
                unsafe {
                    ffi::tomoxide_fourierrec_new(nproj, half, n, theta_dev.ptr as *const f32)
                },
                ffi::tomoxide_fourierrec_free,
                "cfunc_fourierrec",
            )?;
            unsafe {
                ck(
                    ffi::tomoxide_fourierrec_backproject(
                        handle.ptr,
                        f_dev.ptr,
                        g_dev.ptr,
                        std::ptr::null_mut(),
                    ),
                    "fourierrec_backproject",
                )?;
            }
            let rc = unsafe { ffi::tomoxide_cuda_sync() };
            drop(handle);
            if rc != 0 {
                return Err(Error::Backend(format!(
                    "cuda fourierrec sync failed ({rc})"
                )));
            }

            let mut fbuf = vec![0.0f32; nz * n * n];
            f_dev.to_host_f32(&mut fbuf)?;
            // De-interleave: re → slice sp, im → slice sp+nz/2.
            let mut vol = vec![0.0f32; nz * n * n];
            for sp in 0..half {
                for y in 0..n {
                    for x in 0..n {
                        let idx = sp * n * n + y * n + x;
                        vol[sp * n * n + y * n + x] = fbuf[2 * idx];
                        vol[(sp + half) * n * n + y * n + x] = fbuf[2 * idx + 1];
                    }
                }
            }
            vol.truncate(nz_out * n * n);
            Ok(Volume::new(
                Array3::from_shape_vec((nz_out, n, n), vol)
                    .map_err(|e| Error::InvalidParam(format!("cuda fourierrec shape: {e}")))?,
            ))
        }
    }

    /// Device-resident log-polar geometry grids plus the per-chunk runtime,
    /// shared by the whole-volume [`LpRecReconstruct`] path and the streaming
    /// reconstructor ([`CudaFbpStream`]). Built once — host `build_grids` then a
    /// single upload — and reused across every tile/chunk, so a streamed job pays
    /// the (host) precompute and the grid upload exactly once.
    struct LpRecDev {
        ntheta: usize,
        nrho: usize,
        n_lp: usize,
        n_w: usize,
        n_c: usize,
        /// Full Hermitian convolution kernel `[nrho, ntheta]` (folds the
        /// deapodization + the tomocupy constant).
        kfull: DevBuf,
        /// Span-independent target index sets (i32).
        lpids: DevBuf,
        wids: DevBuf,
        cids: DevBuf,
        /// Per-span coordinate arrays, NSPAN spans concatenated contiguously
        /// (span `k` lives at offset `k * npts`).
        lp2p1: DevBuf,
        lp2p2: DevBuf,
        lp2p1w: DevBuf,
        lp2p2w: DevBuf,
        c2lp1: DevBuf,
        c2lp2: DevBuf,
    }

    impl LpRecDev {
        /// Precompute the log-polar grids on the host (`fft` backs the small
        /// precompute transforms — the CUDA backend's own Fft is fine) and upload
        /// them.
        fn new(n: usize, nproj: usize) -> Result<Self> {
            use crate::recon::lprec::{build_grids, LP_NSPAN};
            // build_grids' handful of small setup FFTs (adjoint zeta kernel + two
            // 1-D B-spline transforms) are one-time HOST precompute whose result
            // feeds the device kernels; running them on the CUDA backend round-trips
            // each to the GPU (the batched nthetalarge×nrho transform alone is a
            // large buffer). Use the in-process CPU rustfft instead — no PCIe
            // traffic, and the precompute FFT backend is output-neutral (see the
            // wgpu lprec precompute change). Cuts ~45ms off build_grids at 1024².
            let grids = build_grids(n, nproj, &crate::cpu::CpuBackend::new())?;
            let kfull_f32: &[f32] = unsafe {
                std::slice::from_raw_parts(
                    grids.kfull.as_ptr() as *const f32,
                    grids.kfull.len() * 2,
                )
            };
            // The log-polar function is real, so the per-span convolution runs as
            // an in-place R2C → cmul → C2R. The spectrum is the half-complex
            // `[nrho, ntheta_c]` (ntheta_c = ntheta/2+1, the conjugate-symmetric
            // half), so `kfull` — the FFT of a real kernel, hence Hermitian — is
            // cropped to its first `ntheta_c` columns per row to match.
            let (nrho, ntheta) = (grids.nrho, grids.ntheta);
            let ntheta_c = ntheta / 2 + 1;
            let ntheta_pad = 2 * ntheta_c;
            let mut kfull_half = Vec::with_capacity(nrho * ntheta_c * 2);
            for row in 0..nrho {
                let base = row * ntheta * 2;
                for col in 0..ntheta_c {
                    kfull_half.push(kfull_f32[base + col * 2]);
                    kfull_half.push(kfull_f32[base + col * 2 + 1]);
                }
            }
            let to_i32 = |v: &[usize]| -> Vec<i32> { v.iter().map(|&x| x as i32).collect() };
            // Gather targets index the `[nrho, ntheta]` grid row-major; remap them
            // to the padded real layout (row stride ntheta_pad) used in place by
            // the R2C buffer. cids (Cartesian-output indices) are unaffected.
            let to_padded_i32 = |v: &[usize]| -> Vec<i32> {
                v.iter()
                    .map(|&t| ((t / ntheta) * ntheta_pad + (t % ntheta)) as i32)
                    .collect()
            };
            let concat = |spans: &[Vec<f32>; LP_NSPAN]| -> Vec<f32> {
                let mut v = Vec::with_capacity(spans.iter().map(Vec::len).sum());
                for sp in spans {
                    v.extend_from_slice(sp);
                }
                v
            };
            Ok(LpRecDev {
                ntheta: grids.ntheta,
                nrho: grids.nrho,
                n_lp: grids.lpids.len(),
                n_w: grids.wids.len(),
                n_c: grids.cids.len(),
                kfull: DevBuf::from_host_f32(&kfull_half)?,
                lpids: DevBuf::from_host_i32(&to_padded_i32(&grids.lpids))?,
                wids: DevBuf::from_host_i32(&to_padded_i32(&grids.wids))?,
                cids: DevBuf::from_host_i32(&to_i32(&grids.cids))?,
                lp2p1: DevBuf::from_host_f32(&concat(&grids.lp2p1))?,
                lp2p2: DevBuf::from_host_f32(&concat(&grids.lp2p2))?,
                lp2p1w: DevBuf::from_host_f32(&concat(&grids.lp2p1w))?,
                lp2p2w: DevBuf::from_host_f32(&concat(&grids.lp2p2w))?,
                c2lp1: DevBuf::from_host_f32(&concat(&grids.c2lp1))?,
                c2lp2: DevBuf::from_host_f32(&concat(&grids.c2lp2))?,
            })
        }

        /// Complex half-width of the R2C spectrum (`ntheta/2 + 1`).
        fn ntheta_c(&self) -> usize {
            self.ntheta / 2 + 1
        }

        /// Padded real row width of the in-place R2C buffer (`2*(ntheta/2+1)`).
        fn ntheta_pad(&self) -> usize {
            2 * self.ntheta_c()
        }

        /// Bytes of the in-place R2C work buffer for `cz` slices: the padded real
        /// `[cz, nrho, ntheta_pad]` overlays the half-complex `[cz, nrho,
        /// ntheta_c]`, i.e. `cz*nrho*ntheta_c` complex — roughly half the old
        /// `[cz, nrho, ntheta]` full-complex buffer.
        fn flc_bytes(&self, cz: usize) -> usize {
            cz * self.nrho * self.ntheta_c() * 2 * std::mem::size_of::<f32>()
        }

        /// Per-chunk runtime (port of `recon/lprec.rs::process_row`): `g` is the
        /// **filtered** sinogram `[cz, nproj, n]`, consumed in place as the
        /// spline-coefficient buffer; `flc` a `[cz, nrho, ntheta]` complex scratch
        /// (clobbered); `f` the `[cz, n, n]` output, which the caller must zero
        /// first (the scatter accumulates over the NSPAN spans).
        fn run(
            &self,
            g: *mut c_void,
            flc: *mut c_void,
            f: *mut c_void,
            cz: usize,
            nproj: usize,
            n: usize,
        ) -> Result<()> {
            use crate::recon::lprec::LP_NSPAN;
            let null = std::ptr::null_mut::<c_void>();
            let (nrho, ntheta) = (self.nrho, self.ntheta);
            let (ntheta_c, ntheta_pad) = (self.ntheta_c(), self.ntheta_pad());
            let off = |buf: &DevBuf, elems: usize| -> *const c_void {
                unsafe { (buf.ptr as *const f32).add(elems) as *const c_void }
            };
            ck(
                unsafe {
                    ffi::tomoxide_lprec_prefilter_rows(g, cz as i32, nproj as i32, n as i32, null)
                },
                "lprec prefilter rows",
            )?;
            ck(
                unsafe {
                    ffi::tomoxide_lprec_prefilter_cols(g, cz as i32, nproj as i32, n as i32, null)
                },
                "lprec prefilter cols",
            )?;
            let flc_bytes = self.flc_bytes(cz);
            for k in 0..LP_NSPAN {
                ck(
                    unsafe { ffi::tomoxide_cuda_memset(flc, 0, flc_bytes) },
                    "memset flc",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lprec_gather(
                            g,
                            flc,
                            self.lpids.ptr,
                            off(&self.lp2p2, k * self.n_lp),
                            off(&self.lp2p1, k * self.n_lp),
                            self.n_lp as i32,
                            cz as i32,
                            nproj as i32,
                            n as i32,
                            nrho as i32,
                            ntheta_pad as i32,
                            null,
                        )
                    },
                    "lprec gather main",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lprec_gather(
                            g,
                            flc,
                            self.wids.ptr,
                            off(&self.lp2p2w, k * self.n_w),
                            off(&self.lp2p1w, k * self.n_w),
                            self.n_w as i32,
                            cz as i32,
                            nproj as i32,
                            n as i32,
                            nrho as i32,
                            ntheta_pad as i32,
                            null,
                        )
                    },
                    "lprec gather wrap",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_2d_r2c(flc, nrho, ntheta, cz) },
                    "lprec fft fwd (r2c)",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lprec_cmul(
                            flc,
                            self.kfull.ptr,
                            cz as i32,
                            nrho as i32,
                            ntheta_c as i32,
                            null,
                        )
                    },
                    "lprec cmul",
                )?;
                ck(
                    unsafe { ffi::tomoxide_fft_2d_c2r(flc, nrho, ntheta, cz) },
                    "lprec fft inv (c2r)",
                )?;
                ck(
                    unsafe {
                        ffi::tomoxide_lprec_scatter(
                            flc,
                            f,
                            self.cids.ptr,
                            off(&self.c2lp1, k * self.n_c),
                            off(&self.c2lp2, k * self.n_c),
                            self.n_c as i32,
                            cz as i32,
                            n as i32,
                            nrho as i32,
                            ntheta as i32,
                            ntheta_pad as i32,
                            null,
                        )
                    },
                    "lprec scatter",
                )?;
            }
            Ok(())
        }
    }

    impl LpRecReconstruct for CudaBackend {
        /// Device-resident log-polar reconstruction — the GPU port of
        /// `crate::recon::lprec`'s per-slice runtime. The geometry grids are
        /// precomputed on the host by `build_grids` (the same precompute the CPU
        /// path uses) and uploaded once; the cubic-B-spline prefilter, the
        /// polar↔log-polar gather/scatter, and the per-span FFT convolution all
        /// run on the device (`cuda/lprec.cu`), replacing the host interpolation
        /// that dominated the composed `Fft`-only path. The slice batch is
        /// z-tiled to bound the large `[tile, nrho, ntheta]` complex work buffer.
        fn reconstruct(
            &self,
            filtered: &Tomo<f32>,
            geom: &Geometry,
            n: usize,
        ) -> Result<Volume<f32>> {
            if geom.beam != Beam::Parallel {
                return Err(Error::InvalidParam(
                    "cuda lprec supports parallel beam only".into(),
                ));
            }
            let s = filtered.as_layout(Layout::Sinogram); // [nz, nproj, ncols]
            let (nz, nproj, ncols) = s.array.dim();
            if ncols != n {
                return Err(Error::InvalidParam(format!(
                    "cuda lprec needs a square grid = detector width {ncols}; got {n}"
                )));
            }
            if nproj < 2 {
                return Err(Error::InvalidParam("cuda lprec needs >= 2 angles".into()));
            }
            let angles = &geom.angles.0;
            if angles.len() != nproj {
                return Err(Error::ShapeMismatch {
                    expected: format!("{nproj} angles"),
                    found: angles.len().to_string(),
                });
            }
            // Equally-spaced [0, π) guard (matches the CPU lprec precondition the
            // log-polar span tiling assumes).
            let dth = (angles[1] - angles[0]).abs();
            let nproj_test = (std::f32::consts::PI / dth).round() as usize;
            if nproj_test != nproj {
                return Err(Error::InvalidParam(
                    "cuda lprec requires equally spaced angles spanning [0, π)".into(),
                ));
            }
            let raw = s
                .array
                .as_slice()
                .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

            let devices = selected_devices();
            ck(
                unsafe { ffi::tomoxide_cuda_set_device(*devices.first().unwrap_or(&0)) },
                "set_device",
            )?;

            // Precompute + upload the geometry grids once (shared device runtime).
            let lp = LpRecDev::new(n, nproj)?;
            let (nrho, ntheta) = (lp.nrho, lp.ntheta);

            // z-tile so the [tile, nrho, ntheta] complex work buffer (plus the g
            // and f tiles) fits. A third of free memory leaves headroom for the
            // cuFFT plan and the resident grid uploads.
            let fsz = std::mem::size_of::<f32>();
            let per_slice = nrho * ntheta * 2 * fsz + nproj * ncols * fsz + n * n * fsz;
            let tile = (device_free_bytes() / 3 / per_slice.max(1)).clamp(1, nz);

            let mut vol = vec![0.0f32; nz * n * n];
            let mut z = 0;
            while z < nz {
                let cz = tile.min(nz - z);
                let g = DevBuf::from_host_f32(&raw[z * nproj * ncols..(z + cz) * nproj * ncols])?;
                let flc = DevBuf::zeroed(lp.flc_bytes(cz))?;
                let f = DevBuf::zeroed(cz * n * n * fsz)?; // scatter accumulates → zeroed
                lp.run(g.ptr, flc.ptr, f.ptr, cz, nproj, n)?;
                ck(unsafe { ffi::tomoxide_cuda_sync() }, "lprec sync")?;
                f.to_host_f32(&mut vol[z * n * n..(z + cz) * n * n])?;
                z += cz;
            }

            Ok(Volume::new(
                Array3::from_shape_vec((nz, n, n), vol)
                    .map_err(|e| Error::InvalidParam(format!("cuda lprec shape: {e}")))?,
            ))
        }
    }

    #[cfg(all(test, feature = "cuda"))]
    mod stripe_gpu_tests {
        use super::*;
        use crate::data::{Layout, Tomo};
        use crate::params::StripeMethod;
        use ndarray::Array3;

        fn pearson(a: &[f32], b: &[f32]) -> f64 {
            let n = a.len() as f64;
            let (mut sa, mut sb) = (0.0, 0.0);
            for i in 0..a.len() {
                sa += a[i] as f64;
                sb += b[i] as f64;
            }
            let (ma, mb) = (sa / n, sb / n);
            let (mut cov, mut va, mut vb) = (0.0, 0.0, 0.0);
            for i in 0..a.len() {
                let (da, db) = (a[i] as f64 - ma, b[i] as f64 - mb);
                cov += da * db;
                va += da * da;
                vb += db * db;
            }
            cov / (va.sqrt() * vb.sqrt())
        }

        // Synthetic sinogram [nz, nproj, ncol]: a smooth angle/column structure
        // plus a per-column constant offset (the classic stripe → ring), so the
        // Titarenko correction has something to remove.
        fn synthetic(nz: usize, nproj: usize, ncol: usize) -> Vec<f32> {
            let mut v = vec![0.0f32; nz * nproj * ncol];
            for z in 0..nz {
                for p in 0..nproj {
                    for c in 0..ncol {
                        let base = (p as f32 * 0.05).sin() + (c as f32 * 0.03).cos();
                        let stripe = (((c * 7 + 13) % 17) as f32 / 17.0 - 0.5) * 0.4;
                        v[(z * nproj + p) * ncol + c] = base + 1.0 + stripe + z as f32 * 0.01;
                    }
                }
            }
            v
        }

        // The GPU Titarenko kernel solves the same (HᵀH + αI)q = f systems as the
        // CPU golden via CG; parallel f64 reductions differ in summation order, so
        // it is held to correlation parity, not bit-exactness.
        #[test]
        fn stripe_ti_matches_cpu_golden() {
            let (nz, nproj, ncol) = (4usize, 180usize, 192usize);
            let host = synthetic(nz, nproj, ncol);

            // CPU golden.
            let mut cpu = Tomo::new(
                Array3::from_shape_vec((nz, nproj, ncol), host.clone()).unwrap(),
                Layout::Sinogram,
            );
            crate::prep::remove_stripe(
                &mut cpu,
                StripeMethod::Ti {
                    nblock: 0,
                    beta: 1.5,
                },
            )
            .unwrap();
            let cpu_v: Vec<f32> = cpu.array.iter().copied().collect();

            // GPU: run the kernel on a device copy of the same sinogram.
            let _b = CudaBackend::new().expect("cuda backend");
            ck(unsafe { ffi::tomoxide_cuda_set_device(0) }, "set_device").unwrap();
            let dev = DevBuf::from_host_f32(&host).unwrap();
            let scratch = DevBuf::zeroed(nz * 7 * ncol * std::mem::size_of::<f64>()).unwrap();
            let null = std::ptr::null_mut::<c_void>();
            ck(
                unsafe {
                    ffi::tomoxide_stripe_ti(dev.ptr, nz, nproj, ncol, 1.5, scratch.ptr, null)
                },
                "stripe_ti",
            )
            .unwrap();
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync").unwrap();
            let mut gpu_v = vec![0.0f32; nz * nproj * ncol];
            dev.to_host_f32(&mut gpu_v).unwrap();

            let r = pearson(&cpu_v, &gpu_v);
            let max_abs: f32 = cpu_v
                .iter()
                .zip(&gpu_v)
                .map(|(a, b)| (a - b).abs())
                .fold(0.0, f32::max);
            let nan = gpu_v.iter().filter(|v| !v.is_finite()).count();
            println!("TI GPU vs CPU: pearson={r:.8} max_abs_diff={max_abs:.3e} nan={nan}");
            assert_eq!(nan, 0, "GPU TI produced non-finite values");
            // Same CG systems, same combine: matches the CPU golden to the f32
            // reduction-order floor (parallel dot products reassociate the sums).
            assert!(r > 0.99999, "TI GPU vs CPU correlation too low: {r}");
        }

        // Multi-GPU angle-split SIRT must equal the single-device SIRT for a
        // tilted (laminography) geometry. Sharding across `[0, 0]` runs two angle
        // chunks — both on device 0 — through the all-reduce path, so the logic
        // is exercised without needing two physical GPUs; the result must match
        // the single-pass `sirt_device` to the atomic-add + sum-reassociation
        // floor (the partials sum in a different order than one device's pass).
        #[test]
        fn sirt_multigpu_lamino_matches_single_device() {
            let _b = CudaBackend::new().expect("cuda backend");
            let (n, nproj, nz) = (32usize, 24usize, 8usize);
            let phi = std::f32::consts::FRAC_PI_2 + 20.0 * std::f32::consts::PI / 180.0;
            let geom = Geometry {
                angles: crate::geometry::Angles::uniform(nproj, 0.0, std::f32::consts::PI),
                center: crate::geometry::Center::Scalar(n as f32 / 2.0),
                beam: Beam::Laminography { phi },
                detector: crate::geometry::Detector {
                    width: n,
                    height: nz,
                    pixel_size: 1.0,
                },
            };
            // Deterministic pseudo-random non-negative sinogram (xorshift).
            let mut s = 0x1234_5678u64;
            let sino_vec: Vec<f32> = (0..nz * nproj * n)
                .map(|_| {
                    s ^= s << 13;
                    s ^= s >> 7;
                    s ^= s << 17;
                    (s >> 40) as f32 / (1u64 << 24) as f32
                })
                .collect();
            let sino = Tomo::new(
                Array3::from_shape_vec((nz, nproj, n), sino_vec).unwrap(),
                Layout::Sinogram,
            );

            let single = sirt_device(&sino, &geom, n, 6, None).unwrap();
            let multi = sirt_multigpu_lamino(&sino, &geom, n, 6, None, &[0, 0]).unwrap();

            let a = single.array.as_slice().unwrap();
            let b = multi.array.as_slice().unwrap();
            let r = pearson(a, b);
            let max_abs: f32 = a
                .iter()
                .zip(b)
                .map(|(x, y)| (x - y).abs())
                .fold(0.0, f32::max);
            let peak = a.iter().fold(0.0f32, |m, &v| m.max(v.abs()));
            println!(
                "multi-GPU vs single SIRT lamino: pearson={r:.8} max_abs_diff={max_abs:.3e} peak={peak:.3e}"
            );
            assert!(
                r > 0.999_99,
                "multi-GPU SIRT diverged from single: pearson={r}"
            );
            assert!(
                max_abs <= 1e-3 * peak.max(1e-6),
                "multi-GPU SIRT max abs diff too large: {max_abs:.3e} (peak {peak:.3e})"
            );
        }

        // Validate the db5 DWT/IDWT kernels against the pywt oracle (the same
        // [5,4] case as the CPU `wavelet::dwt2_idwt2_match_pywt` test).
        #[test]
        fn fw_wavelet_matches_pywt() {
            let _b = CudaBackend::new().expect("cuda backend");
            ck(unsafe { ffi::tomoxide_cuda_set_device(0) }, "set_device").unwrap();
            let null = std::ptr::null_mut::<c_void>();
            let f8 = std::mem::size_of::<f64>();
            let (nz, r, c) = (1usize, 5usize, 4usize);
            let (oc, or) = ((c + 9) / 2, (r + 9) / 2); // 6, 7
            let a: Vec<f64> = (0..r * c).map(|i| (i + 1) as f64).collect();
            let dev_a = DevBuf::from_host_f64(&a).unwrap();

            // Forward dwt2: rows then cols.
            let cols_a = DevBuf::zeroed(nz * r * oc * f8).unwrap();
            let cols_d = DevBuf::zeroed(nz * r * oc * f8).unwrap();
            ck(
                unsafe {
                    ffi::tomoxide_fw_dwt_rows(dev_a.ptr, cols_a.ptr, cols_d.ptr, nz, r, c, null)
                },
                "dwt_rows",
            )
            .unwrap();
            let (ca, ch, cv, cd) = (
                DevBuf::zeroed(nz * or * oc * f8).unwrap(),
                DevBuf::zeroed(nz * or * oc * f8).unwrap(),
                DevBuf::zeroed(nz * or * oc * f8).unwrap(),
                DevBuf::zeroed(nz * or * oc * f8).unwrap(),
            );
            ck(
                unsafe { ffi::tomoxide_fw_dwt_cols(cols_a.ptr, ca.ptr, ch.ptr, nz, r, oc, null) },
                "dwt_cols a",
            )
            .unwrap();
            ck(
                unsafe { ffi::tomoxide_fw_dwt_cols(cols_d.ptr, cv.ptr, cd.ptr, nz, r, oc, null) },
                "dwt_cols d",
            )
            .unwrap();
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync").unwrap();

            let ca_h = ca.to_host_f64(nz * or * oc).unwrap();
            let ch_h = ch.to_host_f64(nz * or * oc).unwrap();
            let cv_h = cv.to_host_f64(nz * or * oc).unwrap();
            let cd_h = cd.to_host_f64(nz * or * oc).unwrap();
            assert!(
                (ca_h[0] - 32.046313561434275).abs() < 1e-9,
                "ca {}",
                ca_h[0]
            );
            assert!((ch_h[0] - 0.426202580246038).abs() < 1e-9, "ch {}", ch_h[0]);
            assert!(
                (cv_h[0] - 0.1888883078383144).abs() < 1e-9,
                "cv {}",
                cv_h[0]
            );
            assert!(cd_h[0].abs() < 1e-9, "cd {}", cd_h[0]);

            // Inverse idwt2: cols then rows. rR = 2*or+2-10 = 6, rC = 2*oc+2-10 = 4.
            let rr = 2 * or + 2 - 10;
            let colsa2 = DevBuf::zeroed(nz * rr * oc * f8).unwrap();
            let colsd2 = DevBuf::zeroed(nz * rr * oc * f8).unwrap();
            ck(
                unsafe { ffi::tomoxide_fw_idwt_cols(ca.ptr, ch.ptr, colsa2.ptr, nz, or, oc, null) },
                "idwt_cols a",
            )
            .unwrap();
            ck(
                unsafe { ffi::tomoxide_fw_idwt_cols(cv.ptr, cd.ptr, colsd2.ptr, nz, or, oc, null) },
                "idwt_cols d",
            )
            .unwrap();
            let rc2 = 2 * oc + 2 - 10;
            let out = DevBuf::zeroed(nz * rr * rc2 * f8).unwrap();
            ck(
                unsafe {
                    ffi::tomoxide_fw_idwt_rows(colsa2.ptr, colsd2.ptr, out.ptr, nz, rr, oc, null)
                },
                "idwt_rows",
            )
            .unwrap();
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync").unwrap();
            let out_h = out.to_host_f64(nz * rr * rc2).unwrap();
            assert_eq!((rr, rc2), (6, 4));
            for row in 0..5 {
                for col in 0..4 {
                    let want = a[row * 4 + col];
                    let got = out_h[row * rc2 + col];
                    assert!(
                        (got - want).abs() < 1e-8,
                        "recon[{row},{col}] {got} vs {want}"
                    );
                }
            }
            assert!(
                (out_h[5 * rc2 + 3] - 20.0).abs() < 1e-8,
                "recon[5,3] {}",
                out_h[5 * rc2 + 3]
            );
        }

        // The Vo per-column bitonic sort must reproduce Rust's stable ascending
        // `sort_by` exactly — including tie-breaking by original row — so the
        // unsort scatter lands every value back on the right projection. Uses a
        // column with deliberate ties (clamped values) to exercise the composite
        // (value, row) key.
        #[test]
        fn vo_colsort_matches_stable_sort() {
            let _b = CudaBackend::new().expect("cuda backend");
            ck(unsafe { ffi::tomoxide_cuda_set_device(0) }, "set_device").unwrap();
            let null = std::ptr::null_mut::<c_void>();
            let (nz, nrow, nc) = (2usize, 90usize, 7usize);
            let mut host = vec![0.0f32; nz * nrow * nc];
            for z in 0..nz {
                for p in 0..nrow {
                    for c in 0..nc {
                        // Quantised to create many ties; pow2 padding (128) exercised.
                        let raw = (p as f32 * 0.3 + c as f32 * 1.7 + z as f32).sin();
                        host[(z * nrow + p) * nc + c] = (raw * 4.0).round() / 4.0;
                    }
                }
            }
            let dev = DevBuf::from_host_f32(&host).unwrap();
            let f4 = std::mem::size_of::<f32>();
            let i4 = std::mem::size_of::<i32>();
            let sorted = DevBuf::zeroed(nz * nrow * nc * f4).unwrap();
            let perm = DevBuf::zeroed(nz * nrow * nc * i4).unwrap();
            ck(
                unsafe {
                    ffi::tomoxide_vo_colsort(dev.ptr, sorted.ptr, perm.ptr, nz, nrow, nc, 1, null)
                },
                "vo_colsort",
            )
            .unwrap();
            ck(unsafe { ffi::tomoxide_cuda_sync() }, "sync").unwrap();
            let mut sorted_h = vec![0.0f32; nz * nrow * nc];
            sorted.to_host_f32(&mut sorted_h).unwrap();
            let mut perm_h = vec![0i32; nz * nrow * nc];
            {
                let bytes = std::mem::size_of_val(perm_h.as_slice());
                ck(
                    unsafe {
                        ffi::tomoxide_cuda_memcpy_d2h(
                            perm_h.as_mut_ptr() as *mut c_void,
                            perm.ptr,
                            bytes,
                        )
                    },
                    "perm d2h",
                )
                .unwrap();
            }
            for z in 0..nz {
                for c in 0..nc {
                    let mut idx: Vec<usize> = (0..nrow).collect();
                    idx.sort_by(|&a, &b| {
                        host[(z * nrow + a) * nc + c].total_cmp(&host[(z * nrow + b) * nc + c])
                    });
                    for rank in 0..nrow {
                        let o = (z * nrow + rank) * nc + c;
                        assert_eq!(
                            perm_h[o] as usize, idx[rank],
                            "perm mismatch z={z} c={c} rank={rank}"
                        );
                        let want = host[(z * nrow + idx[rank]) * nc + c];
                        assert_eq!(sorted_h[o], want, "value mismatch z={z} c={c} rank={rank}");
                    }
                }
            }
        }
    }
}

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

    #[test]
    #[cfg(not(feature = "cuda"))]
    fn unavailable_without_feature() {
        assert!(matches!(
            CudaBackend::new(),
            Err(Error::BackendUnavailable(_))
        ));
    }

    #[test]
    fn advertises_cuda_device() {
        let b = CudaBackend;
        assert_eq!(b.name(), "cuda");
        assert_eq!(b.device(), DeviceKind::Cuda);
        assert!(b.supports(Dtype::F16));
    }
}