ferrotorch-core 0.6.1

Core tensor and autograd engine for ferrotorch — PyTorch 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
//! GPU backend dispatch layer.
//!
//! ferrotorch-core defines the [`GpuBackend`] trait and [`GpuBufferHandle`].
//! ferrotorch-gpu (or any other GPU crate) implements and registers a backend.
//! This avoids circular dependencies: core doesn't depend on gpu.
//!
//! ## REQ status (per `.design/ferrotorch-core/gpu_dispatch.md`)
//!
//! | REQ | Status | Evidence |
//! |---|---|---|
//! | REQ-1 | SHIPPED | impl `enum CompareOp` + `suffix`; non-test consumer `GpuBackend::compare` dispatch. |
//! | REQ-2 | SHIPPED | impl `GpuRngState`; non-test consumer `GpuBackend::save_rng_state`/`restore_rng_state`. |
//! | REQ-3 | SHIPPED | impl `GpuBufferHandle`; non-test consumer `StorageBuffer::Gpu` variant + every CUDA op. |
//! | REQ-4 | SHIPPED | impl `trait GpuBackend`; non-test consumer `ferrotorch-gpu::CudaBackendImpl`. |
//! | REQ-5 | SHIPPED | impl elementwise method slots `add_f32`, `sub_f32`, `mul_f32`, `neg_f32`, `relu_f32`; non-test consumer `Tensor::accumulate_grad` GPU path + `grad_fns::arithmetic` CUDA branches. |
//! | REQ-6 | SHIPPED | impl broadcast-* trait slots; non-test consumer `grad_fns::arithmetic::add_inner` broadcast branch. |
//! | REQ-7 | SHIPPED | impl `scale_*` trait slots; non-test consumer `grad_fns::arithmetic::scale_tensor`. |
//! | REQ-8 | SHIPPED | impl `strided_copy_*`, `strided_scatter_*` trait slots; non-test consumer `stride_tricks` materialise, `Tensor::to(Cpu)` non-contiguous, `Tensor::materialize_format` GPU fast path. |
//! | REQ-9 | SHIPPED | impl reduction trait slots; non-test consumer `grad_fns::arithmetic::reduce_grad_to_shape`. |
//! | REQ-10 | SHIPPED | impl linalg trait slots (matmul, `matmul_f32_nt`/`matmul_f64_nt` fused-transpose `A @ B^T` (#1679), gemm, syevd, getrf, geqrf, potrf, gesdd, inverse); non-test consumer `ops::linalg::matmul`, `linalg::eigh`, `grad_fns::linalg::linear_fused` GPU path (the `_nt` slots). |
//! | REQ-11 | SHIPPED | impl conv2d/conv3d/pooling trait slots; non-test consumer `ferrotorch-nn::Conv2d`. |
//! | REQ-12 | SHIPPED | impl recurrent trait slots; non-test consumer `ferrotorch-nn::LSTM`/`GRU`/`RNN`. |
//! | REQ-13 | SHIPPED | impl FFT trait slots; non-test consumer `ferrotorch-core::fft`. |
//! | REQ-14 | SHIPPED | impl dropout/RNG/`save_rng_state`/`restore_rng_state` trait slots; non-test consumer `nn::Dropout`, `creation::randn`. |
//! | REQ-15 | SHIPPED | impl `masked_fill_dt`, `where_cond`, `masked_select`, `masked_scatter`, `argmax`, `argmin`, `index_select_intidx`, `gather_intidx`; non-test consumer `Tensor::masked_fill`/`masked_select`, `grad_fns::indexing`. |
//! | REQ-16 | SHIPPED | impl cuSPARSE dispatch slots; non-test consumer `SparseTensor::from_dense` CUDA path. |
//! | REQ-17 | SHIPPED | impl int_* trait slots; non-test consumer `int_tensor.rs` op forwarders. |
//! | REQ-18 | SHIPPED | impl `compare`, `bool_*`, cast slots; non-test consumer `bool_tensor.rs` op forwarders. |
//! | REQ-19 | SHIPPED | impl `synchronize`, `stream_count`, `strided_cat`; non-test consumer `CudaBackendImpl::synchronize` override. |
//! | REQ-20 | SHIPPED | impl `register_gpu_backend`, `gpu_backend`, `has_gpu_backend`; non-test consumer `ferrotorch-gpu::backend_impl::register` + every CUDA op in core. |

use std::any::Any;
use std::sync::OnceLock;

use crate::dtype::DType;
use crate::error::{FerrotorchError, FerrotorchResult};

// ---------------------------------------------------------------------------
// CompareOp — the comparison operator for `GpuBackend::compare` (Phase 3b)
// ---------------------------------------------------------------------------

/// The six elementwise comparison operators (`torch.{eq,ne,lt,le,gt,ge}`),
/// passed to [`GpuBackend::compare`] which produces a `DType::Bool`-tagged
/// (u8 0/1) output. PyTorch parity: the comparison's result dtype is `bool`
/// regardless of the input value dtype.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
    /// `a == b`.
    Eq,
    /// `a != b`.
    Ne,
    /// `a < b`.
    Lt,
    /// `a <= b`.
    Le,
    /// `a > b`.
    Gt,
    /// `a >= b`.
    Ge,
}

impl CompareOp {
    /// Stable kernel-name suffix (`"eq"`, `"ne"`, …) used to select the PTX
    /// entry point in the CUDA backend.
    #[must_use]
    pub fn suffix(self) -> &'static str {
        match self {
            CompareOp::Eq => "eq",
            CompareOp::Ne => "ne",
            CompareOp::Lt => "lt",
            CompareOp::Le => "le",
            CompareOp::Gt => "gt",
            CompareOp::Ge => "ge",
        }
    }
}

// ---------------------------------------------------------------------------
// GpuRngState — serializable GPU RNG state for checkpoint save/restore
// ---------------------------------------------------------------------------

/// Serializable snapshot of a GPU device's RNG state.
///
/// This is defined in `ferrotorch-core` (not `ferrotorch-gpu`) so that the
/// checkpoint module can save/restore GPU RNG state without depending on the
/// GPU crate directly. The GPU backend implementation is responsible for
/// converting this to/from its internal representation (e.g., `PhiloxState`).
///
/// Fields are crate-private; construct via [`GpuRngState::new`] and read via
/// the [`Self::counter`], [`Self::seed`], [`Self::offset`], [`Self::device`]
/// accessors. Encapsulation lets the layout evolve (e.g. add a Philox-key
/// pair) without a workspace-wide breaking change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GpuRngState {
    /// RNG counter value.
    pub(crate) counter: u64,
    /// RNG seed.
    pub(crate) seed: u64,
    /// Offset within the current random number group.
    pub(crate) offset: u64,
    /// Device ordinal this state belongs to.
    pub(crate) device: usize,
}

impl GpuRngState {
    /// Construct a new RNG state snapshot.
    #[inline]
    #[must_use]
    pub fn new(counter: u64, seed: u64, offset: u64, device: usize) -> Self {
        Self {
            counter,
            seed,
            offset,
            device,
        }
    }

    /// RNG counter value at the time of the snapshot.
    #[inline]
    #[must_use]
    pub fn counter(&self) -> u64 {
        self.counter
    }

    /// RNG seed used by this generator.
    #[inline]
    #[must_use]
    pub fn seed(&self) -> u64 {
        self.seed
    }

    /// Offset within the current random number group.
    #[inline]
    #[must_use]
    pub fn offset(&self) -> u64 {
        self.offset
    }

    /// Device ordinal this RNG state belongs to.
    #[inline]
    #[must_use]
    pub fn device(&self) -> usize {
        self.device
    }
}

/// Opaque handle to GPU memory.
///
/// ferrotorch-core doesn't know what's inside -- the GPU backend provides
/// the concrete type (e.g., `CudaBuffer<f32>`). We store it as
/// `Box<dyn Any + Send + Sync>` for type erasure.
///
/// # The `dtype` tag (PyTorch parity)
///
/// PyTorch's `StorageImpl` holds raw bytes with no dtype; the `ScalarType`
/// tag lives above storage on `TensorImpl::data_type_` as runtime metadata.
/// `Half` and `BFloat16` are both 2 bytes and are told apart *only* by that
/// tag, never by byte width. This handle mirrors that: [`Self::dtype`] is the
/// authoritative element-type tag. Backends dispatch on the tag, not on the
/// erased concrete type or the byte width — so f16 vs. bf16 (both 2 bytes)
/// and (in later phases) i32 vs. f32 (both 4 bytes) never collide.
pub struct GpuBufferHandle {
    pub(crate) inner: Box<dyn Any + Send + Sync>,
    pub(crate) device_ordinal: usize,
    pub(crate) len: usize,
    pub(crate) dtype: DType,
}

impl GpuBufferHandle {
    pub fn new(
        inner: Box<dyn Any + Send + Sync>,
        device_ordinal: usize,
        len: usize,
        dtype: DType,
    ) -> Self {
        Self {
            inner,
            device_ordinal,
            len,
            dtype,
        }
    }

    #[inline]
    pub fn device_ordinal(&self) -> usize {
        self.device_ordinal
    }

    /// The authoritative element-type tag for the bytes this handle owns.
    ///
    /// This is the PyTorch `ScalarType` analog: it, not the byte width or the
    /// erased concrete buffer type, decides how the data is interpreted.
    #[inline]
    pub fn dtype(&self) -> DType {
        self.dtype
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
        self.inner.downcast_ref()
    }

    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.inner.downcast_mut()
    }

    /// Consume the handle and extract the inner value as a concrete type.
    pub fn into_inner<T: 'static>(self) -> Result<T, Box<dyn Any + Send + Sync>> {
        self.inner.downcast::<T>().map(|b| *b)
    }
}

impl std::fmt::Debug for GpuBufferHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GpuBufferHandle")
            .field("inner", &"<dyn Any + Send + Sync>")
            .field("device", &self.device_ordinal)
            .field("len", &self.len)
            .field("dtype", &self.dtype)
            .finish()
    }
}

/// True when the f32 GPU `cdist` kernel covers the norm exponent `p`.
///
/// The on-device f32 kernel ([`GpuBackend::cdist_f32`]) handles `p == 1`,
/// `p == 2`, `p == inf`, and general finite `p > 0` (via an on-device `pow`).
/// The only excluded case is the `p == 0` count-of-nonzeros norm, which is
/// delegated to the CPU path. Mirrors the upstream dispatch in
/// `aten/src/ATen/native/cuda/DistanceKernel.cu:230-240` (which special-cases
/// `0`, `1`, `2`, `inf` and falls through to the general kernel otherwise).
#[must_use]
// reason: `p` is a discrete norm selector, not a measured value; PyTorch
// itself special-cases the norm with exact `p == 0.0` / `1.0` / `2.0`
// comparisons at `aten/src/ATen/native/cuda/DistanceKernel.cu:232-238`, so
// the exact compare is the correct upstream-mirroring behaviour here.
#[allow(
    clippy::float_cmp,
    reason = "discrete norm selector, mirrors upstream exact p compares"
)]
pub(crate) fn cdist_supported_f32(p: f64) -> bool {
    p != 0.0
}

/// True when the f64 GPU `cdist` kernel covers the norm exponent `p`.
///
/// The on-device f64 kernel ([`GpuBackend::cdist_f64`]) covers `p == 1`,
/// `p == 2`, and `p == inf`; the `p == 0` count-norm and general finite `p`
/// (which would need an accurate f64 `pow` the base PTX ISA does not provide)
/// fall back to the CPU path.
#[must_use]
// reason: see `cdist_supported_f32` — `p` is a discrete norm selector and the
// exact compare mirrors the upstream norm dispatch.
#[allow(
    clippy::float_cmp,
    reason = "discrete norm selector, mirrors upstream exact p compares"
)]
pub(crate) fn cdist_supported_f64(p: f64) -> bool {
    p == 1.0 || p == 2.0 || p.is_infinite()
}

/// Trait that GPU backends implement to handle tensor operations.
///
/// ferrotorch-core calls these methods; ferrotorch-gpu provides the implementation.
pub trait GpuBackend: Send + Sync {
    /// Downcast to `&dyn Any` for backend-specific access (e.g., getting the
    /// underlying `GpuDevice` for CUDA graph capture).
    fn as_any(&self) -> &dyn std::any::Any;
    /// Copy CPU bytes to GPU, tagging the resulting handle with `dtype`.
    ///
    /// `dtype` is the PyTorch `ScalarType` analog: it is the authoritative
    /// element-type tag for `data` and decides the concrete on-device buffer
    /// type. The element size is derived internally via `dtype.size_of()`.
    fn cpu_to_gpu(
        &self,
        data: &[u8],
        dtype: DType,
        device: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn gpu_to_cpu(&self, handle: &GpuBufferHandle) -> FerrotorchResult<Vec<u8>>;

    /// Get the raw CUDA device pointer from a buffer handle.
    ///
    /// Returns null if the handle type is not recognized or the backend
    /// doesn't support raw pointer access.
    fn raw_device_ptr(&self, _handle: &GpuBufferHandle) -> *const std::ffi::c_void {
        std::ptr::null()
    }

    /// Get a mutable raw CUDA device pointer from a buffer handle.
    fn raw_device_ptr_mut(&self, _handle: &mut GpuBufferHandle) -> *mut std::ffi::c_void {
        std::ptr::null_mut()
    }

    /// Get the element size (in bytes) of the data stored in a buffer handle.
    ///
    /// Derived from the handle's authoritative [`GpuBufferHandle::dtype`] tag
    /// (PyTorch parity: byte width is a function of the `ScalarType`, never the
    /// other way around). Returns 0 if unknown.
    fn buffer_elem_size(&self, handle: &GpuBufferHandle) -> usize {
        handle.dtype().size_of()
    }

    /// Copy CPU data to GPU via pinned (page-locked) host memory.
    ///
    /// ~2x faster than [`cpu_to_gpu`] for large buffers due to DMA transfers.
    /// Falls back to regular `cpu_to_gpu` by default. `dtype` is the
    /// authoritative element-type tag for `data` (see [`Self::cpu_to_gpu`]).
    fn cpu_to_gpu_pinned(
        &self,
        data: &[u8],
        dtype: DType,
        device: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        self.cpu_to_gpu(data, dtype, device)
    }
    fn clone_buffer(&self, handle: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle>;
    /// Allocate a zero-initialised device buffer of `len` elements, tagged
    /// with `dtype`. Element size is derived via `dtype.size_of()`.
    fn alloc_zeros(
        &self,
        len: usize,
        dtype: DType,
        device: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;

    // Elementwise f32
    fn add_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn sub_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn mul_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    /// Fused f32 scaled add: `out[i] = a[i] + alpha * b[i]` in a single
    /// device kernel launch (FMA), for SAME-shape inputs. Replaces the
    /// two-launch `scale_f32(b, alpha)` + `add_f32(a, b_scaled)` staging.
    /// For `alpha == -1.0` the FMA result is exactly `a - b`; this is the
    /// fast path consumed by `sub` / `sub_scaled` / `rsub` (all delegate to
    /// `add_scaled`). Default returns `NotImplementedOnCuda` so non-CUDA
    /// backends compile unchanged and the caller falls back to the
    /// scale-then-add path. (#1675)
    fn add_scaled_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _alpha: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "add_scaled_f32",
        })
    }
    fn neg_f32(&self, a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle>;
    fn relu_f32(&self, a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle>;

    // Linalg f32
    fn matmul_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        m: usize,
        k: usize,
        n: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;

    /// Mixed-precision matmul: cast f32 inputs to f16, multiply, accumulate
    /// back to f32. Used by autocast when the category is `ReducedPrecision`.
    ///
    /// Default implementation falls back to `matmul_f32` (no precision
    /// reduction) until a real f16 GEMM kernel is available.
    ///
    /// # NaN / Inf propagation
    ///
    /// f16 has a much smaller dynamic range than f32 (max ~65504). Values
    /// outside that range will overflow to inf or underflow to zero when cast.
    /// Callers relying on autocast should ensure their model weights stay
    /// within f16-representable bounds (which is normal for trained networks).
    fn matmul_f16_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        m: usize,
        k: usize,
        n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        // Fallback: no f16 kernel available, use full-precision f32.
        self.matmul_f32(a, b, m, k, n)
    }

    // Reduction f32
    fn sum_f32(&self, a: &GpuBufferHandle, len: usize) -> FerrotorchResult<GpuBufferHandle>;

    /// f32 product reduction. Returns a 1-element buffer holding the
    /// product of all elements. (#524)
    fn prod_f32(&self, _a: &GpuBufferHandle, _len: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "GPU reduce_prod not implemented for this backend".into(),
        })
    }

    /// f32 parallel min reduction. Returns a 1-element buffer holding the
    /// minimum element of `a`. Default impl returns the
    /// "not yet implemented" error so existing backends compile unchanged
    /// — concrete backends override. (#627)
    fn min_f32(&self, _a: &GpuBufferHandle, _len: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "GPU reduce_min not implemented for this backend".into(),
        })
    }

    /// f32 parallel max reduction. Counterpart of [`Self::min_f32`]. (#627)
    fn max_f32(&self, _a: &GpuBufferHandle, _len: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "GPU reduce_max not implemented for this backend".into(),
        })
    }

    /// f32 fused masked-min reduction (#627). Single-pass kernel that
    /// folds `(data, mask_f) -> min` directly, where `mask_f[i]` is 1.0
    /// for valid entries and 0.0 for masked. Avoids the
    /// `mul + add + reduce` chain that the unfused path requires.
    fn masked_min_f32(
        &self,
        _data: &GpuBufferHandle,
        _mask_f: &GpuBufferHandle,
        _len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "GPU masked_reduce_min not implemented for this backend".into(),
        })
    }

    /// f32 fused masked-max counterpart of [`Self::masked_min_f32`]. (#627)
    fn masked_max_f32(
        &self,
        _data: &GpuBufferHandle,
        _mask_f: &GpuBufferHandle,
        _len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "GPU masked_reduce_max not implemented for this backend".into(),
        })
    }

    // Elementwise f64 (default impls return "not yet implemented" errors)
    fn add_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }
    fn sub_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }
    fn mul_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }
    /// Fused f64 scaled add: `out[i] = a[i] + alpha * b[i]` in a single
    /// launch. f64 counterpart of [`Self::add_scaled_f32`]. (#1675)
    fn add_scaled_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _alpha: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "add_scaled_f64",
        })
    }
    fn neg_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }
    fn relu_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }

    // Linalg f64
    fn matmul_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }

    /// Fused-transpose matmul `C = A @ B^T` (f32).
    ///
    /// `a: [m, k]`, `b: [n, k]` (row-major; the transpose of `B` is folded
    /// into the cuBLAS `transb` flag with no extra kernel launch or buffer
    /// alloc). Returns a `[m, n]` f32 buffer. This is the `nn.Linear` forward
    /// shape — weight is `[out, in] = [n, k]`, input is `[m, k]`, so
    /// `input @ weight^T` lowers directly to this op (#1679). Default returns
    /// `NotImplementedOnCuda` so non-CUDA backends compile unchanged and the
    /// caller falls back to the `transpose_2d + matmul` path.
    fn matmul_f32_nt(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "matmul_f32_nt",
        })
    }

    /// Fused-transpose matmul `C = A @ B^T` (f64). f64 counterpart of
    /// [`Self::matmul_f32_nt`]. (#1679)
    fn matmul_f64_nt(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "matmul_f64_nt",
        })
    }

    // -- Vector matmul kernels (#816 / #817 / #818) ---------------------------
    //
    // These cover the rank combinations that PyTorch's `torch.matmul` (and
    // `torch.dot` / `torch.mv`) accepts on CUDA but ferrotorch previously
    // routed through CPU-only specialised paths, surfacing as
    // `GpuTensorNotAccessible` for CUDA inputs.
    //
    // - `dot_*` : 1D x 1D inner product (cuBLAS `{S,D}dot`)
    // - `mv_*`  : 2D x 1D matrix-vector product (cuBLAS `{S,D}gemv`, OP_T)
    // - `vm_*`  : 1D x 2D vector-matrix product (cuBLAS `{S,D}gemv`, OP_N)
    //
    // CUDA is the primary GPU backend; backends that don't implement these
    // (or aren't CUDA at all) inherit the default `Err` impl. CUDA itself
    // overrides them with real cuBLAS kernels.

    /// 1D x 1D dot product on GPU. Returns a 1-element buffer.
    /// `n` is the shared length of both inputs (each buffer holds `n` elements).
    fn dot_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "dot_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// 1D x 1D dot product on GPU (f64 dtype).
    fn dot_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "dot_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// 2D x 1D matrix-vector product `y[m] = A[m,k] @ x[k]`. Returns a
    /// buffer of length `m`.
    fn mv_f32(
        &self,
        _a: &GpuBufferHandle,
        _x: &GpuBufferHandle,
        _m: usize,
        _k: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mv_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// 2D x 1D matrix-vector product on GPU (f64 dtype).
    fn mv_f64(
        &self,
        _a: &GpuBufferHandle,
        _x: &GpuBufferHandle,
        _m: usize,
        _k: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mv_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// 1D x 2D vector-matrix product `y[n] = x[k] @ B[k,n]`. Returns a
    /// buffer of length `n`. Implemented via `gemv` with the transpose flag
    /// — does NOT materialise a transposed copy of `B`.
    fn vm_f32(
        &self,
        _x: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "vm_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// 1D x 2D vector-matrix product on GPU (f64 dtype).
    fn vm_f64(
        &self,
        _x: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "vm_f64 GPU op not implemented for this backend".into(),
        })
    }

    // -- Broadcast / 4D matmul kernel (#819) ----------------------------------
    //
    // PyTorch's `torch.matmul` supports arbitrary leading-dim broadcast on
    // CUDA — `(B, M, K) @ (K, N)`, `(M, K) @ (B, K, N)`, full 4D bmm,
    // `(2, 1, M, K) @ (2, 4, K, N)`, etc. Pre-fix these shapes fell through
    // to `linalg::matmul` (CPU path) and surfaced as `GpuTensorNotAccessible`
    // for CUDA inputs. Post-fix, `matmul_differentiable` routes them to
    // `broadcast_bmm_f{32,64}` which lower to `cublas{S,D}gemmStridedBatched`
    // — stride=0 on broadcasted axes, no `expand` materialisation.
    //
    // Inputs:
    // - `a`/`b`: GPU buffers, contiguous, in row-major batch layout. The
    //   caller has already ensured non-broadcasted dims match and that
    //   `a.len() == a_batch_count * m * k`, `b.len() == b_batch_count * k * n`.
    // - `out_lead`: the broadcasted leading-dim shape (excluding `m, n`).
    //   `batch = product(out_lead)`. Output shape is `out_lead + [m, n]`.
    // - `a_lead`/`b_lead`: per-leading-axis sizes for A and B. Where the
    //   axis size is 1 vs `out_lead[i]`, that axis is treated as broadcast.
    //   Lengths may be shorter than `out_lead` (implicit batch=1 prefix).
    // - `m`, `k`, `n`: per-batch matmul dims.

    /// Broadcast / batched matmul on GPU (f32 dtype).
    fn broadcast_bmm_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_lead: &[usize],
        _b_lead: &[usize],
        _out_lead: &[usize],
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_bmm_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Broadcast / batched matmul on GPU (f64 dtype).
    fn broadcast_bmm_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_lead: &[usize],
        _b_lead: &[usize],
        _out_lead: &[usize],
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_bmm_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// Broadcast / batched matmul on GPU (bf16 dtype, bf16 in/out, f32 accum).
    ///
    /// Same calling convention as [`Self::broadcast_bmm_f32`]: handles the 4D
    /// bmm, 3D × 2D, 2D × 3D, and arbitrary leading-dim broadcasts that
    /// `matmul_differentiable` routes here for `Tensor<bf16>` on CUDA.
    /// Pre-fix (GH forecast-bio/ferrotorch#25 / local #1543) bf16 fell through
    /// to the CPU `broadcast_matmul` round-trip; downstream of that path the
    /// ViT 3D × 2D `(1, 200, 4096) @ (4096, 768)` matmul reported a 50× worse
    /// `max|Δ|` than CPU bf16, because the GPU→CPU→GPU code-path is what the
    /// reporter actually measured (the CPU bf16 path uses an f64 accumulator;
    /// the device round-trip silently changes which kernel runs). Routing
    /// bf16 directly through `gpu_matmul_bf16_bf16_strided_batched`
    /// (`CUDA_R_16BF` in/out, `CUBLAS_COMPUTE_32F` accumulator) restores the
    /// standard ~1.5e-3 cuBLAS bf16+f32-accum floor that the upstream issue
    /// expects.
    fn broadcast_bmm_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_lead: &[usize],
        _b_lead: &[usize],
        _out_lead: &[usize],
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_bmm_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// Broadcast / batched matmul on GPU (IEEE f16 dtype, f16 in/out, f32 accum).
    ///
    /// Symmetric trait surface to [`Self::broadcast_bmm_bf16`] for `Tensor<f16>`
    /// on CUDA. The default impl returns `InvalidArgument`; the CUDA backend
    /// has no `gpu_matmul_f16_f16_strided_batched` kernel today, so f16 GPU
    /// 3D × 2D matmul continues to fall back to the CPU `broadcast_matmul`
    /// round-trip until that kernel lands (see `.design/ferrotorch-gpu/blas.md`
    /// REQ-11 status row). This trait surface is preserved so the
    /// `matmul_differentiable` dispatcher in
    /// `ferrotorch-core/src/grad_fns/linalg.rs` can branch uniformly on
    /// `is_bf16` / `is_f16` and an opt-in backend can override later without
    /// further dispatcher churn.
    fn broadcast_bmm_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_lead: &[usize],
        _b_lead: &[usize],
        _out_lead: &[usize],
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_bmm_f16 GPU op not implemented for this backend".into(),
        })
    }

    // Reduction f64
    fn sum_f64(&self, _a: &GpuBufferHandle, _numel: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU ops not yet implemented".into(),
        })
    }

    /// f64 product reduction. (#524)
    fn prod_f64(&self, _a: &GpuBufferHandle, _len: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU reduce_prod not implemented for this backend".into(),
        })
    }

    /// f32 backward of the global `prod` reduction (#785).
    ///
    /// Returns `grad_input[i] = grad_output * (prod_{j != i} input[j])`,
    /// which matches PyTorch's exact zero-handling semantics:
    /// no zeros → `grad_input = grad_output * total / input`; one zero
    /// at index z → only `grad_input[z]` is nonzero (the product of the
    /// remaining elements); two or more zeros → all zero.
    ///
    /// `grad_output` is a scalar (`numel == 1`).
    fn prod_backward_f32(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "prod_backward_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 backward of the global `prod` reduction (#785). Companion of
    /// [`Self::prod_backward_f32`].
    fn prod_backward_f64(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "prod_backward_f64 GPU op not yet implemented".into(),
        })
    }

    /// f64 parallel min reduction. (#627)
    fn min_f64(&self, _a: &GpuBufferHandle, _len: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU reduce_min not implemented for this backend".into(),
        })
    }

    /// f64 parallel max reduction. (#627)
    fn max_f64(&self, _a: &GpuBufferHandle, _len: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU reduce_max not implemented for this backend".into(),
        })
    }

    /// f64 fused masked-min reduction (#627).
    fn masked_min_f64(
        &self,
        _data: &GpuBufferHandle,
        _mask_f: &GpuBufferHandle,
        _len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU masked_reduce_min not implemented for this backend".into(),
        })
    }

    /// f64 fused masked-max reduction (#627).
    fn masked_max_f64(
        &self,
        _data: &GpuBufferHandle,
        _mask_f: &GpuBufferHandle,
        _len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "f64 GPU masked_reduce_max not implemented for this backend".into(),
        })
    }

    // Broadcast binary f32
    fn broadcast_add_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        a_shape: &[usize],
        b_shape: &[usize],
        out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn broadcast_add_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_add_f64 GPU op not yet implemented".into(),
        })
    }
    fn broadcast_sub_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        a_shape: &[usize],
        b_shape: &[usize],
        out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn broadcast_sub_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_sub_f64 GPU op not yet implemented".into(),
        })
    }
    fn broadcast_mul_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        a_shape: &[usize],
        b_shape: &[usize],
        out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn broadcast_mul_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_mul_f64 GPU op not yet implemented".into(),
        })
    }
    fn broadcast_div_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        a_shape: &[usize],
        b_shape: &[usize],
        out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn broadcast_div_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "broadcast_div_f64 GPU op not yet implemented".into(),
        })
    }

    // Softmax f32 (row-wise over last dim)
    fn softmax_f32(
        &self,
        a: &GpuBufferHandle,
        rows: usize,
        cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn softmax_f64(
        &self,
        _a: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "softmax_f64 GPU op not yet implemented".into(),
        })
    }

    // Dropout f32 (inverted dropout)
    fn dropout_f32(
        &self,
        a: &GpuBufferHandle,
        threshold: u32,
        scale: f32,
        seed: u32,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn dropout_f64(
        &self,
        _a: &GpuBufferHandle,
        _threshold: u32,
        _scale: f64,
        _seed: u32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "dropout_f64 GPU op not yet implemented".into(),
        })
    }

    /// Dropout using the Philox CBRNG for deterministic, reproducible mask generation.
    ///
    /// Instead of a simple u32 seed, this takes a `GpuRngState` that specifies the
    /// exact Philox counter and key to use. This enables gradient checkpointing to
    /// reproduce identical dropout masks by restoring the RNG state.
    ///
    /// The method also advances the global GPU RNG state by `ceil(n/4)` counters.
    ///
    /// Returns the dropped-out buffer and the Philox state that was used (for
    /// backward mask regeneration).
    fn dropout_philox_f32(
        &self,
        a: &GpuBufferHandle,
        threshold: u32,
        scale: f32,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuRngState)> {
        // Default: fall back to the non-Philox version with a dummy seed.
        // The returned state has device=0 as a placeholder.
        let result = self.dropout_f32(a, threshold, scale, 0)?;
        Ok((
            result,
            GpuRngState {
                counter: 0,
                seed: 0,
                offset: 0,
                device: 0,
            },
        ))
    }
    fn dropout_philox_f64(
        &self,
        _a: &GpuBufferHandle,
        _threshold: u32,
        _scale: f64,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuRngState)> {
        Err(FerrotorchError::InvalidArgument {
            message: "dropout_philox_f64 GPU op not yet implemented".into(),
        })
    }

    // 2D transpose f32
    fn transpose_2d_f32(
        &self,
        a: &GpuBufferHandle,
        m: usize,
        n: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn transpose_2d_f64(
        &self,
        _a: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "transpose_2d_f64 GPU op not yet implemented".into(),
        })
    }

    // 4D permute (0,2,1,3) f32 — swap dims 1 and 2
    fn permute_0213_f32(
        &self,
        a: &GpuBufferHandle,
        d0: usize,
        d1: usize,
        d2: usize,
        d3: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn permute_0213_f64(
        &self,
        _a: &GpuBufferHandle,
        _d0: usize,
        _d1: usize,
        _d2: usize,
        _d3: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "permute_0213_f64 GPU op not yet implemented".into(),
        })
    }

    // Batched matmul f32: C[i] = A[i] @ B[i] for i in 0..batch
    fn bmm_f32(
        &self,
        a: &GpuBufferHandle,
        b: &GpuBufferHandle,
        batch: usize,
        m: usize,
        k: usize,
        n: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn bmm_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _batch: usize,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "bmm_f64 GPU op not yet implemented".into(),
        })
    }

    /// Batched matmul with f16 Tensor Core acceleration.
    /// Takes f32 handles, converts to f16 internally, accumulates in f32.
    fn bmm_f16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _batch: usize,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "bmm_f16_f32 GPU op not yet implemented".into(),
        })
    }

    // -- bf16 × f32-accumulator mixed-precision kernels (#518) ---------------
    //
    // PyTorch parity (rust-gpu-discipline §3): under `torch.autocast(device_type
    // ="cuda", dtype=torch.bfloat16)`, `torch.matmul`, `torch.bmm`, and
    // `torch.softmax` on CUDA tensors use bf16 inputs with f32 accumulation via
    // cuBLAS GemmEx (CUDA_R_16BF / CUBLAS_COMPUTE_32F).
    //
    // Default impls return `Err` so existing backends compile unchanged. The
    // CUDA backend overrides these three methods with real cuBLAS / PTX kernels.
    // There is NO silent CPU fallback (§3 hard requirement).

    /// Matrix multiply: bf16 inputs (f32-buffers converted to bf16 on-device)
    /// → f32 output via cuBLAS GemmEx (CUDA_R_16BF / CUBLAS_COMPUTE_32F).
    ///
    /// Signature mirrors [`Self::matmul_f16_f32`]; dtype is bf16 instead of f16.
    /// bf16 has a wider exponent range than f16 (same 8-bit exponent as f32),
    /// making it more robust to large weight values typical in transformers.
    fn matmul_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "matmul_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Batched matrix multiply: bf16 inputs → f32 output.
    ///
    /// `a` is `[batch, m, k]`, `b` is `[batch, k, n]`, result is `[batch, m, n]`.
    /// All tensors are passed as f32 handles; inputs are converted to bf16
    /// on-device before the cuBLAS GemmStridedBatchedEx call.
    fn bmm_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _batch: usize,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "bmm_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Matrix multiply: bf16 inputs → bf16 output via cuBLAS GemmEx
    /// (`CUDA_R_16BF` operands, `CUBLAS_COMPUTE_32F` accumulator).
    ///
    /// Both input handles must carry a `CudaSlice<u16>` (each u16 is a bf16
    /// bit pattern — top 16 bits of an f32). The result is also a
    /// `CudaSlice<u16>` of shape `[m, n]`. This is the foundational op for
    /// bf16-resident inference (weights + activations stay bf16 in VRAM,
    /// halving VRAM vs. f32) and is what unblocks `Tensor<bf16> @
    /// Tensor<bf16>` on CUDA without an upstream-side cast to f32.
    fn matmul_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "matmul_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// Batched matrix multiply: bf16 inputs → bf16 output via cuBLAS
    /// GemmStridedBatchedEx.
    ///
    /// Each batch element is a row-major matmul of shapes `A:[M,K]`,
    /// `B:[K,N]`, producing `C:[M,N]`. Per-batch strides default to
    /// `m*k`, `k*n`, `m*n` (contiguous batches). Both input handles
    /// must carry `CudaSlice<u16>` (bf16 bit patterns); the output is
    /// a `CudaSlice<u16>` of total size `batch * m * n`.
    fn bmm_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _batch: usize,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "bmm_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// Row-wise softmax: bf16 input (stored as `u16` bit-pattern buffer) →
    /// f32 output via PTX kernel with f32 accumulator.
    ///
    /// `rows` = product of all dims except the last; `cols` = last dim size.
    /// The input handle must contain a `CudaSlice<u16>` (bf16 bit patterns);
    /// the output is a `CudaBuffer<f32>` of the same shape.
    ///
    /// All phases (max-find, exp-sum, normalize) accumulate in f32 for
    /// numerical stability — matches PyTorch's bf16 softmax contract.
    fn softmax_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "softmax_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    // -- bf16 elementwise (#963) ---------------------------------------------

    /// Elementwise add: bf16 inputs (u16 bit-pattern buffers) -> f32 output.
    ///
    /// PyTorch parity: `torch.add(a.bfloat16(), b.bfloat16())` under autocast
    /// uses f32 accumulators on CUDA. Both handles must contain
    /// `CudaSlice<u16>` (bf16 bit patterns) of the same length `n`.
    fn add_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "add_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Elementwise subtract: bf16 inputs -> f32 output.
    fn sub_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sub_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Elementwise multiply: bf16 inputs -> f32 output.
    fn mul_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mul_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Elementwise divide: bf16 inputs -> f32 output.
    fn div_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "div_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    // -- bf16 reductions (#963) ----------------------------------------------

    /// Sum along an axis: bf16 input [outer, axis_size, inner] (u16) -> f32
    /// [outer, inner]. Accumulates in f32.
    fn sum_axis_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _axis_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sum_axis_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Mean along an axis: bf16 input [outer, axis_size, inner] (u16) -> f32
    /// [outer, inner]. Accumulates in f32, divides by axis_size in f32.
    fn mean_axis_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _axis_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mean_axis_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    // -- bf16 activations (#963) ---------------------------------------------

    /// ReLU activation: bf16 input (u16) -> f32 output.
    /// `out[i] = max(0.0, bf16_to_f32(a[i]))`.
    fn relu_bf16_f32(&self, _a: &GpuBufferHandle, _n: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "relu_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Sigmoid activation: bf16 input (u16) -> f32 output.
    /// `out[i] = 1 / (1 + exp(-bf16_to_f32(a[i])))`.
    fn sigmoid_bf16_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sigmoid_bf16_f32 GPU op not implemented for this backend".into(),
        })
    }

    // GELU activation f32 (sigmoid approximation)
    fn gelu_f32(&self, a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle>;
    fn gelu_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_f64 GPU op not yet implemented".into(),
        })
    }
    // GELU activation f32 (tanh approximation: PyTorch approximate="tanh")
    fn gelu_tanh_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_tanh_f32 GPU op not yet implemented".into(),
        })
    }
    fn gelu_tanh_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_tanh_f64 GPU op not yet implemented".into(),
        })
    }
    // GELU activation f32 (exact erf: PyTorch approximate="none")
    fn gelu_erf_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_erf_f32 GPU op not yet implemented".into(),
        })
    }
    fn gelu_erf_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_erf_f64 GPU op not yet implemented".into(),
        })
    }

    // LayerNorm f32 (row-wise, with affine)
    fn layernorm_f32(
        &self,
        input: &GpuBufferHandle,
        weight: &GpuBufferHandle,
        bias: &GpuBufferHandle,
        rows: usize,
        cols: usize,
        eps: f32,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn layernorm_f64(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _bias: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "layernorm_f64 GPU op not yet implemented".into(),
        })
    }

    // GroupNorm f32 (#1356 / #1357).
    //
    // Channel-group normalization over a `[batch, channels, hw]`-laid-out f32
    // buffer (PyTorch `[N, C, H, W]` flattened to `hw = H*W`). `channels` is
    // split into `groups` groups; per-`(batch, group)` mean/var are taken over
    // `(channels/groups) * hw` elements, then the per-channel affine
    // `weight[c] * normed + bias[c]` is applied. `weight`/`bias` have length
    // `channels`. Mirrors `aten/src/ATen/native/cuda/group_norm_kernel.cu`
    // (`GroupNormKernelImpl`). The default impl returns `InvalidArgument` so
    // existing backends compile unchanged; the CUDA backend overrides it with
    // the `gpu_group_norm_f32` PTX kernel. Non-test production consumer:
    // `ferrotorch-nn::GroupNorm::forward` GPU fast path.
    fn group_norm_f32(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _bias: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _groups: usize,
        _hw: usize,
        _eps: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "group_norm_f32 GPU op not implemented for this backend".into(),
        })
    }

    // BatchNorm f32 (#1449).
    //
    // Per-channel normalization over a `[batch, channels, hw]`-laid-out f32
    // buffer (PyTorch `[N, C, *spatial]` flattened to `hw = ∏ spatial`). In
    // **training** mode (`training == true`) the per-channel mean / variance
    // are computed over `(batch, hw)` (biased, like PyTorch) and the computed
    // batch stats are returned as the second / third tuple element so the
    // caller can update its running statistics; in **eval** mode the
    // caller-supplied `mean` / `var` (the running stats) are used and returned
    // unchanged. `weight`/`bias` have length `channels` (ones / zeros when the
    // layer is non-affine). Mirrors `aten/src/ATen/native/Normalization.cpp`
    // `batch_norm_cpu_transform_input_template`. The default impl returns
    // `InvalidArgument` so existing backends compile unchanged; the CUDA
    // backend overrides it with the `gpu_batch_norm_f32` PTX kernel. Non-test
    // production consumer: `ferrotorch-nn::BatchNorm{1,2,3}d::forward` GPU fast
    // path.
    //
    // Returns `(output, mean_out, var_out)` where `output` has the input shape
    // and `mean_out` / `var_out` have length `channels`.
    #[allow(clippy::too_many_arguments)]
    fn batch_norm_f32(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _bias: &GpuBufferHandle,
        _mean: &GpuBufferHandle,
        _var: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _hw: usize,
        _eps: f32,
        _training: bool,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "batch_norm_f32 GPU op not implemented for this backend".into(),
        })
    }

    // BatchNorm backward f32 (#1449).
    //
    // On-device gradient for the BatchNorm family over a
    // `[batch, channels, hw]`-laid-out f32 buffer. Mirrors
    // `aten/src/ATen/native/cuda/Normalization.cuh:388 batch_norm_backward_kernel`:
    // one reduction per channel computes `grad_output_sum = Σ go` and
    // `dot_p = Σ (x - mean) * go`, then
    //   grad_input  = train ? (go - (x-mean)*proj_scale - grad_mean) * grad_scale
    //                       : go * grad_scale
    //   grad_weight = dot_p * invstd ; grad_bias = grad_output_sum
    // where `proj_scale = dot_p/N * invstd²`, `grad_mean = grad_output_sum/N`,
    // `grad_scale = invstd * weight[c]`. In **training** mode `mean`/`invstd` are
    // recomputed from `input` (biased var, +eps); in **eval** mode they come from
    // `running_mean`/`running_var`. `weight` has length `channels` (all-ones for
    // the non-affine case so `grad_scale = invstd`). The default impl returns
    // `InvalidArgument`; the CUDA backend overrides it with
    // `gpu_batch_norm_backward_f32`. Non-test production consumer:
    // `ferrotorch-nn::BatchNorm{1,2,3}dBackward::backward` / `InstanceNormBackward`
    // GPU fast path.
    //
    // Returns `(grad_input, grad_weight, grad_bias)`: `grad_input` has the input
    // shape, `grad_weight` / `grad_bias` have length `channels`.
    #[allow(clippy::too_many_arguments)]
    fn batch_norm_backward_f32(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _running_mean: &GpuBufferHandle,
        _running_var: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _hw: usize,
        _eps: f32,
        _training: bool,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "batch_norm_backward_f32 GPU op not implemented for this backend".into(),
        })
    }

    // LocalResponseNorm forward f32 (#1449).
    //
    // Per-element cross-channel normalization over a
    // `[batch, channels, spatial]`-laid-out f32 buffer. Mirrors
    // `torch/nn/functional.py:3032-3046 local_response_norm` (square → windowed
    // channel sum → `* alpha + k` → `pow(beta)` → divide):
    //   denom[i] = (Σ_window x² / size) * alpha + k
    //   out[i]   = x[i] / denom[i]^beta
    // Returns `(output, denom)`; `denom` (input shape) is the saved buffer the
    // backward consumes. The default impl returns `InvalidArgument`; the CUDA
    // backend overrides it with `gpu_local_response_norm_f32`. Non-test
    // production consumer: `ferrotorch-nn::LocalResponseNorm::forward` GPU path.
    #[allow(clippy::too_many_arguments)]
    fn local_response_norm_f32(
        &self,
        _input: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _spatial: usize,
        _size: usize,
        _alpha: f32,
        _beta: f32,
        _k: f32,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "local_response_norm_f32 GPU op not implemented for this backend".into(),
        })
    }

    // LocalResponseNorm backward f32 (#1449).
    //
    // On-device VJP for `local_response_norm`, consuming the `denom` buffer
    // saved by `local_response_norm_f32`. One thread per element:
    //   term1 = denom[i]^(-beta) * go[i]
    //   cross = Σ_{c in window(i)} go[c] * x[c] * denom[c]^(-beta-1)
    //   grad_input[i] = term1 - 2*beta*alpha/size * x[i] * cross
    // The default impl returns `InvalidArgument`; the CUDA backend overrides it
    // with `gpu_local_response_norm_backward_f32`. Non-test production consumer:
    // `ferrotorch-nn::LocalResponseNormBackward::backward` GPU path.
    #[allow(clippy::too_many_arguments)]
    fn local_response_norm_backward_f32(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
        _denom: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _spatial: usize,
        _size: usize,
        _alpha: f32,
        _beta: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "local_response_norm_backward_f32 GPU op not implemented for this backend"
                .into(),
        })
    }

    // Softmax2d f32 (#1451).
    //
    // Channel-axis softmax over a `[n, c, hw]`-laid-out f32 buffer
    // (PyTorch `[N, C, H, W]` flattened to `hw = H*W`). For each `(n, p)`
    // spatial position, softmax is taken over the `c` channel values that are
    // strided `hw` apart in the flat buffer:
    // `out[n,c,p] = exp(x[n,c,p] - max_c') / Σ_c' exp(x[n,c',p] - max_c')`.
    // Mirrors `torch.nn.Softmax2d` (`torch/nn/modules/activation.py`). The
    // default impl returns `InvalidArgument` so existing backends compile
    // unchanged; the CUDA backend overrides it with the `gpu_softmax2d_f32`
    // PTX kernel. Non-test production consumer:
    // `ferrotorch-nn::Softmax2d::forward` GPU fast path.
    fn softmax2d_f32(
        &self,
        _input: &GpuBufferHandle,
        _n: usize,
        _c: usize,
        _hw: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "softmax2d_f32 GPU op not implemented for this backend".into(),
        })
    }

    // RMSNorm f32 (row-wise, weight only — no bias, no mean centering)
    fn rmsnorm_f32(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "rmsnorm_f32 GPU op not yet implemented".into(),
        })
    }
    fn rmsnorm_f64(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "rmsnorm_f64 GPU op not yet implemented".into(),
        })
    }

    // RMSNorm backward f32: returns (grad_input, grad_weight)
    fn rmsnorm_backward_f32(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f32,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "rmsnorm_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn rmsnorm_backward_f64(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f64,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "rmsnorm_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // Slice write: write [N, D] into row `pos` of [N, max_len, D] (in-place)
    fn slice_write_f32(
        &self,
        src: &GpuBufferHandle,
        dst: &mut GpuBufferHandle,
        n_batch: usize,
        d: usize,
        max_len: usize,
        pos: usize,
    ) -> FerrotorchResult<()>;
    fn slice_write_f64(
        &self,
        _src: &GpuBufferHandle,
        _dst: &mut GpuBufferHandle,
        _n_batch: usize,
        _d: usize,
        _max_len: usize,
        _pos: usize,
    ) -> FerrotorchResult<()> {
        Err(FerrotorchError::InvalidArgument {
            message: "slice_write_f64 GPU op not yet implemented".into(),
        })
    }

    // Slice read: read first `len` rows from [N, max_len, D] → [N, len, D]
    fn slice_read_f32(
        &self,
        src: &GpuBufferHandle,
        n_batch: usize,
        d: usize,
        len: usize,
        max_len: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn slice_read_f64(
        &self,
        _src: &GpuBufferHandle,
        _n_batch: usize,
        _d: usize,
        _len: usize,
        _max_len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "slice_read_f64 GPU op not yet implemented".into(),
        })
    }

    // Embedding lookup: gather row `idx` from weight [V, D] → [D]
    fn embed_lookup_f32(
        &self,
        idx: &GpuBufferHandle,
        weight: &GpuBufferHandle,
        d: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn embed_lookup_f64(
        &self,
        _idx: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _d: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "embed_lookup_f64 GPU op not yet implemented".into(),
        })
    }

    // Batch embedding lookup: gather N rows from weight [V, D] → [N, D]
    // `indices` contains N f32 values encoding integer row indices.
    fn embed_lookup_batch_f32(
        &self,
        indices: &GpuBufferHandle,
        weight: &GpuBufferHandle,
        n: usize,
        d: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn embed_lookup_batch_f64(
        &self,
        _indices: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _n: usize,
        _d: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "embed_lookup_batch_f64 GPU op not yet implemented".into(),
        })
    }

    // Scatter-add rows: grad_weight[indices[i], :] += grad_output[i, :] for embedding backward
    // `indices` contains N f32 values, grad_output is [N, D], output is [num_embeddings, D]
    fn scatter_add_rows_f32(
        &self,
        grad_output: &GpuBufferHandle,
        indices: &GpuBufferHandle,
        num_embeddings: usize,
        d: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn scatter_add_rows_f64(
        &self,
        _grad_output: &GpuBufferHandle,
        _indices: &GpuBufferHandle,
        _num_embeddings: usize,
        _d: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scatter_add_rows_f64 GPU op not yet implemented".into(),
        })
    }

    // Scalar multiply: out[i] = a[i] * scalar
    fn scale_f32(&self, a: &GpuBufferHandle, scalar: f32) -> FerrotorchResult<GpuBufferHandle>;
    fn scale_f64(&self, _a: &GpuBufferHandle, _scalar: f64) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scale_f64 GPU op not yet implemented".into(),
        })
    }

    // Backward activation kernels
    // relu_backward: out[i] = (input[i] > 0) ? grad[i] : 0
    fn relu_backward_f32(
        &self,
        grad: &GpuBufferHandle,
        input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn relu_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "relu_backward_f64 GPU op not yet implemented".into(),
        })
    }
    // abs_backward: out[i] = grad[i] * sign(input[i])  (sign(0) = 0)
    fn abs_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "abs_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn abs_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "abs_backward_f64 GPU op not yet implemented".into(),
        })
    }
    // fill: allocate an n-element device buffer filled with `scalar`.
    // Used by sum/mean backward so the grad is built entirely on-device.
    fn fill_f32(
        &self,
        _n: usize,
        _scalar: f32,
        _ordinal: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fill_f32 GPU op not yet implemented".into(),
        })
    }
    fn fill_f64(
        &self,
        _n: usize,
        _scalar: f64,
        _ordinal: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fill_f64 GPU op not yet implemented".into(),
        })
    }
    // gelu_backward (sigmoid approx): out[i] = grad[i] * (sig + 1.702*x*sig*(1-sig))
    fn gelu_backward_f32(
        &self,
        grad: &GpuBufferHandle,
        input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn gelu_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_backward_f64 GPU op not yet implemented".into(),
        })
    }
    // gelu_backward (tanh approx)
    fn gelu_backward_tanh_f32(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_backward_tanh_f32 GPU op not yet implemented".into(),
        })
    }
    fn gelu_backward_tanh_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_backward_tanh_f64 GPU op not yet implemented".into(),
        })
    }
    // gelu_backward (exact erf): out[i] = grad[i] * (Φ(x) + x·φ(x))
    // where Φ = normal CDF, φ = normal PDF
    fn gelu_backward_erf_f32(
        &self,
        grad: &GpuBufferHandle,
        input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn gelu_backward_erf_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_backward_erf_f64 GPU op not yet implemented".into(),
        })
    }

    // Cumulative scan operations along a dimension.
    // Parameters: (input, outer, dim_size, inner) factorize the tensor shape.
    fn cumsum_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "cumsum_f32 GPU op not yet implemented".into(),
        })
    }
    fn cumsum_f64(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "cumsum_f64 GPU op not yet implemented".into(),
        })
    }
    fn cumprod_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "cumprod_f32 GPU op not yet implemented".into(),
        })
    }
    fn cumprod_f64(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "cumprod_f64 GPU op not yet implemented".into(),
        })
    }
    // Returns (values, indices_as_f32)
    fn cummax_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "cummax_f32 GPU op not yet implemented".into(),
        })
    }
    fn cummax_f64(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "cummax_f64 GPU op not yet implemented".into(),
        })
    }
    // Returns (values, indices_as_f32)
    fn cummin_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "cummin_f32 GPU op not yet implemented".into(),
        })
    }
    fn cummin_f64(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "cummin_f64 GPU op not yet implemented".into(),
        })
    }
    fn logcumsumexp_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "logcumsumexp_f32 GPU op not yet implemented".into(),
        })
    }
    fn logcumsumexp_f64(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "logcumsumexp_f64 GPU op not yet implemented".into(),
        })
    }

    // Roll (cyclic shift) along a single axis. The `(outer, dim_size, inner)`
    // factorization mirrors the cumulative ops above; `shift_norm` is the
    // already-normalized non-negative shift with `0 <= shift_norm < dim_size`.
    // Forward and backward both call this method (the backward simply
    // negates the original shift before normalizing).
    fn roll_f32(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
        _shift_norm: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "roll_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 sibling of [`GpuBackend::roll_f32`] — same `(outer, dim_size,
    /// inner)` factorization and `shift_norm` contract; only the element width
    /// differs (`roll` is pure index movement, so the f64 path is exact).
    fn roll_f64(
        &self,
        _a: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
        _shift_norm: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "roll_f64 GPU op not yet implemented".into(),
        })
    }

    // -- Triangular masks: triu / tril (#1545 / sub #1535) -------------------
    //
    // `[batch.., rows, cols]` C-contiguous masks (`batch` = product of the
    // leading dims, `1` for plain 2-D). The mask is applied to EVERY trailing
    // `[rows, cols]` matrix, batching over the leading dims. Element
    // `(row, col)` is preserved when the predicate holds and zeroed otherwise:
    //   - triu keeps `col - row >= k`
    //   - tril keeps `col - row <= k`
    // matching `aten/src/ATen/native/cuda/TriangularOps.cu:100` (predicate) and
    // `:120` (`N_padded = multiply_integers(sizes[..last]) * last_dim_padded`,
    // i.e. batches over leading dims) and the ferrotorch CPU `triu`/`tril`.
    // `k` is the signed diagonal offset. The result stays GPU-resident (no host
    // round-trip). Default bodies return `NotImplementedOnCuda` so non-CUDA
    // backends compile unchanged; the CUDA backend overrides all four. Non-test
    // consumer: the `input.is_cuda()` branch of `triu`/`tril` in
    // `ferrotorch-core/src/ops/tensor_ops.rs`.

    /// Upper-triangular mask over an f32 `[batch.., rows, cols]` buffer.
    fn triu_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _rows: usize,
        _cols: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "triu_f32" })
    }

    /// Lower-triangular mask over an f32 `[batch.., rows, cols]` buffer.
    fn tril_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _rows: usize,
        _cols: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "tril_f32" })
    }

    /// Upper-triangular mask over an f64 `[batch.., rows, cols]` buffer.
    fn triu_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _rows: usize,
        _cols: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "triu_f64" })
    }

    /// Lower-triangular mask over an f64 `[batch.., rows, cols]` buffer.
    fn tril_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _rows: usize,
        _cols: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "tril_f64" })
    }

    // -- Diagonal: diag_embed / diag_extract (#1545 / sub #1535) -------------
    //
    // `torch.diag` is `diag_embed` (1-D -> 2-D scatter onto the k-th diagonal)
    // for a 1-D input and `diagonal_copy` (2-D -> 1-D gather of the k-th
    // diagonal) for a 2-D input, mirroring
    // `aten/src/ATen/native/TensorShape.cpp:4610`. Both are pure gather/scatter
    // (no arithmetic), so the GPU result is bit-for-bit identical to the
    // ferrotorch CPU `diag`. `k` is the signed diagonal offset. The result
    // stays GPU-resident (no host round-trip). Default bodies return
    // `NotImplementedOnCuda` so non-CUDA backends compile unchanged; the CUDA
    // backend overrides all four. Non-test consumer: the `input.is_cuda()`
    // branch of `diag`/`diagflat` in `ferrotorch-core/src/ops/tensor_ops.rs`.

    /// `diag` of a 1-D f32 buffer: scatter `n` elements onto the `k`-th
    /// diagonal of a `[size, size]` matrix (`size = n + |k|`). Returns the
    /// resident `size*size`-element output.
    fn diag_embed_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "diag_embed_f32",
        })
    }

    /// `diag` of a 1-D f64 buffer. See [`Self::diag_embed_f32`].
    fn diag_embed_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "diag_embed_f64",
        })
    }

    /// `diag` of a 2-D f32 `[rows, cols]` buffer: gather the `k`-th diagonal
    /// into a 1-D vector of `min(rows-start_r, cols-start_c)` elements.
    fn diag_extract_f32(
        &self,
        _a: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "diag_extract_f32",
        })
    }

    /// `diag` of a 2-D f64 `[rows, cols]` buffer. See [`Self::diag_extract_f32`].
    fn diag_extract_f64(
        &self,
        _a: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _k: i64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "diag_extract_f64",
        })
    }

    // -- Pairwise distance: cdist (#1545 / sub #1535) ------------------------
    //
    // `torch.cdist(x1, x2, p)` is the batched Lp pairwise distance matrix:
    // `x1` is `[b, p_dim, m]`, `x2` is `[b, r_dim, m]`, the result is
    // `[b, p_dim, r_dim]`, `out[b,i,j] = (sum_k |x1[b,i,k]-x2[b,j,k]|^p)^(1/p)`.
    // Mirrors `aten/src/ATen/native/cuda/DistanceKernel.cu:195`
    // (`cdist_kernel_cuda_impl`) and the per-norm `dists<scalar_t>::{p,one,
    // two,inf}` accumulate/finish at `:50-86`. The result stays GPU-resident.
    // The CUDA backend covers `p in {1, 2, inf}` and general `p` for f32; the
    // `p == 0` count-norm (and general-p f64) fall back to the CPU path. Non-
    // test consumer: the `is_cuda()` branch of `cdist` in
    // `ferrotorch-core/src/ops/tensor_ops.rs`.

    /// Batched f32 `cdist`. `x1`/`x2` are `[b, p_dim, m]` / `[b, r_dim, m]`
    /// flattened; result is `[b, p_dim, r_dim]` flattened. Returns the
    /// resident `b * p_dim * r_dim`-element output.
    #[allow(clippy::too_many_arguments)]
    fn cdist_f32(
        &self,
        _x1: &GpuBufferHandle,
        _x2: &GpuBufferHandle,
        _b: usize,
        _p_dim: usize,
        _r_dim: usize,
        _m: usize,
        _p: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "cdist_f32" })
    }

    /// Batched f64 `cdist`. The f64 GPU kernel covers `p in {1, 2, inf}`;
    /// see [`Self::cdist_f32`] and [`cdist_supported_f64`].
    #[allow(clippy::too_many_arguments)]
    fn cdist_f64(
        &self,
        _x1: &GpuBufferHandle,
        _x2: &GpuBufferHandle,
        _b: usize,
        _p_dim: usize,
        _r_dim: usize,
        _m: usize,
        _p: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "cdist_f64" })
    }

    // -- Orthogonal-polynomial special functions (#1545 / #1533) -------------
    //
    // Each evaluates the n-th degree basis polynomial pointwise on a CUDA
    // buffer via an on-device three-term recurrence (one thread per element,
    // no host round-trip). The math mirrors the ferrotorch CPU recurrences in
    // `ferrotorch_core::special` so the GPU result equals the CPU result
    // bit-for-relevant-tolerance. The upstream recurrence reference is
    // `aten/src/ATen/native/Math.h` `chebyshev_polynomial_t_forward` et al.
    //
    // The chebyshev method folds T/U/V/W and their shifted variants into one
    // entry via `(seed_a, seed_b, shift)`: `q1 = seed_a*xx + seed_b` with
    // `xx = shift ? 2x-1 : x` (T: 1,0; U: 2,0; V: 2,-1; W: 2,1). Defaults
    // return `InvalidArgument` so non-CUDA backends compile unchanged; the
    // CUDA backend overrides all ten.

    /// Chebyshev polynomial (T/U/V/W + shifted) forward, f32. See the module
    /// comment for the `(seed_a, seed_b, shift)` kind selector.
    fn chebyshev_poly_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
        _seed_a: f32,
        _seed_b: f32,
        _shift: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "chebyshev_poly_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Chebyshev polynomial (T/U/V/W + shifted) forward, f64.
    fn chebyshev_poly_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
        _seed_a: f64,
        _seed_b: f64,
        _shift: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "chebyshev_poly_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Hermite (physicist's) `H_n` forward, f32.
    fn hermite_h_poly_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "hermite_h_poly_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Hermite (physicist's) `H_n` forward, f64.
    fn hermite_h_poly_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "hermite_h_poly_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Hermite (probabilist's) `He_n` forward, f32.
    fn hermite_he_poly_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "hermite_he_poly_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Hermite (probabilist's) `He_n` forward, f64.
    fn hermite_he_poly_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "hermite_he_poly_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Laguerre `L_n` forward, f32.
    fn laguerre_poly_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "laguerre_poly_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Laguerre `L_n` forward, f64.
    fn laguerre_poly_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "laguerre_poly_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Legendre `P_n` forward, f32.
    fn legendre_poly_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "legendre_poly_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Legendre `P_n` forward, f64.
    fn legendre_poly_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "legendre_poly_f64 GPU op not implemented for this backend".into(),
        })
    }

    // -- Normal-distribution trio: entr / ndtr / ndtri (#1651, batch 1) ------
    //
    // Each method launches an on-device elementwise PTX kernel (one thread per
    // element, no host round-trip). The math mirrors the ferrotorch CPU scalar
    // evaluators (`entr_scalar`, `ndtr_scalar`, `ndtri_f64`) so the GPU result
    // equals the CPU result bit-for-relevant-tolerance. Upstream kernels:
    // `entr_string` / `ndtri_string` (`aten/src/ATen/native/cuda/Math.cuh:463-480,
    // 48-173`) and `calc_ndtr` (`aten/src/ATen/native/UnaryOps.cpp:715-718`).
    // Defaults return `InvalidArgument` so non-CUDA backends compile unchanged;
    // the CUDA backend overrides all six.

    /// Entropy `entr(x)` forward, f32.
    fn entr_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "entr_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Entropy `entr(x)` forward, f64.
    fn entr_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "entr_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Standard-normal CDF `ndtr(x)` forward, f32.
    fn ndtr_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "ndtr_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Standard-normal CDF `ndtr(x)` forward, f64.
    fn ndtr_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "ndtr_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Inverse standard-normal CDF `ndtri(p)` forward, f32.
    fn ndtri_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "ndtri_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Inverse standard-normal CDF `ndtri(p)` forward, f64.
    fn ndtri_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "ndtri_f64 GPU op not implemented for this backend".into(),
        })
    }

    // -- Modified-Bessel-I family: i0 / i0e / i1 / i1e (#1651, batch 2) -------
    //
    // Each method launches an on-device elementwise PTX kernel (one thread per
    // element, no host round trip). The f32 math mirrors the ferrotorch CPU
    // scalar evaluators (`i0_f64` ... narrowed) bit-for-relevant-tolerance.
    // Upstream Cephes kernels: `i0_string` / `i1_string` / `i1e_string`
    // (`aten/src/ATen/native/cuda/Math.cuh:502-555, 575-622, 647-696`) and
    // `calc_i0e` (`aten/src/ATen/native/Math.h:101-145`). Defaults return
    // `InvalidArgument` so non-CUDA backends compile unchanged; the CUDA
    // backend overrides f32 (f64 -> `NotImplementedOnCuda`: base PTX has no
    // `lg2.approx.f64`/`ex2.approx.f64`, same constraint as batch 1).

    /// Modified Bessel `i0(x)` forward, f32.
    fn i0_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i0_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Modified Bessel `i0(x)` forward, f64.
    fn i0_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i0_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `i0e(x)` forward, f32.
    fn i0e_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i0e_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `i0e(x)` forward, f64.
    fn i0e_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i0e_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Modified Bessel `i1(x)` forward, f32.
    fn i1_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i1_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Modified Bessel `i1(x)` forward, f64.
    fn i1_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i1_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `i1e(x)` forward, f32.
    fn i1e_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i1e_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `i1e(x)` forward, f64.
    fn i1e_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "i1e_f64 GPU op not implemented for this backend".into(),
        })
    }

    // Spherical Bessel `j0(x)` forward (#1651 batch 3a). `j0(x) = sin(x)/x`
    // with the `|x| < 0.5` Taylor branch and `isinf -> 0`
    // (`aten/src/ATen/native/cuda/Math.cuh:3039-3052`). Defaults return
    // `InvalidArgument` so non-CUDA backends compile unchanged; the CUDA
    // backend overrides f32 (f64 -> `NotImplementedOnCuda`: base PTX has no
    // `lg2.approx.f64`/`ex2.approx.f64`, same constraint as batches 1/2).

    /// Spherical Bessel `j0(x)` forward, f32.
    fn spherical_bessel_j0_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "spherical_bessel_j0_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Spherical Bessel `j0(x)` forward, f64.
    fn spherical_bessel_j0_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "spherical_bessel_j0_f64 GPU op not implemented for this backend".into(),
        })
    }

    // Modified-Bessel-K family (#1651 batch 3b): k0 / scaled-k0 / k1 / scaled-k1.
    // f32 runs an on-device elementwise PTX kernel (one thread per element, no
    // host round trip). The f32 math mirrors the ferrotorch CPU f64 scalar
    // evaluators (`modified_bessel_k0_f64` ... narrowed to f32): the shared
    // `chbevl` Clenshaw recurrence over the Cephes A/B tables, with the small
    // region (`x <= 2`) composing `log(0.5x)` (via `lg2.approx.f32`*ln2) and the
    // inner `i0`/`i1` (via `ex2.approx.f32(x*log2e)`). Upstream Cephes kernels:
    // `modified_bessel_k0_forward` / `_k1_forward` and the scaled variants
    // (`aten/src/ATen/native/cuda/Math.cuh:2503-2577, 2582-2656, 2661-2736,
    // 2740-2815`). Defaults return `InvalidArgument` so non-CUDA backends compile
    // unchanged; the CUDA backend overrides f32 (f64 -> `NotImplementedOnCuda`:
    // base PTX has no `lg2.approx.f64`/`ex2.approx.f64`, same constraint as the
    // I-family batch 2 and spherical batch 3a).

    /// Modified Bessel `k0(x)` forward, f32.
    fn modified_bessel_k0_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "modified_bessel_k0_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Modified Bessel `k0(x)` forward, f64.
    fn modified_bessel_k0_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "modified_bessel_k0_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `scaled_modified_bessel_k0(x)` forward, f32.
    fn scaled_modified_bessel_k0_f32(
        &self,
        _a: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scaled_modified_bessel_k0_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `scaled_modified_bessel_k0(x)` forward, f64.
    fn scaled_modified_bessel_k0_f64(
        &self,
        _a: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scaled_modified_bessel_k0_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Modified Bessel `k1(x)` forward, f32.
    fn modified_bessel_k1_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "modified_bessel_k1_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Modified Bessel `k1(x)` forward, f64.
    fn modified_bessel_k1_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "modified_bessel_k1_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `scaled_modified_bessel_k1(x)` forward, f32.
    fn scaled_modified_bessel_k1_f32(
        &self,
        _a: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scaled_modified_bessel_k1_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Exp-scaled modified Bessel `scaled_modified_bessel_k1(x)` forward, f64.
    fn scaled_modified_bessel_k1_f64(
        &self,
        _a: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scaled_modified_bessel_k1_f64 GPU op not implemented for this backend".into(),
        })
    }

    // -- Airy Ai + Hurwitz zeta (#1651 GPU tail) ------------------------------
    //
    // f32 runs an on-device PTX kernel (no host round trip). `airy_ai` is a
    // unary multi-region Cephes rational/series (FIXED 36-iter central Maclaurin
    // unroll); `zeta` is the binary Hurwitz zeta (FIXED 9-iter first sum + FIXED
    // 12-term Euler-Maclaurin tail, both with a relative-MACHEP early-exit
    // flag). Upstream Cephes: `airy_ai_forward` / `zeta` at
    // `aten/src/ATen/native/cuda/Math.cuh:1280-1459, 299-383`. Defaults return
    // `InvalidArgument` so non-CUDA backends compile unchanged; the CUDA backend
    // overrides f32 (f64 -> `NotImplementedOnCuda`: base PTX has no
    // `lg2.approx.f64`/`ex2.approx.f64`, same constraint as the earlier #1651
    // batches). bf16/f16 are rejected by the core dispatch before reaching here.

    /// Airy function of the first kind `Ai(x)` forward, f32.
    fn airy_ai_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "airy_ai_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Airy function of the first kind `Ai(x)` forward, f64.
    fn airy_ai_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "airy_ai_f64 GPU op not implemented for this backend".into(),
        })
    }
    /// Hurwitz zeta `zeta(x, q)` forward, f32. `x` is the exponent buffer,
    /// `q` the shift; both equal-length.
    fn zeta_f32(
        &self,
        _x: &GpuBufferHandle,
        _q: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "zeta_f32 GPU op not implemented for this backend".into(),
        })
    }
    /// Hurwitz zeta `zeta(x, q)` forward, f64.
    fn zeta_f64(
        &self,
        _x: &GpuBufferHandle,
        _q: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "zeta_f64 GPU op not implemented for this backend".into(),
        })
    }

    // Clamp: out[i] = max(min_val, min(max_val, x[i]))
    fn clamp_f32(
        &self,
        _a: &GpuBufferHandle,
        _min_val: f32,
        _max_val: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "clamp_f32 GPU op not yet implemented".into(),
        })
    }
    fn clamp_f64(
        &self,
        _a: &GpuBufferHandle,
        _min_val: f64,
        _max_val: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "clamp_f64 GPU op not yet implemented".into(),
        })
    }

    /// VJP for `clamp(x, min, max)`: `out[i] = grad[i]` when `x[i]` is in
    /// `[min, max]`, else `0`. (#524)
    fn clamp_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
        _min_val: f32,
        _max_val: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "clamp_backward_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 counterpart. (#524)
    fn clamp_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
        _min_val: f64,
        _max_val: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "clamp_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // SiLU activation: out[i] = x * sigmoid(x)
    fn silu_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "silu_f32 GPU op not yet implemented".into(),
        })
    }
    fn silu_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "silu_f64 GPU op not yet implemented".into(),
        })
    }
    fn silu_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "silu_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn silu_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "silu_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // ELU activation: out[i] = x > 0 ? x : alpha*(exp(x)-1)
    fn elu_f32(&self, _a: &GpuBufferHandle, _alpha: f32) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "elu_f32 GPU op not yet implemented".into(),
        })
    }
    fn elu_f64(&self, _a: &GpuBufferHandle, _alpha: f64) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "elu_f64 GPU op not yet implemented".into(),
        })
    }
    fn elu_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
        _alpha: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "elu_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn elu_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
        _alpha: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "elu_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // Mish activation: out[i] = x * tanh(softplus(x))
    fn mish_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mish_f32 GPU op not yet implemented".into(),
        })
    }
    fn mish_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mish_f64 GPU op not yet implemented".into(),
        })
    }
    fn mish_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mish_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn mish_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _input: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mish_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // LogSoftmax: out[i] = x[i] - log(sum(exp(x))) (row-wise)
    fn log_softmax_f32(
        &self,
        _a: &GpuBufferHandle,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "log_softmax_f32 GPU op not yet implemented".into(),
        })
    }
    fn log_softmax_f64(
        &self,
        _a: &GpuBufferHandle,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "log_softmax_f64 GPU op not yet implemented".into(),
        })
    }
    // LogSoftmax backward: out[i] = grad[i] - softmax[i] * sum(grad) (row-wise)
    fn log_softmax_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "log_softmax_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn log_softmax_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "log_softmax_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // Indexing operations
    // index_select_1d: out[i] = input[indices[i]]  (indices stored as f32)
    fn index_select_1d_f32(
        &self,
        input: &GpuBufferHandle,
        indices: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn index_select_1d_f64(
        &self,
        _input: &GpuBufferHandle,
        _indices: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "index_select_1d_f64 GPU op not yet implemented".into(),
        })
    }
    // scatter_add_1d: out = zeros(input_len); for i: out[indices[i]] += grad_output[i]  (atomic)
    fn scatter_add_1d_f32(
        &self,
        grad_output: &GpuBufferHandle,
        indices: &GpuBufferHandle,
        input_len: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn scatter_add_1d_f64(
        &self,
        _grad_output: &GpuBufferHandle,
        _indices: &GpuBufferHandle,
        _input_len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scatter_add_1d_f64 GPU op not yet implemented".into(),
        })
    }
    // index_select_dim: gather slices along an arbitrary axis (N-D).
    //
    // Forward layout (contract):
    //   `input`  has logical shape `[outer, in_dim_size, inner]` after
    //   collapsing the axes before/after `dim`. `indices` is an
    //   `out_dim_size`-long f32 buffer encoding integer offsets into
    //   the `in_dim_size` axis (caller-validated, non-negative,
    //   in-range). The kernel writes
    //     `output[o, i, k] = input[o, indices[i], k]`
    //   for `o in [0, outer), i in [0, out_dim_size), k in [0, inner)`.
    // The output buffer has length `outer * out_dim_size * inner`.
    //
    // This subsumes the 1-D `index_select_1d_*` ops for ndim>=2 with
    // arbitrary `dim`. The 1-D ops are kept for the
    // `IndexSelectBackward` (single-axis 1-D index) call site, which
    // predates this op.
    fn index_select_dim_f32(
        &self,
        input: &GpuBufferHandle,
        indices: &GpuBufferHandle,
        outer: usize,
        in_dim_size: usize,
        out_dim_size: usize,
        inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn index_select_dim_f64(
        &self,
        _input: &GpuBufferHandle,
        _indices: &GpuBufferHandle,
        _outer: usize,
        _in_dim_size: usize,
        _out_dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "index_select_dim_f64 GPU op not yet implemented".into(),
        })
    }
    // masked_fill: out[i] = mask[i] ? value : input[i]  (mask stored as f32, 1.0/0.0)
    fn masked_fill_f32(
        &self,
        input: &GpuBufferHandle,
        mask: &GpuBufferHandle,
        value: f32,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn masked_fill_f64(
        &self,
        _input: &GpuBufferHandle,
        _mask: &GpuBufferHandle,
        _value: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "masked_fill_f64 GPU op not yet implemented".into(),
        })
    }
    // masked_fill with a GPU-resident Bool (u8) mask, dispatched on input.dtype()
    // (crosslink #1185 Phase 3c). `out[i] = mask[i]!=0 ? value : input[i]`.
    // Covers f32/f64/bf16/f16 (+ i32/i64). The scalar `value` is passed as f64
    // and converted to the input dtype in the backend (for bf16/f16 it is
    // narrowed in-kernel). `mask` MUST be tagged `DType::Bool` and have the same
    // numel as `input`; the result keeps `input`'s dtype and stays GPU-resident.
    // Unlike `masked_fill_f32`, the mask is the resident bool buffer — no
    // float-mask upload, no host crossing.
    fn masked_fill_dt(
        &self,
        _input: &GpuBufferHandle,
        _mask: &GpuBufferHandle,
        _value: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "masked_fill_dt",
        })
    }

    // where_cond / torch.where with a GPU-resident Bool (u8) condition
    // (crosslink #1185 Phase 3c). `out[i] = cond[i]!=0 ? x[i] : y[i]`, dispatched
    // on x.dtype(). `cond` MUST be tagged `DType::Bool`; `x.dtype() == y.dtype()`
    // and all three buffers MUST have equal numel. The result keeps x's dtype and
    // stays GPU-resident. Covers f32/f64/bf16/f16 (+ i32/i64).
    fn where_cond(
        &self,
        _cond: &GpuBufferHandle,
        _x: &GpuBufferHandle,
        _y: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "where_cond" })
    }

    // masked_select stream compaction (crosslink #1185 Phase 3c). Returns
    // `(out, len)` where `out` is a 1-D GPU-resident buffer of x's dtype holding
    // the `len` elements of `input` where `mask` is true. `mask` MUST be tagged
    // `DType::Bool` with the same numel as `input`. `len` is the on-device true
    // count read once to the host to size the data-dependent output — that single
    // integer is the result SHAPE, not a data round-trip (PyTorch parity: a CUDA
    // sync sizes `torch.masked_select`'s output). Covers f32/f64/bf16/f16
    // (+ i32/i64).
    fn masked_select(
        &self,
        _input: &GpuBufferHandle,
        _mask: &GpuBufferHandle,
    ) -> FerrotorchResult<(GpuBufferHandle, usize)> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "masked_select",
        })
    }

    // masked_scatter — the resident VJP of `masked_select` (crosslink #1187
    // Phase 3d). Scatter the compacted `grad_compact` (length = #true) back into
    // a zeros buffer of `out_numel` elements at the flat C-order positions where
    // `mask` is true: `out[i] = mask[i]!=0 ? grad_compact[j++] : 0`. `mask` MUST
    // be tagged `DType::Bool` with `mask.len() == out_numel`; the result keeps
    // `grad_compact`'s dtype and stays GPU-resident. Covers f32/f64/bf16/f16
    // (+ i32/i64). This is the inverse of the Phase-3c compaction kernel.
    fn masked_scatter(
        &self,
        _grad_compact: &GpuBufferHandle,
        _mask: &GpuBufferHandle,
        _out_numel: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "masked_scatter",
        })
    }

    // masked_scatter FORWARD (#1662): the on-device `Tensor::masked_scatter`
    // forward when input, source and mask are all CUDA-resident.
    // `out[i] = mask[i]!=0 ? source[j++] : input[i]`, source consumed serially
    // in flat C-order (the source-index `j` is the exclusive prefix-sum of the
    // mask, matching upstream `aten/src/ATen/native/cuda/IndexKernel.cu:416-453`).
    // `input` and `mask` MUST have equal numel == `n`; `mask` MUST be tagged
    // `DType::Bool`; `source` must hold >= count_nonzero(mask) elements (the
    // caller checks this). Result keeps `input`'s dtype and stays GPU-resident
    // (NO host round trip — R-CODE-4). Covers f32/f64.
    fn masked_scatter_forward(
        &self,
        _input: &GpuBufferHandle,
        _source: &GpuBufferHandle,
        _mask: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "masked_scatter_forward",
        })
    }

    // broadcast_bool (#1663): expand a `DType::Bool` (u8 0/1) mask from
    // `in_shape` to a larger `out_shape` ENTIRELY on device, using NumPy / torch
    // broadcasting rules (align trailing dims; a size-1 or absent input dim
    // replicates). This is the resident analog of the CPU
    // `grad_fns::indexing::broadcast_bool_tensor`, mirroring the
    // `expand_outplace(mask, self)` step PyTorch performs for masked ops at
    // `aten/src/ATen/native/TensorAdvancedIndexing.cpp:2406`. `mask` MUST be
    // tagged `DType::Bool` with `mask.len() == product(in_shape)`; the result is
    // a `DType::Bool` handle of `product(out_shape)` elements and stays
    // GPU-resident (NO host round trip — R-CODE-4). The default impl returns
    // `NotImplementedOnCuda` so non-CUDA backends compile unchanged.
    fn broadcast_bool(
        &self,
        _mask: &GpuBufferHandle,
        _in_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_bool",
        })
    }

    // masked_zero: out[i] = mask[i] ? 0.0 : grad[i]  (backward of masked_fill)
    fn masked_zero_f32(
        &self,
        grad: &GpuBufferHandle,
        mask: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle>;
    fn masked_zero_f64(
        &self,
        _grad: &GpuBufferHandle,
        _mask: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "masked_zero_f64 GPU op not yet implemented".into(),
        })
    }

    // Elementwise unary/binary f32 (default impls for forward ops)
    fn div_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "div_f32 GPU op not yet implemented".into(),
        })
    }
    fn div_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "div_f64 GPU op not yet implemented".into(),
        })
    }
    fn exp_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "exp_f32 GPU op not yet implemented".into(),
        })
    }
    fn exp_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "exp_f64 GPU op not yet implemented".into(),
        })
    }
    fn log_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "log_f32 GPU op not yet implemented".into(),
        })
    }
    fn log_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "log_f64 GPU op not yet implemented".into(),
        })
    }
    fn sqrt_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sqrt_f32 GPU op not yet implemented".into(),
        })
    }
    fn sqrt_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sqrt_f64 GPU op not yet implemented".into(),
        })
    }
    fn pow_f32(&self, _a: &GpuBufferHandle, _exponent: f32) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "pow_f32 GPU op not yet implemented".into(),
        })
    }
    fn pow_f64(&self, _a: &GpuBufferHandle, _exponent: f64) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "pow_f64 GPU op not yet implemented".into(),
        })
    }
    fn abs_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "abs_f32 GPU op not yet implemented".into(),
        })
    }
    fn abs_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "abs_f64 GPU op not yet implemented".into(),
        })
    }
    fn sigmoid_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sigmoid_f32 GPU op not yet implemented".into(),
        })
    }
    fn sigmoid_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sigmoid_f64 GPU op not yet implemented".into(),
        })
    }
    fn tanh_f32(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "tanh_f32 GPU op not yet implemented".into(),
        })
    }
    fn tanh_f64(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "tanh_f64 GPU op not yet implemented".into(),
        })
    }

    // Sigmoid backward: out[i] = grad[i] * output[i] * (1 - output[i])
    fn sigmoid_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sigmoid_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn sigmoid_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sigmoid_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // Tanh backward: out[i] = grad[i] * (1 - output[i]^2)
    fn tanh_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "tanh_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn tanh_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "tanh_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // Softmax backward: out[i] = output[i] * (grad[i] - dot(grad_row, output_row))
    fn softmax_backward_f32(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "softmax_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn softmax_backward_f64(
        &self,
        _grad: &GpuBufferHandle,
        _output: &GpuBufferHandle,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "softmax_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // LayerNorm backward: computes grad_input, grad_weight, grad_bias on GPU
    fn layernorm_backward_f32(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f32,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "layernorm_backward_f32 GPU op not yet implemented".into(),
        })
    }
    fn layernorm_backward_f64(
        &self,
        _input: &GpuBufferHandle,
        _grad_output: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f64,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "layernorm_backward_f64 GPU op not yet implemented".into(),
        })
    }

    // Sum along one axis of a tensor
    fn sum_axis_f32(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axis: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sum_axis_f32 GPU op not yet implemented".into(),
        })
    }
    fn sum_axis_f64(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axis: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sum_axis_f64 GPU op not yet implemented".into(),
        })
    }

    // Strided split: extract a sub-tensor along one axis entirely on GPU.
    fn strided_split_f32(
        &self,
        _input: &GpuBufferHandle,
        _total_along_axis: usize,
        _split_offset: usize,
        _split_size: usize,
        _inner_size: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "strided_split_f32 GPU op not yet implemented".into(),
        })
    }
    fn strided_split_f64(
        &self,
        _input: &GpuBufferHandle,
        _total_along_axis: usize,
        _split_offset: usize,
        _split_size: usize,
        _inner_size: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "strided_split_f64 GPU op not yet implemented".into(),
        })
    }

    // Strided copy: gather an N-d strided view into a contiguous
    // output buffer entirely on GPU. CL-496.
    fn strided_copy_f32(
        &self,
        _input: &GpuBufferHandle,
        _out_shape: &[usize],
        _src_strides: &[isize],
        _src_offset: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "strided_copy_f32 GPU op not yet implemented".into(),
        })
    }
    fn strided_copy_f64(
        &self,
        _input: &GpuBufferHandle,
        _out_shape: &[usize],
        _src_strides: &[isize],
        _src_offset: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "strided_copy_f64 GPU op not yet implemented".into(),
        })
    }

    // Strided scatter: write a contiguous src into strided positions of
    // dst (in-place). Inverse of strided_copy. Used by
    // `Tensor::as_strided_scatter` for CUDA tensors. (#574)
    fn strided_scatter_f32(
        &self,
        _src: &GpuBufferHandle,
        _dst: &mut GpuBufferHandle,
        _view_shape: &[usize],
        _dst_strides: &[isize],
        _dst_offset: usize,
    ) -> FerrotorchResult<()> {
        Err(FerrotorchError::InvalidArgument {
            message: "strided_scatter_f32 GPU op not yet implemented".into(),
        })
    }
    fn strided_scatter_f64(
        &self,
        _src: &GpuBufferHandle,
        _dst: &mut GpuBufferHandle,
        _view_shape: &[usize],
        _dst_strides: &[isize],
        _dst_offset: usize,
    ) -> FerrotorchResult<()> {
        Err(FerrotorchError::InvalidArgument {
            message: "strided_scatter_f64 GPU op not yet implemented".into(),
        })
    }

    // Strided cat: write a sub-tensor into a larger buffer at an offset along
    // one axis on GPU. Dtype-generic via `elem_size`: PyTorch's
    // `aten::cat_out_cuda` (`aten/src/ATen/native/cuda/Shape.cu`) does the same
    // — the host computes the scalar size once, then dispatches into a
    // strided-memcpy kernel whose body only depends on element width (no
    // arithmetic). Concrete backends are expected to support at least
    // `elem_size in {2, 4, 8}` (covers `bf16`/`f16`, `f32`, `f64`); other
    // widths must return an error so the caller can fall back rather than
    // silently produce wrong data.
    #[allow(clippy::too_many_arguments)]
    fn strided_cat(
        &self,
        _src: &GpuBufferHandle,
        _dst: &mut GpuBufferHandle,
        _total_along_axis: usize,
        _offset: usize,
        _t_axis_size: usize,
        _inner: usize,
        _t_numel: usize,
        elem_size: usize,
    ) -> FerrotorchResult<()> {
        Err(FerrotorchError::InvalidArgument {
            message: format!(
                "strided_cat (elem_size={elem_size}) GPU op not implemented for this backend"
            ),
        })
    }

    /// Check if a GPU buffer contains any inf or NaN values.
    ///
    /// Required method (no default impl): backends must provide an
    /// implementation rather than silently fall back to a host-readback
    /// scan. The previous default impl made the host detour invisible at
    /// the call site, hiding a synchronous device-to-host round-trip behind
    /// a trait-method default. Removing it forces the badness to be visible
    /// at each backend's impl site.
    fn has_inf_nan_f32(&self, a: &GpuBufferHandle) -> FerrotorchResult<bool>;

    // GPU RNG state management (for gradient checkpointing)
    /// Save the current GPU RNG state for a device. Used by checkpoint to
    /// ensure dropout masks are identical on recomputation.
    fn save_rng_state(&self, device: usize) -> FerrotorchResult<GpuRngState> {
        Err(FerrotorchError::InvalidArgument {
            message: format!("save_rng_state not implemented for device {device}"),
        })
    }

    /// Restore a previously saved GPU RNG state for a device.
    fn restore_rng_state(&self, state: GpuRngState) -> FerrotorchResult<()> {
        let _ = state;
        Err(FerrotorchError::InvalidArgument {
            message: "restore_rng_state not implemented".into(),
        })
    }

    /// Generate `numel` uniform-`[0, 1)` f32 values directly on the GPU.
    ///
    /// PyTorch parity: `torch.rand(size, device='cuda')` lowers to
    /// `at::empty(size, options).uniform_(0, 1)`
    /// (`aten/src/ATen/native/TensorFactories.cpp:1075-1076`); the tensor is
    /// created ON the CUDA device and filled by the on-device curand/Philox
    /// kernel — there is no CPU generate-then-upload. This trait slot is the
    /// on-device equivalent: the backend produces a `DType::F32` GPU buffer of
    /// `numel` uniform values without any host round trip (R-CODE-4).
    ///
    /// The backend snapshots and advances its per-device Philox counter (the
    /// `torch.cuda` default generator analog), so output is reproducible after
    /// [`Self::manual_seed_gpu`].
    ///
    /// Default returns `NotImplementedOnCuda` so non-CUDA backends compile
    /// unchanged and the caller falls back to the CPU `rand` path.
    fn rand_uniform_f32(&self, _numel: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "rand_uniform_f32",
        })
    }

    /// Generate `numel` standard-normal f32 values directly on the GPU.
    ///
    /// PyTorch parity: `torch.randn(size, device='cuda')` lowers to
    /// `at::empty(size, options).normal_(0, 1)`
    /// (`aten/src/ATen/native/TensorFactories.cpp:1379`). f32 counterpart of
    /// [`Self::rand_uniform_f32`] using the Box-Muller Philox normal kernel.
    fn randn_normal_f32(&self, _numel: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "randn_normal_f32",
        })
    }

    /// Seed every GPU device's RNG generator (`torch.cuda.manual_seed_all`
    /// analog at `torch/cuda/random.py:112`).
    ///
    /// `ferrotorch_core::manual_seed` calls this after seeding the CPU
    /// MT19937 generator, mirroring `torch.manual_seed` which seeds both the
    /// CPU and all CUDA generators (`torch/random.py:67` —
    /// `torch.cuda.manual_seed_all(seed)`). Default is a no-op so non-CUDA
    /// backends compile unchanged.
    fn manual_seed_gpu(&self, _seed: u64) -> FerrotorchResult<()> {
        Ok(())
    }

    // GPU linear algebra via cuSOLVER
    fn svd_f32(
        &self,
        _a: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "svd_f32 GPU op not yet implemented".into(),
        })
    }
    fn svd_f64(
        &self,
        _a: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "svd_f64 GPU op not yet implemented".into(),
        })
    }
    fn cholesky_f32(&self, _a: &GpuBufferHandle, _n: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "cholesky_f32 GPU op not yet implemented".into(),
        })
    }
    fn cholesky_f64(&self, _a: &GpuBufferHandle, _n: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "cholesky_f64 GPU op not yet implemented".into(),
        })
    }
    fn solve_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
        _nrhs: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "solve_f32 GPU op not yet implemented".into(),
        })
    }
    fn solve_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _n: usize,
        _nrhs: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "solve_f64 GPU op not yet implemented".into(),
        })
    }
    fn qr_f32(
        &self,
        _a: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "qr_f32 GPU op not yet implemented".into(),
        })
    }
    fn qr_f64(
        &self,
        _a: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "qr_f64 GPU op not yet implemented".into(),
        })
    }

    /// LU factorization in cuSOLVER's packed form: returns
    /// `(LU_packed, pivots)` where `LU_packed` is an `n×n` row-major GPU
    /// tensor handle (strict lower = `L`, upper = `U`), and `pivots` is a
    /// host `Vec<i32>` of length `n` (1-based row-permutation indices,
    /// LAPACK convention). The pivot vector is small (O(n)) and inherently
    /// host-readable, so we return it materialized on host rather than
    /// inventing a typed-int GPU handle. Mirrors `torch.linalg.lu_factor`.
    /// (#604)
    fn lu_factor_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, Vec<i32>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "lu_factor_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 counterpart of [`Self::lu_factor_f32`]. (#604)
    fn lu_factor_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, Vec<i32>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "lu_factor_f64 GPU op not yet implemented".into(),
        })
    }

    /// GPU-resident least-squares solver via cuSOLVER `cusolverDnSSgels`
    /// (iterative refinement). Solves `min ||A X - B||_F` for `A: m×n`,
    /// `B: m×nrhs`. Returns `X: n×nrhs`. Mirrors `torch.linalg.lstsq`'s
    /// solution output. (#630)
    fn lstsq_f32(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _n: usize,
        _nrhs: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "lstsq_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 counterpart. (#630)
    fn lstsq_f64(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _n: usize,
        _nrhs: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "lstsq_f64 GPU op not yet implemented".into(),
        })
    }

    /// Non-symmetric eigendecomposition via cuSOLVER `cusolverDnXgeev`.
    /// Returns `(eigenvalues, eigenvectors)` as **complex** GPU tensors:
    ///   - eigenvalues: length `2n` interleaved re/im (logical `[n, 2]`)
    ///   - eigenvectors: length `2 * n * n` row-major interleaved
    ///     (logical `[n, n, 2]`)
    ///
    /// Mirrors `torch.linalg.eig`. (#631)
    fn eig_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "eig_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 counterpart. (#631)
    fn eig_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "eig_f64 GPU op not yet implemented".into(),
        })
    }
    /// Symmetric eigendecomposition (eigenvalues + eigenvectors) of an
    /// `n × n` real symmetric matrix. Returns `(eigenvalues, eigenvectors)`
    /// where eigenvectors is row-major with column `j` the `j`-th eigenvector.
    fn eigh_f32(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "eigh_f32 GPU op not yet implemented".into(),
        })
    }
    fn eigh_f64(
        &self,
        _a: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "eigh_f64 GPU op not yet implemented".into(),
        })
    }
    /// Eigenvalues only of an `n × n` real symmetric matrix.
    fn eigvalsh_f32(&self, _a: &GpuBufferHandle, _n: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "eigvalsh_f32 GPU op not yet implemented".into(),
        })
    }
    fn eigvalsh_f64(&self, _a: &GpuBufferHandle, _n: usize) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "eigvalsh_f64 GPU op not yet implemented".into(),
        })
    }

    // GPU 1-D FFT primitives via cuFFT. (#579)
    //
    // - C2C: input/output layout `[batch * n * 2]` interleaved (re, im).
    // - R2C: input `[batch * n]` real → output `[batch * (n/2+1) * 2]` complex.
    // - C2R: input `[batch * (n_out/2+1) * 2]` complex → output `[batch * n_out]` real.
    // - Inverse transforms include 1/n normalization to match torch / numpy.
    fn fft_c2c_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fft_c2c_f32 GPU op not yet implemented".into(),
        })
    }
    fn fft_c2c_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fft_c2c_f64 GPU op not yet implemented".into(),
        })
    }

    /// GPU pad/truncate for complex tensors stored as `[batch, n, 2]`
    /// (#605). Used by the FFT path when the user passes `n != input_n` —
    /// allocates a `[batch, dst_n, 2]` output, copies the visible portion
    /// from `src`, and zero-fills the tail. Single PTX kernel, no host
    /// bounce.
    fn pad_truncate_complex_f32(
        &self,
        _src: &GpuBufferHandle,
        _batch: usize,
        _src_n: usize,
        _dst_n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "pad_truncate_complex_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 counterpart of [`Self::pad_truncate_complex_f32`]. (#605)
    fn pad_truncate_complex_f64(
        &self,
        _src: &GpuBufferHandle,
        _batch: usize,
        _src_n: usize,
        _dst_n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "pad_truncate_complex_f64 GPU op not yet implemented".into(),
        })
    }

    /// 2-D complex-to-complex FFT via cufftPlan2d. Input/output layout
    /// `[h, w, 2]` interleaved complex. `inverse=true` divides by `h*w`.
    /// (#634)
    fn fft2_c2c_f32(
        &self,
        _a: &GpuBufferHandle,
        _h: usize,
        _w: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fft2_c2c_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 2-D FFT counterpart. (#634)
    fn fft2_c2c_f64(
        &self,
        _a: &GpuBufferHandle,
        _h: usize,
        _w: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fft2_c2c_f64 GPU op not yet implemented".into(),
        })
    }

    /// Broadcast a `[outer, inner]` tensor into `[outer, repeat_count, inner]`
    /// by replicating along the inserted middle dim. Used for sum_dim /
    /// mean_dim backward where the gradient must be expanded along the
    /// previously-reduced dim. (#524)
    fn repeat_along_dim_f32(
        &self,
        _input: &GpuBufferHandle,
        _outer: usize,
        _repeat_count: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "repeat_along_dim_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 counterpart. (#524)
    fn repeat_along_dim_f64(
        &self,
        _input: &GpuBufferHandle,
        _outer: usize,
        _repeat_count: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "repeat_along_dim_f64 GPU op not yet implemented".into(),
        })
    }
    fn rfft_r2c_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "rfft_r2c_f32 GPU op not yet implemented".into(),
        })
    }
    fn rfft_r2c_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "rfft_r2c_f64 GPU op not yet implemented".into(),
        })
    }
    fn irfft_c2r_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n_out: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "irfft_c2r_f32 GPU op not yet implemented".into(),
        })
    }
    fn irfft_c2r_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n_out: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "irfft_c2r_f64 GPU op not yet implemented".into(),
        })
    }

    /// Hermitian FFT: `hfft(x, n) = irfft(conj(x), n)` on GPU via cuFFT. (#636)
    ///
    /// Input `[batch, half_in, 2]` complex; output `[batch * n_out]` real.
    /// `half_in` must equal `n_out / 2 + 1`.
    fn hfft_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _half_in: usize,
        _n_out: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "hfft_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 Hermitian FFT counterpart. (#636)
    fn hfft_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _half_in: usize,
        _n_out: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "hfft_f64 GPU op not yet implemented".into(),
        })
    }

    /// Inverse Hermitian FFT: `ihfft(x) = conj(rfft(x)) / n` on GPU. (#636)
    ///
    /// Input `[batch * n]` real; output `[batch, n/2+1, 2]` complex.
    fn ihfft_f32(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "ihfft_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 inverse Hermitian FFT counterpart. (#636)
    fn ihfft_f64(
        &self,
        _a: &GpuBufferHandle,
        _batch: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "ihfft_f64 GPU op not yet implemented".into(),
        })
    }

    /// 3-D complex-to-complex FFT via `cufftPlan3d`. (#636)
    ///
    /// Input/output layout `[d, h, w, 2]` interleaved complex.
    /// `inverse=true` divides by `d*h*w`.
    fn fftn3d_c2c_f32(
        &self,
        _a: &GpuBufferHandle,
        _d: usize,
        _h: usize,
        _w: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fftn3d_c2c_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 3-D FFT counterpart. (#636)
    fn fftn3d_c2c_f64(
        &self,
        _a: &GpuBufferHandle,
        _d: usize,
        _h: usize,
        _w: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fftn3d_c2c_f64 GPU op not yet implemented".into(),
        })
    }

    /// 2-D complex-to-complex FFT via `cufftPlanMany` for f32. (#636)
    ///
    /// Input/output layout `[h, w, 2]` interleaved complex.
    /// `inverse=true` divides by `h*w`.
    fn fftn2d_c2c_f32(
        &self,
        _a: &GpuBufferHandle,
        _h: usize,
        _w: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fftn2d_c2c_f32 GPU op not yet implemented".into(),
        })
    }

    /// f64 2-D FFT counterpart. (#636)
    fn fftn2d_c2c_f64(
        &self,
        _a: &GpuBufferHandle,
        _h: usize,
        _w: usize,
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fftn2d_c2c_f64 GPU op not yet implemented".into(),
        })
    }

    // -- axes-aware N-D FFT via cufftPlanMany (#966) -------------------------

    /// Axes-aware N-D complex-to-complex FFT for f32 via `cufftPlanMany`. (#966)
    ///
    /// Transforms over the specified `axes` (normalized to non-negative in
    /// `[0, ndim)`) of the complex input tensor. Input layout: interleaved
    /// `[..., 2]` (re/im pairs); the trailing complex dim is always the last
    /// and is NOT included in `axes`. `shape` is the tensor's spatial dims
    /// (excluding the trailing 2).
    ///
    /// `inverse=true` applies `1 / product(shape[ax] for ax in axes)`
    /// normalization to match `torch.fft.ifftn`.
    ///
    /// Default impl returns `Err` so existing backends compile unchanged.
    fn fftn_axes_c2c_f32(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axes: &[usize],
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fftn_axes_c2c_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// f64 variant of [`Self::fftn_axes_c2c_f32`]. (#966)
    fn fftn_axes_c2c_f64(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axes: &[usize],
        _inverse: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "fftn_axes_c2c_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// Fused Adam optimizer step: updates param, exp_avg, and exp_avg_sq
    /// in a single kernel launch.
    ///
    /// All four buffers (`param`, `grad`, `exp_avg`, `exp_avg_sq`) must have
    /// the same length. `param`, `exp_avg`, and `exp_avg_sq` are modified
    /// in-place.
    #[allow(clippy::too_many_arguments)]
    fn fused_adam_f32(
        &self,
        _param: &mut GpuBufferHandle,
        _grad: &GpuBufferHandle,
        _exp_avg: &mut GpuBufferHandle,
        _exp_avg_sq: &mut GpuBufferHandle,
        _beta1: f32,
        _beta2: f32,
        _lr: f32,
        _eps: f32,
        _bc1: f32,
        _bc2: f32,
        _weight_decay: f32,
    ) -> FerrotorchResult<()> {
        Err(FerrotorchError::InvalidArgument {
            message: "fused_adam_f32 GPU op not yet implemented".into(),
        })
    }

    /// Fused GRU cell forward: pointwise gate computation on pre-computed
    /// gate matrices. Returns `(hy_handle, workspace_handle)`.
    ///
    /// `input_gates` and `hidden_gates` are `[batch, 3*hsz]` from cuBLAS GEMMs.
    /// `bias_ih` and `bias_hh` are `[3*hsz]`. `hx` is `[batch, hsz]`.
    /// `workspace` is `[batch, 5*hsz]` saved for backward.
    fn fused_gru_cell_f32(
        &self,
        _input_gates: &GpuBufferHandle,
        _hidden_gates: &GpuBufferHandle,
        _bias_ih: &GpuBufferHandle,
        _bias_hh: &GpuBufferHandle,
        _hx: &GpuBufferHandle,
        _hidden_size: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::InvalidArgument {
            message: "fused_gru_cell_f32 GPU op not yet implemented".into(),
        })
    }

    /// GPU MaxPool2d forward.
    #[allow(clippy::too_many_arguments)]
    fn maxpool2d_f32(
        &self,
        _input: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _h_in: usize,
        _w_in: usize,
        _kh: usize,
        _kw: usize,
        _sh: usize,
        _sw: usize,
        _ph: usize,
        _pw: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, [usize; 4])> {
        Err(FerrotorchError::InvalidArgument {
            message: "maxpool2d_f32 GPU op not yet implemented".into(),
        })
    }
    #[allow(clippy::too_many_arguments)]
    fn maxpool2d_f64(
        &self,
        _input: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _h_in: usize,
        _w_in: usize,
        _kh: usize,
        _kw: usize,
        _sh: usize,
        _sw: usize,
        _ph: usize,
        _pw: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, [usize; 4])> {
        Err(FerrotorchError::InvalidArgument {
            message: "maxpool2d_f64 GPU op not yet implemented".into(),
        })
    }

    /// GPU AvgPool2d forward.
    #[allow(clippy::too_many_arguments)]
    fn avgpool2d_f32(
        &self,
        _input: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _h_in: usize,
        _w_in: usize,
        _kh: usize,
        _kw: usize,
        _sh: usize,
        _sw: usize,
        _ph: usize,
        _pw: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, [usize; 4])> {
        Err(FerrotorchError::InvalidArgument {
            message: "avgpool2d_f32 GPU op not yet implemented".into(),
        })
    }
    #[allow(clippy::too_many_arguments)]
    fn avgpool2d_f64(
        &self,
        _input: &GpuBufferHandle,
        _batch: usize,
        _channels: usize,
        _h_in: usize,
        _w_in: usize,
        _kh: usize,
        _kw: usize,
        _sh: usize,
        _sw: usize,
        _ph: usize,
        _pw: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, [usize; 4])> {
        Err(FerrotorchError::InvalidArgument {
            message: "avgpool2d_f64 GPU op not yet implemented".into(),
        })
    }

    /// GPU Conv2d forward: im2col + GEMM + bias add, entirely on-device.
    ///
    /// Supports the full `Conv2d::new_full` parameter surface: `groups`
    /// partitions input/output channels and `dilation` spaces the kernel
    /// taps. The dispatch happens on the GPU for every value of these
    /// parameters; there is no CPU detour. Pass `groups = 1` and
    /// `dilation = (1, 1)` for the dense convolution case.
    ///
    /// Returns `(output_handle, output_shape)` where output_shape is `[B, C_out, H_out, W_out]`.
    #[allow(clippy::too_many_arguments)]
    fn conv2d_f32(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _bias: Option<&GpuBufferHandle>,
        _input_shape: [usize; 4],
        _weight_shape: [usize; 4],
        _stride: (usize, usize),
        _padding: (usize, usize),
        _dilation: (usize, usize),
        _groups: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, [usize; 4])> {
        Err(FerrotorchError::InvalidArgument {
            message: "conv2d_f32 GPU op not yet implemented".into(),
        })
    }
    /// GPU Conv2d forward (f64). See [`Self::conv2d_f32`] for parameter
    /// semantics — this is the f64 companion.
    #[allow(clippy::too_many_arguments)]
    fn conv2d_f64(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _bias: Option<&GpuBufferHandle>,
        _input_shape: [usize; 4],
        _weight_shape: [usize; 4],
        _stride: (usize, usize),
        _padding: (usize, usize),
        _dilation: (usize, usize),
        _groups: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, [usize; 4])> {
        Err(FerrotorchError::InvalidArgument {
            message: "conv2d_f64 GPU op not yet implemented".into(),
        })
    }

    // -- Sparse SpMM (cuSPARSE, CSR format) -----------------------------------
    //
    // These cover `SparseTensor::spmm` when the dense operand is a CUDA
    // tensor — PyTorch's `torch.sparse.mm` runs on cuSPARSE in that case.
    // Just-in-time CSR upload from the caller's host-side `(crow_indices,
    // col_indices, values)`; the dense operand is already device-resident.
    // Output `[m, n]` row-major lives on the same device as the dense input.
    //
    // See ferrotorch-core/src/sparse.rs `SparseTensor::spmm` for the call
    // site and ferrotorch-gpu/src/sparse.rs for the cuSPARSE implementation.

    /// CSR sparse-dense matmul on GPU (f32 dtype).
    ///
    /// `crow_indices`: `m + 1` host `u32` row pointers in CSR order.
    /// `col_indices`: `nnz` host `u32` column indices.
    /// `values`: `nnz` host f32 non-zero values.
    /// `dense`: device buffer holding a `[k, n]` row-major dense matrix.
    /// Returns a device buffer holding the `[m, n]` row-major dense result.
    fn spmm_csr_f32(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f32],
        _dense: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "spmm_csr_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// CSR sparse-dense matmul on GPU (f64 dtype). Companion of
    /// [`Self::spmm_csr_f32`].
    fn spmm_csr_f64(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f64],
        _dense: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "spmm_csr_f64 GPU op not implemented for this backend".into(),
        })
    }

    // -- Sparse <-> Dense conversion (cuSPARSE) -------------------------------
    //
    // P3 covers `SparseTensor::to_dense_on(Device::Cuda)` and the GPU branch
    // of `SparseTensor::from_dense` when the dense tensor lives on CUDA.
    // PyTorch parity (rust-gpu-discipline §3): `torch.Tensor.to_dense()` and
    // `torch.Tensor.to_sparse()` keep the result on the input device and
    // dispatch to cuSPARSE on CUDA. We mirror that.
    //
    // These are CSR-shaped: ferrotorch's internal SpMM path is CSR, and
    // cuSPARSE's `*_to_dense`/`*_to_sparse` accept CSR descriptors. The COO
    // → CSR build (host-side row-pointer prefix sum) reuses the same code
    // path as `SparseTensor::spmm`.
    //
    // See ferrotorch-gpu/src/sparse.rs for the implementation.

    /// CSR-form sparse → dense materialization on GPU (f32 dtype).
    ///
    /// Inputs:
    /// - `crow_indices`: `m + 1` host `u32` row pointers.
    /// - `col_indices`: `nnz` host `u32` column indices.
    /// - `values`: `nnz` host f32 non-zero values.
    /// - `device_ordinal`: target CUDA ordinal; output buffer lives there.
    /// - `m`, `n`: output dense shape `[m, n]`, row-major.
    ///
    /// Returns a device buffer holding the `[m, n]` row-major dense result.
    fn sparse_to_dense_csr_f32(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f32],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sparse_to_dense_csr_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// CSR-form sparse → dense materialization on GPU (f64 dtype).
    /// Companion of [`Self::sparse_to_dense_csr_f32`].
    fn sparse_to_dense_csr_f64(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f64],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sparse_to_dense_csr_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// Dense → CSR-form sparse extraction on GPU (f32 dtype).
    ///
    /// Reads a row-major `[m, n]` device dense matrix and returns the CSR
    /// triplet `(crow_indices, col_indices, values)` with **only exact-zero**
    /// entries dropped (PyTorch's `torch.Tensor.to_sparse()` semantics — non-
    /// zero thresholds must be applied by the caller).
    ///
    /// Returns host-side `Vec`s — the caller decides whether to coalesce or
    /// store on device. ferrotorch's `SparseTensor` is CPU-resident so the
    /// host-side return matches that storage model.
    fn dense_to_sparse_csr_f32(
        &self,
        _dense: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f32>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "dense_to_sparse_csr_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// Dense → CSR-form sparse extraction on GPU (f64 dtype).
    /// Companion of [`Self::dense_to_sparse_csr_f32`].
    fn dense_to_sparse_csr_f64(
        &self,
        _dense: &GpuBufferHandle,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f64>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "dense_to_sparse_csr_f64 GPU op not implemented for this backend".into(),
        })
    }

    // -- CSR/CSC/COO format-conversion + to_dense (cuSPARSE) -- P7 ------------
    //
    // PyTorch parity (rust-gpu-discipline §3): `torch.sparse_csr_tensor` /
    // `torch.sparse_csc_tensor` / `torch.sparse_coo_tensor` keep the result on
    // the input device, and the format-conversion helpers (`.to_sparse_csr()`,
    // `.to_sparse_csc()`, `.to_dense()` on a CSR/CSC/COO tensor) run on
    // cuSPARSE when the data lives on CUDA. ferrotorch routes CSR↔CSC via
    // `cusparseCsr2cscEx2` and COO↔CSR via `cusparseXcoo2csr` /
    // `cusparseXcsr2coo` (host inputs uploaded JIT, dense output stays on
    // device).
    //
    // The CSR-shaped sparse-to-dense path already exists as
    // `sparse_to_dense_csr_f{32,64}` (P3); the CSC variants below are dual
    // paths that take a CSC triplet and materialise the dense matrix on
    // device. Per-component dispatch from `CscTensor::to_dense_on` and
    // `CooTensor::to_dense_on`.
    //
    // See ferrotorch-gpu/src/sparse.rs for the cuSPARSE implementations.

    /// CSC-form sparse → dense materialization on GPU (f32 dtype).
    ///
    /// Inputs:
    /// - `col_ptrs`: `n + 1` host `u32` column pointers in CSC order.
    /// - `row_indices`: `nnz` host `u32` row indices.
    /// - `values`: `nnz` host f32 non-zero values.
    /// - `device_ordinal`: target CUDA ordinal; output buffer lives there.
    /// - `m`, `n`: output dense shape `[m, n]`, row-major.
    ///
    /// Returns a device buffer holding the `[m, n]` row-major dense result.
    fn csc_to_dense_f32(
        &self,
        _col_ptrs: &[u32],
        _row_indices: &[u32],
        _values: &[f32],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "csc_to_dense_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// CSC-form sparse → dense materialization on GPU (f64 dtype).
    /// Companion of [`Self::csc_to_dense_f32`].
    fn csc_to_dense_f64(
        &self,
        _col_ptrs: &[u32],
        _row_indices: &[u32],
        _values: &[f64],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "csc_to_dense_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// CSR → CSC format conversion on GPU (f32 dtype).
    ///
    /// Uses `cusparseCsr2cscEx2`. Returns the CSC triplet
    /// `(col_ptrs, row_indices, values)` in host buffers — ferrotorch's
    /// `CscTensor` is CPU-resident so the host return matches that storage
    /// model. `m`, `n` are the source CSR shape.
    fn csr_to_csc_f32(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f32],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f32>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "csr_to_csc_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// CSR → CSC format conversion on GPU (f64 dtype).
    /// Companion of [`Self::csr_to_csc_f32`].
    fn csr_to_csc_f64(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f64],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f64>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "csr_to_csc_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// COO → CSR format conversion on GPU (f32 dtype).
    ///
    /// Wraps `cusparseXcoo2csr`. Caller supplies row-sorted COO (cuSPARSE
    /// requires it); ferrotorch's `CooTensor` is host-resident so the
    /// caller pre-sorts on the host before invoking. Values are passed
    /// through unchanged (only the row indices are compacted into a
    /// `crow_indices` row-pointer array).
    ///
    /// Returns the host CSR triplet `(crow_indices, col_indices, values)`.
    fn coo_to_csr_f32(
        &self,
        _row_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f32],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f32>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "coo_to_csr_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// COO → CSR format conversion on GPU (f64 dtype).
    /// Companion of [`Self::coo_to_csr_f32`].
    fn coo_to_csr_f64(
        &self,
        _row_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f64],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f64>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "coo_to_csr_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// CSR → COO row-index expansion on GPU (f32 dtype).
    ///
    /// Wraps `cusparseXcsr2coo`. Returns the host COO triplet
    /// `(row_indices, col_indices, values)`. `col_indices` and `values`
    /// pass through unchanged from the source CSR; only the `crow_indices`
    /// row-pointer array is expanded into per-entry `row_indices`.
    fn csr_to_coo_f32(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f32],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f32>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "csr_to_coo_f32 GPU op not implemented for this backend".into(),
        })
    }

    /// CSR → COO row-index expansion on GPU (f64 dtype).
    /// Companion of [`Self::csr_to_coo_f32`].
    fn csr_to_coo_f64(
        &self,
        _crow_indices: &[u32],
        _col_indices: &[u32],
        _values: &[f64],
        _device_ordinal: usize,
        _m: usize,
        _n: usize,
    ) -> FerrotorchResult<(Vec<u32>, Vec<u32>, Vec<f64>)> {
        Err(FerrotorchError::InvalidArgument {
            message: "csr_to_coo_f64 GPU op not implemented for this backend".into(),
        })
    }

    /// Synchronize the current stream on the given device, blocking until
    /// all enqueued operations have completed.
    fn synchronize(&self, _device: usize) -> FerrotorchResult<()> {
        Err(FerrotorchError::DeviceUnavailable)
    }

    /// Return the number of streams in the pool for the given device.
    fn stream_count(&self, _device: usize) -> usize {
        1
    }

    // ---------------------------------------------------------------------
    // FlashAttention forward (P5).
    //
    // Per-component dispatch from `nested_scaled_dot_product_attention`.
    // Computes `softmax(Q @ K^T * scale) @ V` with on-device tiled
    // online-softmax (FlashAttention-2 forward) without materialising the
    // full [seq_q, seq_k] scores matrix.
    //
    // Default impls return `InvalidArgument` so backends without CUDA
    // declare unsupported, and the caller falls through to the GPU
    // composite path (`bmm + softmax_rows + bmm`).
    // ---------------------------------------------------------------------

    /// FlashAttention forward (f32). `query`/`key` are `[seq_q, d]` /
    /// `[seq_k, d]`; `value` is `[seq_k, d_v]`. Returns `[seq_q, d_v]`.
    /// `scale` is typically `1 / sqrt(d)`. Single-head (no batch dim) —
    /// the caller folds batch into per-component dispatch.
    fn flash_attention_forward_f32(
        &self,
        _query: &GpuBufferHandle,
        _key: &GpuBufferHandle,
        _value: &GpuBufferHandle,
        _seq_q: usize,
        _seq_k: usize,
        _d: usize,
        _d_v: usize,
        _scale: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "flash_attention_forward_f32 GPU op not yet implemented".into(),
        })
    }

    /// FlashAttention forward (f64). See [`flash_attention_forward_f32`].
    fn flash_attention_forward_f64(
        &self,
        _query: &GpuBufferHandle,
        _key: &GpuBufferHandle,
        _value: &GpuBufferHandle,
        _seq_q: usize,
        _seq_k: usize,
        _d: usize,
        _d_v: usize,
        _scale: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "flash_attention_forward_f64 GPU op not yet implemented".into(),
        })
    }

    // ---------------------------------------------------------------------
    // P6: 2:4 structured sparse matmul (cuSPARSELt).
    //
    // PyTorch parity (rust-gpu-discipline §3): `torch._C._sparse_semi_
    // structured_apply` (and the `SparseSemiStructuredTensor` user API)
    // dispatches to NVIDIA cuSPARSELt on Ampere+ Tensor Cores when the
    // 2:4 sparse weight is on CUDA. ferrotorch mirrors that by routing
    // `SemiStructuredSparseTensor::sparse_matmul_24` through these
    // hooks.
    //
    // The dense `b_dense_decompressed` operand is the dense
    // representation of the structured 2:4 matrix (mask applied → zeros
    // in non-retained positions). cuSPARSELt repacks it into the
    // Tensor-Core-friendly layout via `cusparseLtSpMMACompress`
    // internally.
    //
    // Default impls return `InvalidArgument` so backends without the
    // `cusparselt` cargo feature declare unsupported and the caller
    // falls through to the existing decompress + dense matmul reference
    // path. This is the §3-correct opt-in mechanism — no silent CPU
    // fallback. See `ferrotorch-gpu/src/cusparselt.rs` for the live
    // implementation under the feature.
    // ---------------------------------------------------------------------

    /// 2:4 structured sparse matmul, FP32 (TF32-Tensor-Core compute).
    /// Computes `[m, n] = a @ b_dense_decompressed` where `b` carries
    /// 2:4 structured zeros along its inner dimension.
    fn sparse_matmul_24_f32(
        &self,
        _a: &GpuBufferHandle,
        _b_dense_decompressed: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sparse_matmul_24_f32 GPU op not implemented for this backend (build with --features cusparselt)".into(),
        })
    }

    /// 2:4 structured sparse matmul, FP16 (FP32 accumulator).
    /// f16 inputs/outputs are passed as raw `u16` buffers (bf16/f16 in
    /// ferrotorch are `u16`-bit-pattern carriers).
    fn sparse_matmul_24_f16(
        &self,
        _a: &GpuBufferHandle,
        _b_dense_decompressed: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sparse_matmul_24_f16 GPU op not implemented for this backend (build with --features cusparselt)".into(),
        })
    }

    /// 2:4 structured sparse matmul, BF16 (FP32 accumulator).
    /// See [`Self::sparse_matmul_24_f16`].
    fn sparse_matmul_24_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b_dense_decompressed: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "sparse_matmul_24_bf16 GPU op not implemented for this backend (build with --features cusparselt)".into(),
        })
    }

    // -- bf16 → bf16 native dispatch (#17) -----------------------------------
    //
    // These trait methods stay in bf16 end-to-end (inputs *and* outputs are
    // `CudaSlice<u16>` bit-pattern handles, matching the storage convention
    // used by every `*_bf16` PTX kernel in `ferrotorch-gpu::bf16` and the
    // `gpu_matmul_bf16_bf16` family in `ferrotorch-gpu::blas`). The earlier
    // `*_bf16_f32` family widens to f32 on the output (PyTorch-autocast
    // parity); these `*_bf16_bf16` variants preserve bf16 storage end-to-end
    // for the ViT / CLIP-style inference pipeline.
    //
    // Default impls return `Unsupported` so non-CUDA backends compile
    // unchanged — there is NO silent CPU fallback (rust-gpu-discipline §3).
    // The CUDA implementation is in `ferrotorch-gpu::backend_impl`.

    /// bf16 fused-transpose matmul `C = A @ B^T`.
    ///
    /// `A: [m, k]`, `B: [n, k]` (row-major; the transpose is folded into
    /// the cuBLAS `transb` flag with no extra memory traffic). Returns a
    /// `[m, n]` bf16 buffer.
    fn matmul_bf16_bf16_nt(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "matmul_bf16_bf16_nt GPU op not implemented for this backend".into(),
        })
    }

    /// Row-wise softmax: bf16 input → bf16 output via PTX kernel with
    /// f32 accumulator (max-find, exp-sum, normalize all in f32; only the
    /// final store rounds back to bf16). The bf16 round-trip is the
    /// HuggingFace bf16 attention contract.
    fn softmax_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "softmax_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 LayerNorm with per-channel γ/β (also bf16).
    /// `input: [rows, cols]`, `gamma: [cols]`, `beta: [cols]`. The per-row
    /// mean and variance reduce in f32; the final scale-shift result rounds
    /// back to bf16 with round-to-nearest-even.
    fn layernorm_bf16_bf16(
        &self,
        _input: &GpuBufferHandle,
        _gamma: &GpuBufferHandle,
        _beta: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "layernorm_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 GELU activation `out = 0.5 * x * (1 + erf(x / sqrt(2)))`,
    /// computed in f32 (Hastings degree-5 erf polynomial; ≤1.5e-7 max abs
    /// error, well below bf16 ULP) and rounded back to bf16. ViT and CLIP
    /// MLP blocks use this exact formulation.
    fn gelu_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "gelu_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 SiLU activation `out = x * sigmoid(x)`, f32 internal, bf16 RNE
    /// store back.
    fn silu_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "silu_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 ReLU activation `out = max(0, x)` (clamp on the bf16 sign bit).
    fn relu_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "relu_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 elementwise add `out = a + b`. f32 internal, bf16 RNE store back.
    fn add_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "add_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 elementwise multiply `out = a * b`. f32 internal, bf16 RNE
    /// store back.
    fn mul_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "mul_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    /// bf16 scalar multiply `out = a * scalar`. Used to fold
    /// `1 / sqrt(head_dim)` into attention scores.
    fn scale_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _scalar: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::InvalidArgument {
            message: "scale_bf16_bf16 GPU op not implemented for this backend".into(),
        })
    }

    // ─── Issue #23: bf16 dispatch-gap closure ──────────────────────────────
    //
    // These trait methods close the dispatcher gap surfaced by
    // forecast-bio/ferrotorch#23. They cover sub / div / neg, broadcast
    // {add, sub, mul, div}, sum / mean (both scalar + axis), and the
    // transcendentals exp / log / tanh / sigmoid. Each has a default
    // `Err(NotImplementedOnCuda)` body so non-CUDA backends (cubecl,
    // mps, xpu) compile untouched; the CUDA backend overrides them in
    // `ferrotorch-gpu::backend_impl`.

    /// bf16 elementwise subtract `out = a - b`. f32 internal, bf16 RNE store back.
    fn sub_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "sub_bf16_bf16",
        })
    }

    /// bf16 elementwise divide `out = a / b`. f32 internal, bf16 RNE store back.
    fn div_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "div_bf16_bf16",
        })
    }

    /// bf16 elementwise negate `out = -a`. Implemented as a sign-bit XOR
    /// on the u16 bit pattern — no f32 round-trip.
    fn neg_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "neg_bf16_bf16",
        })
    }

    /// bf16 broadcast add. `a_shape`, `b_shape` are the original shapes;
    /// `out_shape` is the numpy-style broadcasted output shape.
    fn broadcast_add_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_add_bf16",
        })
    }

    /// bf16 broadcast sub.
    fn broadcast_sub_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_sub_bf16",
        })
    }

    /// bf16 broadcast mul.
    fn broadcast_mul_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_mul_bf16",
        })
    }

    /// bf16 broadcast div.
    fn broadcast_div_bf16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_div_bf16",
        })
    }

    /// bf16 sum-reduce to scalar. PyTorch parity: accumulator is f32, final
    /// store rounds back to bf16 with round-to-nearest-even.
    fn sum_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "sum_bf16_bf16",
        })
    }

    /// bf16 mean-reduce to scalar. Computed via sum_bf16_bf16 / n on-device.
    fn mean_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "mean_bf16_bf16",
        })
    }

    /// bf16 axis-reduce sum. `shape` is the full input shape; `axis` is
    /// the index of the dimension being reduced. Output has the same shape
    /// minus the reduced dim (caller may keepdim if desired). f32
    /// accumulator, bf16 round-back.
    fn sum_axis_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axis: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "sum_axis_bf16_bf16",
        })
    }

    /// bf16 axis-reduce mean. Same shape/axis contract as
    /// [`sum_axis_bf16_bf16`]. f32 accumulator, divides by `shape[axis]`
    /// before bf16 round-back.
    fn mean_axis_bf16_bf16(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axis: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "mean_axis_bf16_bf16",
        })
    }

    /// bf16 elementwise exp. f32 internal via `ex2.approx.f32(x * log2(e))`,
    /// bf16 RNE store back.
    fn exp_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "exp_bf16_bf16",
        })
    }

    /// bf16 elementwise natural log. f32 internal via
    /// `lg2.approx.f32(x) * ln(2)`, bf16 RNE store back.
    fn log_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "log_bf16_bf16",
        })
    }

    /// bf16 elementwise tanh. f32 internal via `(e^(2x) - 1)/(e^(2x) + 1)`,
    /// bf16 RNE store back.
    fn tanh_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "tanh_bf16_bf16",
        })
    }

    /// bf16 elementwise sigmoid `1 / (1 + exp(-x))`. f32 internal, bf16 RNE
    /// store back.
    fn sigmoid_bf16_bf16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "sigmoid_bf16_bf16",
        })
    }

    // ── IEEE float16 (f16) ops — crosslink #1185 Phase 1 ─────────────────────
    //
    // f16 storage is `CudaSlice<u16>` (same width as bf16) but the
    // `GpuBufferHandle` carries `DType::F16`, so `unwrap_buffer_f16` asserts
    // the F16 tag and rejects a BF16-tagged handle (and vice-versa). All math
    // happens in f32 registers per thread (native `cvt.f32.f16` /
    // `cvt.rn.f16.f32`); reductions accumulate in f32 (PyTorch parity). These
    // default bodies return a structured error so non-CUDA backends compile
    // unchanged; `CudaBackendImpl` overrides each one.

    /// f16 elementwise `out = a + b`, f32 compute, f16 RNE store.
    fn add_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "add_f16" })
    }

    /// f16 elementwise `out = a - b`, f32 compute, f16 RNE store.
    fn sub_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "sub_f16" })
    }

    /// f16 elementwise `out = a * b`, f32 compute, f16 RNE store.
    fn mul_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "mul_f16" })
    }

    /// f16 elementwise `out = a / b`, f32 compute, f16 RNE store.
    fn div_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "div_f16" })
    }

    /// f16 elementwise `out = -a`.
    fn neg_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "neg_f16" })
    }

    /// f16 multiply every element by an f32 scalar (`out = a * scale`).
    fn scale_f16(&self, _a: &GpuBufferHandle, _scale: f32) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "scale_f16" })
    }

    /// f16 broadcast add over N-D broadcast shapes.
    fn broadcast_add_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_add_f16",
        })
    }

    /// f16 broadcast sub over N-D broadcast shapes.
    fn broadcast_sub_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_sub_f16",
        })
    }

    /// f16 broadcast mul over N-D broadcast shapes.
    fn broadcast_mul_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_mul_f16",
        })
    }

    /// f16 broadcast div over N-D broadcast shapes.
    fn broadcast_div_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _a_shape: &[usize],
        _b_shape: &[usize],
        _out_shape: &[usize],
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "broadcast_div_f16",
        })
    }

    /// f16 sum-reduce to scalar. f32 accumulator (PyTorch parity).
    fn sum_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "sum_f16" })
    }

    /// f16 mean-reduce to scalar. Computed via `sum_f16 / n` on-device.
    fn mean_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "mean_f16" })
    }

    /// f16 axis sum-reduce. f32 accumulator; collapses `shape[axis]`.
    fn sum_axis_f16(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axis: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "sum_axis_f16" })
    }

    /// f16 axis mean-reduce. f32 accumulator; divides by `shape[axis]`.
    fn mean_axis_f16(
        &self,
        _a: &GpuBufferHandle,
        _shape: &[usize],
        _axis: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "mean_axis_f16",
        })
    }

    /// f16 elementwise `out = exp(a)`. f32 internal, f16 RNE store.
    fn exp_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "exp_f16" })
    }

    /// f16 elementwise `out = ln(a)`. f32 internal, f16 RNE store.
    fn log_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "log_f16" })
    }

    /// f16 elementwise tanh. f32 internal, f16 RNE store.
    fn tanh_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "tanh_f16" })
    }

    /// f16 elementwise sigmoid `1 / (1 + exp(-x))`. f32 internal, f16 RNE store.
    fn sigmoid_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "sigmoid_f16" })
    }

    /// f16 elementwise `out = sqrt(a)`. f32 internal, f16 RNE store.
    fn sqrt_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "sqrt_f16" })
    }

    /// f16 elementwise ReLU `max(0, a)`.
    fn relu_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "relu_f16" })
    }

    /// f16 elementwise SiLU `a * sigmoid(a)`. f32 internal, f16 RNE store.
    fn silu_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "silu_f16" })
    }

    /// f16 elementwise GELU `0.5 * x * (1 + erf(x / sqrt(2)))`. f32 internal.
    fn gelu_f16(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "gelu_f16" })
    }

    /// f16 row-wise softmax over `[rows, cols]`. f32 accumulator, f16 store.
    fn softmax_f16(
        &self,
        _a: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "softmax_f16" })
    }

    /// f16 LayerNorm over `[rows, cols]` with f16 gamma/beta. f32 reductions.
    fn layernorm_f16(
        &self,
        _input: &GpuBufferHandle,
        _gamma: &GpuBufferHandle,
        _beta: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "layernorm_f16",
        })
    }

    /// f16 RMSNorm over `[rows, cols]` with f16 weight. f32 reductions.
    fn rmsnorm_f16(
        &self,
        _input: &GpuBufferHandle,
        _weight: &GpuBufferHandle,
        _rows: usize,
        _cols: usize,
        _eps: f32,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "rmsnorm_f16" })
    }

    /// f16-resident matmul `C = A @ B` (cuBLAS GemmEx, `CUDA_R_16F` operands,
    /// f32 compute). `A: [m, k]`, `B: [k, n]`, `C: [m, n]`.
    fn matmul_f16_f16(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _m: usize,
        _k: usize,
        _n: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "matmul_f16_f16",
        })
    }

    // ── Integer (i32 / i64) ops — crosslink #1185 Phase 2b ───────────────────
    //
    // Runtime dispatch on the ScalarType tag (PyTorch style): ONE trait method
    // per op, which switches on `a.dtype()` internally in the CUDA backend
    // (`DType::I32` → i32 kernel, `DType::I64` → i64 kernel, else structured
    // error). This mirrors PyTorch's dispatcher routing on `ScalarType` rather
    // than minting a separate symbol per (op, width). Native `CudaBuffer<i32>`
    // / `CudaBuffer<i64>` storage — no `CudaSlice<u16>` bit-pattern trick, no
    // f32/f64 detour, no host round-trip. Each default body returns a
    // structured error so non-CUDA backends compile unchanged; `CudaBackendImpl`
    // overrides them in `ferrotorch-gpu::backend_impl`.

    /// Integer elementwise `out = a + b` (i32 / i64, wrapping on overflow).
    /// Dispatches on `a.dtype()`. Inputs must be same width and length.
    fn int_add(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_add" })
    }

    /// Integer elementwise `out = a - b` (i32 / i64, wrapping).
    fn int_sub(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_sub" })
    }

    /// Integer elementwise `out = a * b` (i32 / i64, wrapping).
    fn int_mul(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_mul" })
    }

    /// Integer elementwise negate `out = -a`.
    fn int_neg(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_neg" })
    }

    /// Integer floor division `out = floor_divide(a, b)` (floors toward −∞,
    /// `torch.floor_divide` semantics — NOT C truncation).
    fn int_floor_div(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "int_floor_div",
        })
    }

    /// Integer remainder `out = remainder(a, b)` (sign of the DIVISOR,
    /// `torch.remainder` / Python semantics — NOT C `%`).
    fn int_remainder(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "int_remainder",
        })
    }

    /// Integer elementwise bitwise AND.
    fn int_bitand(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_bitand" })
    }

    /// Integer elementwise bitwise OR.
    fn int_bitor(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_bitor" })
    }

    /// Integer elementwise bitwise XOR.
    fn int_bitxor(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_bitxor" })
    }

    /// Integer elementwise bitwise NOT `out = !a`.
    fn int_bitnot(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_bitnot" })
    }

    /// Integer elementwise left shift `out = a << b`.
    fn int_shl(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_shl" })
    }

    /// Integer elementwise arithmetic right shift `out = a >> b`
    /// (sign-extending, matching PyTorch `__rshift__` on signed dtypes).
    fn int_shr(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_shr" })
    }

    /// Integer sum-reduce to a 1-element buffer (same width accumulator,
    /// wrapping — PyTorch does NOT upcast integer `sum`).
    fn int_sum(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_sum" })
    }

    /// Integer product-reduce to a 1-element buffer (same width, wrapping).
    fn int_prod(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_prod" })
    }

    /// Integer min-reduce to a 1-element buffer.
    fn int_min(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_min" })
    }

    /// Integer max-reduce to a 1-element buffer.
    fn int_max(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "int_max" })
    }

    // ── argmax / argmin / gather / cast — crosslink #1185 Phase 2c ───────────
    //
    // Cross-world integer ops that unblock the GPU-resident token/sampling path
    // (Llama generation loop). All dispatch on the relevant `DType` tag(s)
    // internally; the result stays GPU-resident. Default bodies return a
    // structured error so non-CUDA backends compile (PyTorch parity §3).

    /// Argmax over a value buffer (any float/int `DType`), returning an
    /// **I64-tagged** index handle (PyTorch returns int64 indices).
    ///
    /// Logical layout `[outer, dim_size, inner]` (contiguous, C-order). Global
    /// reduction = `outer=1, inner=1, dim_size=numel`; along-dim = the obvious
    /// factorisation. Tie-break is the FIRST occurrence. The output handle has
    /// `outer * inner` elements. Dispatches on `src.dtype()` for the value type.
    fn argmax(
        &self,
        _src: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "argmax" })
    }

    /// Argmin over a value buffer; see [`Self::argmax`]. Returns an I64 handle.
    fn argmin(
        &self,
        _src: &GpuBufferHandle,
        _outer: usize,
        _dim_size: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "argmin" })
    }

    /// On-device `searchsorted` / `bucketize` over a sorted 1-D `boundaries`
    /// buffer (#1545). For each element of `values`, returns the insertion
    /// index into `boundaries`:
    ///
    /// - `right == false` (PyTorch `side="left"`): first `i` with
    ///   `boundaries[i] >= v` (lower_bound).
    /// - `right == true` (PyTorch `side="right"`): first `i` with
    ///   `boundaries[i] > v` (upper_bound).
    ///
    /// Both `values` and `boundaries` are GPU-resident value buffers of the
    /// same `DType` (∈ {F32, F64}); the result is an `I64`-tagged handle of
    /// `values.len()` indices (PyTorch returns `ScalarType::Long`). Mirrors
    /// `searchsorted_cuda_kernel` (`is_1d_boundaries == true`) in
    /// `aten/src/ATen/native/cuda/Bucketization.cu`. The default impl errors;
    /// the CUDA backend overrides it with the `gpu_searchsorted_*` PTX kernel.
    fn searchsorted_1d(
        &self,
        _values: &GpuBufferHandle,
        _boundaries: &GpuBufferHandle,
        _right: bool,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "searchsorted_1d",
        })
    }

    /// On-device `topk` over a GPU-resident `[outer, last_dim]` value buffer
    /// (#1545). Selects the `k` extrema along the last dim for every one of the
    /// `outer` slices, returning `(values, indices)`:
    ///
    /// - `values` — a `GpuBufferHandle` of `outer * k` elements with the SAME
    ///   `DType` as `values_in` (∈ {F32, F64}), in sorted order.
    /// - `indices` — an `I64`-tagged `GpuBufferHandle` of `outer * k` original
    ///   indices into `[0, last_dim)` (PyTorch returns `ScalarType::Long`).
    ///
    /// `largest == true` → descending value order; else ascending. Ties are
    /// broken by ascending original index, which is a valid `torch.topk`
    /// result (upstream `topk_out_cuda` gathers then sorts the top-k with
    /// `stable=false`, leaving the per-tie index order unspecified) and matches
    /// the CPU `ops::search::topk` path bit-for-bit. Mirrors
    /// `topk_out_cuda` in `aten/src/ATen/native/cuda/TensorTopK.cpp` for the
    /// last-dim, sorted case. The default impl errors; the CUDA backend
    /// overrides it with the `gpu_topk_*` PTX kernel.
    fn topk_1d(
        &self,
        _values_in: &GpuBufferHandle,
        _outer: usize,
        _last_dim: usize,
        _k: usize,
        _largest: bool,
    ) -> FerrotorchResult<(GpuBufferHandle, GpuBufferHandle)> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "topk_1d" })
    }

    /// On-device `histc` over a GPU-resident value buffer (#1545). Counts the
    /// `input` elements falling in each of `bins` equal-width bins spanning the
    /// inclusive range `[min_val, max_val]`, returning a value handle of `bins`
    /// counts with the SAME `DType` as `input` (∈ {F32, F64}) — PyTorch's
    /// `_histc_cuda` allocates the output with `self.scalar_type()`.
    ///
    /// Bin semantics mirror `getBin` + `kernelHistogram1D` in
    /// `aten/src/ATen/native/cuda/SummaryOps.cu`: `bin = (int)((v - min) *
    /// bins / (max - min))`, the last bin is closed at both ends (a value `==
    /// max` lands in `bins-1`), and values outside `[min, max]` (and NaN) are
    /// not counted. The caller guarantees `bins > 0` and `min_val < max_val`.
    /// The default impl errors; the CUDA backend overrides it with the
    /// `gpu_histc_*` PTX kernel.
    fn histc_1d(
        &self,
        _input: &GpuBufferHandle,
        _bins: usize,
        _min_val: f64,
        _max_val: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "histc_1d" })
    }

    /// On-device `meshgrid` grid for ONE axis over a GPU-resident 1-D
    /// coordinate buffer (#1545, `indexing='ij'`). `input` is the axis's
    /// coordinate vector (length `axis_len`); the result is a value handle of
    /// `total` elements with the same `DType` as `input` (∈ {F32, F64}) where
    /// `out[flat] = input[(flat / inner) % axis_len]`, `inner =
    /// product(shapes[axis+1..])`, `total = product(shapes)`.
    ///
    /// This is the `view(view_shape).expand(shape)` decomposition that upstream
    /// `meshgrid` uses (`aten/src/ATen/native/TensorShape.cpp:4462-4467`) lowered
    /// to a single gather — no intermediate strided `expand` is materialised.
    /// The default impl errors; the CUDA backend overrides it with the
    /// `gpu_meshgrid_*` PTX kernel.
    fn meshgrid_grid(
        &self,
        _input: &GpuBufferHandle,
        _total: usize,
        _inner: usize,
        _axis_len: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "meshgrid_grid",
        })
    }

    /// On-device `unique_consecutive` over a GPU-resident 1-D value buffer
    /// (#1545). Collapses each maximal RUN of equal ADJACENT elements into a
    /// single output element, returning `(values, inverse, counts)`:
    ///
    /// - `values` — a value handle of `out_len` run-start values with the SAME
    ///   `DType` as `input` (∈ {F32, F64}); the deduplicated output stays
    ///   GPU-resident. `out_len` is DATA-DEPENDENT (the number of runs).
    /// - `inverse` — host `Vec<usize>` of length `n`: each input element's
    ///   index in `values` (`return_inverse=True`).
    /// - `counts` — host `Vec<usize>` of length `out_len`: the length of each
    ///   run (`return_counts=True`).
    ///
    /// Run detection uses value inequality of adjacent elements, so NaN starts
    /// its own run (`NaN != NaN`), matching the CPU `ops::search`
    /// `unique_consecutive` (`data[i] == data[i-1]`, PartialEq) bit-for-bit.
    /// The compaction runs entirely on-device (run-flag → prefix-sum →
    /// scatter); only the derived run-position metadata is read back to build
    /// `inverse` / `counts` (host `Vec<usize>` by the CPU signature) — the
    /// VALUE data never leaves the device (no R-CODE-4 round trip). The default
    /// impl errors; the CUDA backend overrides it with the
    /// `gpu_unique_consecutive_*` kernels.
    fn unique_consecutive_1d(
        &self,
        _input: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, Vec<usize>, Vec<usize>)> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "unique_consecutive_1d",
        })
    }

    /// On-device `torch.unique(sorted=True, return_inverse=True,
    /// return_counts=True)` over a GPU-resident 1-D value buffer (#1545).
    /// Returns the SORTED-ascending DISTINCT elements plus inverse + counts:
    ///
    /// - `values` — a value handle of `out_len` sorted unique elements with the
    ///   SAME `DType` as `input` (∈ {F32, F64}); the deduplicated output stays
    ///   GPU-resident. `out_len` is DATA-DEPENDENT (the number of distinct
    ///   values). NaN entries sort to the end, each NaN a DISTINCT unique.
    /// - `inverse` — host `Vec<usize>` of length `n`: each input element's index
    ///   into `values` (`return_inverse=True`).
    /// - `counts` — host `Vec<usize>` of length `out_len`: each unique's
    ///   frequency (`return_counts=True`).
    ///
    /// Unlike [`Self::unique_consecutive_1d`] (which collapses only ADJACENT
    /// runs), this first SORTS the values (carrying their original indices) so
    /// that ALL occurrences of a value collapse — mirroring `compute_unique` in
    /// `aten/src/ATen/native/cuda/Unique.cu` (sort-by-key → adjacent-difference
    /// inverse scan → run-length counts). The CUDA `unique` always sorts (no
    /// device hashtable in thrust). The compaction/dedup runs on-device; only
    /// the derived index/run metadata is read back to build `inverse` / `counts`
    /// (host `Vec<usize>` by the CPU signature) — the VALUE data never leaves
    /// the device (no R-CODE-4 round trip). The default impl errors; the CUDA
    /// backend overrides it with the `gpu_unique_*` kernels.
    fn unique_1d(
        &self,
        _input: &GpuBufferHandle,
        _n: usize,
    ) -> FerrotorchResult<(GpuBufferHandle, Vec<usize>, Vec<usize>)> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "unique_1d" })
    }

    /// `index_select(dim)` driven by a GPU-resident integer index handle.
    ///
    /// `src` is the value buffer (layout `[outer, in_dim, inner]`); `index` is
    /// an I32/I64-tagged handle of `out_dim` entries. Output is a value handle
    /// of `outer * out_dim * inner` elements with the same `DType` as `src`.
    /// Dispatches on `(src.dtype(), index.dtype())`.
    #[allow(clippy::too_many_arguments)]
    fn index_select_intidx(
        &self,
        _src: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _outer: usize,
        _in_dim: usize,
        _out_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "index_select_intidx",
        })
    }

    /// `gather(dim)` driven by a GPU-resident integer index handle.
    ///
    /// `src` layout `[outer, in_dim, inner]`; `index` (I32/I64) AND output both
    /// have layout `[outer, out_dim, inner]` (the index is parallel to the
    /// output). Output `DType` matches `src`. Dispatches on
    /// `(src.dtype(), index.dtype())`.
    #[allow(clippy::too_many_arguments)]
    fn gather_intidx(
        &self,
        _src: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _outer: usize,
        _in_dim: usize,
        _out_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "gather_intidx",
        })
    }

    // -- dim-aware gather / scatter family (#1545 / sub #1535) ----------------
    //
    // These are the `ops::indexing` dim-parameterised, full-rank-index ops
    // (`torch.gather` / `Tensor.scatter_` / `scatter_(value)` /
    // `scatter_add_`). The `[outer, axis, inner]` decomposition follows the
    // upstream `aten/src/ATen/native/cuda/ScatterGatherKernel.cu` per-dim
    // stride indexing. `index` is a GPU-resident `i64` handle (PyTorch index
    // tensors are int64). The CUDA backend overrides these with real PTX
    // kernels (`ferrotorch-gpu/src/scatter_gather_kernels.rs`); other backends
    // inherit the `NotImplementedOnCuda` default.

    /// f32 dim-aware `gather`: `input` `[outer, in_dim, inner]`, `index` (I64)
    /// AND output both `[outer, out_dim, inner]`. Returns a fresh resident
    /// buffer of `outer*out_dim*inner` f32 elements.
    #[allow(clippy::too_many_arguments)]
    fn gather_dim_f32(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _outer: usize,
        _in_dim: usize,
        _out_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "gather_dim_f32",
        })
    }

    /// f64 dim-aware `gather`. Companion of [`Self::gather_dim_f32`].
    #[allow(clippy::too_many_arguments)]
    fn gather_dim_f64(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _outer: usize,
        _in_dim: usize,
        _out_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "gather_dim_f64",
        })
    }

    /// f32 dim-aware `scatter`: clones `input` (`[outer, out_dim, inner]`) and
    /// writes `out[.., index[t].., ..] = src[t]` where `index`/`src` are
    /// `[outer, idx_dim, inner]`. Returns a fresh resident buffer.
    #[allow(clippy::too_many_arguments)]
    fn scatter_dim_f32(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _src: &GpuBufferHandle,
        _outer: usize,
        _out_dim: usize,
        _idx_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_dim_f32",
        })
    }

    /// f64 dim-aware `scatter`. Companion of [`Self::scatter_dim_f32`].
    #[allow(clippy::too_many_arguments)]
    fn scatter_dim_f64(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _src: &GpuBufferHandle,
        _outer: usize,
        _out_dim: usize,
        _idx_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_dim_f64",
        })
    }

    /// f32 dim-aware `scatter_value`: clones `input` (`[outer, out_dim,
    /// inner]`) and writes the broadcast scalar `value` at every position named
    /// by `index` (`[outer, idx_dim, inner]`).
    #[allow(clippy::too_many_arguments)]
    fn scatter_value_dim_f32(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _value: f32,
        _outer: usize,
        _out_dim: usize,
        _idx_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_value_dim_f32",
        })
    }

    /// f64 dim-aware `scatter_value`. Companion of
    /// [`Self::scatter_value_dim_f32`].
    #[allow(clippy::too_many_arguments)]
    fn scatter_value_dim_f64(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _value: f64,
        _outer: usize,
        _out_dim: usize,
        _idx_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_value_dim_f64",
        })
    }

    /// f32 dim-aware `scatter_add`: like [`Self::scatter_dim_f32`] but
    /// accumulates (`out[dst] += src[t]`) via an atomic add, so duplicate index
    /// values targeting the same `dst` sum correctly.
    #[allow(clippy::too_many_arguments)]
    fn scatter_add_dim_f32(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _src: &GpuBufferHandle,
        _outer: usize,
        _out_dim: usize,
        _idx_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_add_dim_f32",
        })
    }

    /// f64 dim-aware `scatter_add`. Companion of
    /// [`Self::scatter_add_dim_f32`]; uses an `sm_60+` f64 atomic add.
    #[allow(clippy::too_many_arguments)]
    fn scatter_add_dim_f64(
        &self,
        _input: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _src: &GpuBufferHandle,
        _outer: usize,
        _out_dim: usize,
        _idx_dim: usize,
        _inner: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_add_dim_f64",
        })
    }

    /// f32 segmented row-scatter-add (GNN message passing —
    /// `ops::scatter::scatter_add_segments`). `src` is `[e, d]`; `index` is a
    /// resident `i64` per-ROW segment id (length `e`); the result is a fresh
    /// zero-initialised `[dim_size, d]` buffer with
    /// `out[index[row], :] += src[row, :]` accumulated atomically over all
    /// rows. Duplicate segment ids sum; rows with no contributing edge stay 0.
    fn scatter_add_segments_f32(
        &self,
        _src: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _e: usize,
        _d: usize,
        _dim_size: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_add_segments_f32",
        })
    }

    /// f64 segmented row-scatter-add. Companion of
    /// [`Self::scatter_add_segments_f32`]; uses an `sm_60+` f64 atomic add.
    fn scatter_add_segments_f64(
        &self,
        _src: &GpuBufferHandle,
        _index: &GpuBufferHandle,
        _e: usize,
        _d: usize,
        _dim_size: usize,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "scatter_add_segments_f64",
        })
    }

    /// Cast a float buffer (`src.dtype()` ∈ {F32,F64,BF16,F16}) to an integer
    /// buffer tagged `dst` (∈ {I32,I64}), truncating toward zero (PyTorch
    /// `.to(int)`). Result stays GPU-resident.
    fn cast_f_to_i(
        &self,
        _src: &GpuBufferHandle,
        _dst: DType,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "cast_f_to_i" })
    }

    /// Cast an integer buffer (`src.dtype()` ∈ {I32,I64}) to a float buffer
    /// tagged `dst` (∈ {F32,F64,BF16,F16}), round-to-nearest-even.
    fn cast_i_to_f(
        &self,
        _src: &GpuBufferHandle,
        _dst: DType,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "cast_i_to_f" })
    }

    /// Cast an integer buffer between i32 and i64 (`src.dtype()` and `dst`
    /// each ∈ {I32,I64}). Widen sign-extends; narrow wraps (PyTorch CUDA
    /// `.to(int)` semantics).
    fn cast_i_to_i(
        &self,
        _src: &GpuBufferHandle,
        _dst: DType,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "cast_i_to_i" })
    }

    // ── Boolean / comparison ops — crosslink #1185 Phase 3b ──────────────────
    //
    // Comparisons read a VALUE buffer (`a.dtype()` ∈ {F32,F64,BF16,F16,I32,I64})
    // and produce a `DType::Bool`-tagged output (u8, 0/1) — PyTorch parity: the
    // comparison result dtype is always `bool`. Logical ops read and write Bool
    // (u8) buffers. Reductions any/all fold a Bool buffer to a 1-element Bool
    // buffer. All dispatch on the relevant `DType` tag internally in the CUDA
    // backend; results stay GPU-resident (no host round-trip). Default bodies
    // return a structured error so non-CUDA backends compile (PyTorch parity §3).

    /// Elementwise comparison `out[i] = (a[i] OP b[i]) ? 1u8 : 0u8`.
    ///
    /// Reads the value dtype from `a.dtype()` to pick the kernel; `a` and `b`
    /// must carry the same dtype and length. The returned handle is tagged
    /// `DType::Bool` (u8 storage). `op` selects the operator.
    fn compare(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
        _op: CompareOp,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "compare" })
    }

    /// Elementwise logical AND of two Bool (u8) buffers → Bool (u8).
    fn bool_and(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "bool_and" })
    }

    /// Elementwise logical OR of two Bool (u8) buffers → Bool (u8).
    fn bool_or(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "bool_or" })
    }

    /// Elementwise logical XOR of two Bool (u8) buffers → Bool (u8).
    fn bool_xor(
        &self,
        _a: &GpuBufferHandle,
        _b: &GpuBufferHandle,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "bool_xor" })
    }

    /// Elementwise logical NOT of a Bool (u8) buffer → Bool (u8).
    fn bool_not(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "bool_not" })
    }

    /// Global OR-reduction (`torch.any`) of a Bool (u8) buffer → 1-element
    /// Bool (u8) buffer holding 1 if any element is nonzero, else 0.
    fn bool_any(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "bool_any" })
    }

    /// Global AND-reduction (`torch.all`) of a Bool (u8) buffer → 1-element
    /// Bool (u8) buffer holding 1 if all elements are nonzero, else 0.
    fn bool_all(&self, _a: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda { op: "bool_all" })
    }

    /// Cast a Bool (u8) buffer to a float buffer tagged `dst`
    /// (∈ {F32,F64,BF16,F16}): `true → 1.0`, `false → 0.0`. Result stays
    /// GPU-resident.
    fn cast_bool_to_f(
        &self,
        _src: &GpuBufferHandle,
        _dst: DType,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "cast_bool_to_f",
        })
    }

    // ── #1545 / #1534: predicate masks for masked-tensor constructors ────────
    //
    // `MaskedTensor`'s mask is a host `Vec<bool>` by design. These methods
    // compute the boolean predicate ON-DEVICE from the (CUDA-resident) data
    // buffer, returning a `DType::Bool` (u8 0/1) handle. The core
    // `masked_invalid` / `masked_equal` constructors then read that mask back
    // ONCE to populate the host `Vec<bool>` — a one-way readback of the
    // freshly-computed predicate, not a CPU↔GPU round trip of the value data
    // (which never leaves and returns to the device). Dispatched on
    // `input.dtype()`; covers F32/F64 (the dtypes `MaskedTensor<T: Float>`
    // currently lowers to GPU). Default bodies return a structured error so
    // non-CUDA backends compile.

    /// `isfinite` mask: `out[i] = (v==v) && (|v| != +inf)` as a `DType::Bool`
    /// (u8 0/1) buffer. PyTorch parity with `at::isfinite`
    /// (`aten/src/ATen/native/TensorCompare.cpp:484` —
    /// `(self == self) * (self.abs() != inf)`). Consumer:
    /// `ferrotorch_core::masked_invalid` GPU branch.
    fn isfinite_mask(&self, _input: &GpuBufferHandle) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "isfinite_mask",
        })
    }

    /// `ne_scalar` mask: `out[i] = (v != value)` as a `DType::Bool` (u8 0/1)
    /// buffer (`value` passed as f64, narrowed to the input dtype). This is the
    /// VALID mask for `numpy.ma.masked_equal` under the torch convention.
    /// Consumer: `ferrotorch_core::masked_equal` GPU branch.
    fn ne_scalar_mask(
        &self,
        _input: &GpuBufferHandle,
        _value: f64,
    ) -> FerrotorchResult<GpuBufferHandle> {
        Err(FerrotorchError::NotImplementedOnCuda {
            op: "ne_scalar_mask",
        })
    }
}

static GPU_BACKEND: OnceLock<Box<dyn GpuBackend>> = OnceLock::new();

/// Register a GPU backend. Called once by the GPU crate on init.
pub fn register_gpu_backend(backend: Box<dyn GpuBackend>) -> Result<(), Box<dyn GpuBackend>> {
    GPU_BACKEND.set(backend)
}

/// Get the registered GPU backend, if any.
pub fn gpu_backend() -> Option<&'static dyn GpuBackend> {
    GPU_BACKEND.get().map(|b| b.as_ref())
}

/// Returns `true` if a GPU backend has been registered.
pub fn has_gpu_backend() -> bool {
    GPU_BACKEND.get().is_some()
}

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

    #[test]
    fn test_gpu_buffer_handle() {
        // Inner type is arbitrary here (this exercises the type-erasure
        // mechanics, not dtype dispatch); tag with F32 as a placeholder.
        let handle = GpuBufferHandle::new(Box::new(42u64), 0, 100, DType::F32);
        assert_eq!(handle.device_ordinal(), 0);
        assert_eq!(handle.len(), 100);
        assert!(!handle.is_empty());
        assert_eq!(handle.downcast_ref::<u64>(), Some(&42));
        assert_eq!(handle.dtype(), DType::F32);
    }

    #[test]
    fn test_gpu_buffer_handle_debug() {
        let handle = GpuBufferHandle::new(Box::new(()), 1, 50, DType::F64);
        let s = format!("{handle:?}");
        assert!(s.contains("device: 1"));
        // The Debug impl now surfaces the dtype tag.
        assert!(s.contains("dtype"));
    }
}