tenferro-tensor 0.3.0

Dense runtime tensors, views, backend traits, and backend-independent contracts for tenferro.
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
use crate::config::{
    CompareDir, DotGeneralConfig, GatherConfig, PadConfig, ScatterConfig, SliceConfig,
};
use crate::types::{
    TensorRank, TensorScalar, TensorView, TensorViewMut, TypedTensor, TypedTensorView,
    TypedTensorViewMut,
};
use crate::validate::validate_convert_dtype;
use crate::{
    AllocationDomainId, AllocationId, DType, Error, RuntimeCacheControl, ShapeMismatch, Tensor,
    TensorRead, TensorValue, TensorWrite, ValidationError,
};
use num_complex::{Complex32, Complex64};
use smallvec::SmallVec;
use std::any::TypeId;
use std::ptr::NonNull;
use strided_kernel::{
    erased_map_into, erased_zip_into, ErasedMapOp, ErasedRawStridedMut, ErasedRawStridedPtr,
    ErasedZipOp, ExecContext, KernelDType,
};

#[cfg(test)]
mod tests;

fn read_boundary_error(op: &'static str) -> crate::Error {
    crate::Error::unsupported(
        op,
        "backend does not accept borrowed tensor views at this execution boundary",
    )
}

fn validation(op: &'static str, source: ValidationError) -> crate::Error {
    Error::validation(op, source)
}

fn invalid_argument(op: &'static str, argument: &'static str, message: impl Into<String>) -> Error {
    Error::invalid_argument(op, argument, message)
}

fn read_tensor<'a>(op: &'static str, input: TensorRead<'a>) -> crate::Result<&'a Tensor> {
    input.as_tensor().ok_or_else(|| read_boundary_error(op))
}

fn validate_axis_list(
    op: &'static str,
    role: &'static str,
    axes: &[usize],
    rank: usize,
) -> crate::Result<()> {
    let mut seen = vec![false; rank];
    for &axis in axes {
        if axis >= rank {
            return Err(validation(
                op,
                ValidationError::AxisOutOfBounds { axis, rank },
            ));
        }
        if seen[axis] {
            return Err(validation(
                op,
                ValidationError::DuplicateAxis { axis, role },
            ));
        }
        seen[axis] = true;
    }
    Ok(())
}

fn validate_role_disjoint(
    op: &'static str,
    first_role: &'static str,
    first_axes: &[usize],
    second_role: &'static str,
    second_axes: &[usize],
) -> crate::Result<()> {
    for &axis in first_axes {
        if second_axes.contains(&axis) {
            return Err(validation(
                op,
                ValidationError::AxisRoleConflict {
                    axis,
                    first_role,
                    second_role,
                },
            ));
        }
    }
    Ok(())
}

/// Infer the output shape for a validated dot-general operation.
#[doc(hidden)]
pub fn dot_general_output_shape(
    lhs_shape: &[usize],
    rhs_shape: &[usize],
    config: &DotGeneralConfig,
    op: &'static str,
) -> crate::Result<Vec<usize>> {
    if config.lhs_contracting_dims.len() != config.rhs_contracting_dims.len() {
        return Err(invalid_argument(
            op,
            "contracting_dims",
            "lhs/rhs contracting dim counts differ",
        ));
    }
    if config.lhs_batch_dims.len() != config.rhs_batch_dims.len() {
        return Err(invalid_argument(
            op,
            "batch_dims",
            "lhs/rhs batch dim counts differ",
        ));
    }

    let lhs_rank = lhs_shape.len();
    let rhs_rank = rhs_shape.len();
    validate_axis_list(
        op,
        "lhs_contracting",
        &config.lhs_contracting_dims,
        lhs_rank,
    )?;
    validate_axis_list(
        op,
        "rhs_contracting",
        &config.rhs_contracting_dims,
        rhs_rank,
    )?;
    validate_axis_list(op, "lhs_batch", &config.lhs_batch_dims, lhs_rank)?;
    validate_axis_list(op, "rhs_batch", &config.rhs_batch_dims, rhs_rank)?;
    validate_role_disjoint(
        op,
        "lhs_contracting",
        &config.lhs_contracting_dims,
        "lhs_batch",
        &config.lhs_batch_dims,
    )?;
    validate_role_disjoint(
        op,
        "rhs_contracting",
        &config.rhs_contracting_dims,
        "rhs_batch",
        &config.rhs_batch_dims,
    )?;

    for (&lhs_axis, &rhs_axis) in config
        .lhs_contracting_dims
        .iter()
        .zip(&config.rhs_contracting_dims)
    {
        if lhs_shape[lhs_axis] != rhs_shape[rhs_axis] {
            return Err(validation(
                op,
                ShapeMismatch::ContractedDimensions {
                    lhs_axis,
                    lhs_size: lhs_shape[lhs_axis],
                    rhs_axis,
                    rhs_size: rhs_shape[rhs_axis],
                }
                .into(),
            ));
        }
    }
    for (&lhs_axis, &rhs_axis) in config.lhs_batch_dims.iter().zip(&config.rhs_batch_dims) {
        if lhs_shape[lhs_axis] != rhs_shape[rhs_axis] {
            return Err(validation(
                op,
                ShapeMismatch::ContractedDimensions {
                    lhs_axis,
                    lhs_size: lhs_shape[lhs_axis],
                    rhs_axis,
                    rhs_size: rhs_shape[rhs_axis],
                }
                .into(),
            ));
        }
    }

    let lhs_free = (0..lhs_rank)
        .filter(|axis| {
            !config.lhs_contracting_dims.contains(axis) && !config.lhs_batch_dims.contains(axis)
        })
        .map(|axis| lhs_shape[axis]);
    let rhs_free = (0..rhs_rank)
        .filter(|axis| {
            !config.rhs_contracting_dims.contains(axis) && !config.rhs_batch_dims.contains(axis)
        })
        .map(|axis| rhs_shape[axis]);
    let batch = config.lhs_batch_dims.iter().map(|&axis| lhs_shape[axis]);

    Ok(lhs_free.chain(rhs_free).chain(batch).collect())
}

/// Validate output dtype and shape for dot-general read-into dispatch.
#[doc(hidden)]
pub fn validate_dot_general_read_into(
    lhs: &TensorRead<'_>,
    rhs: &TensorRead<'_>,
    config: &DotGeneralConfig,
    out: &TensorWrite<'_>,
    op: &'static str,
) -> crate::Result<Vec<usize>> {
    if lhs.dtype() != rhs.dtype() {
        return Err(validation(
            op,
            ValidationError::DTypeMismatch {
                expected: crate::core_dtype(lhs.dtype()),
                actual: crate::core_dtype(rhs.dtype()),
            },
        ));
    }
    if lhs.dtype() != out.dtype() {
        return Err(validation(
            op,
            ValidationError::DTypeMismatch {
                expected: crate::core_dtype(lhs.dtype()),
                actual: crate::core_dtype(out.dtype()),
            },
        ));
    }
    let expected = dot_general_output_shape(lhs.shape(), rhs.shape(), config, op)?;
    if out.shape() != expected.as_slice() {
        return Err(validation(
            op,
            ShapeMismatch::ExpectedActual {
                expected: expected.clone().into(),
                actual: out.shape().to_vec().into(),
            }
            .into(),
        ));
    }
    Ok(expected)
}

/// Scalar coefficient accepted by contraction accumulation backends.
///
/// `ContractionScalar` is intentionally narrower than [`crate::TensorScalar`]:
/// dot-general accumulation is only defined for floating and complex tensor
/// dtypes.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::{ContractionScalar, DType};
///
/// let alpha = ContractionScalar::F64(2.0);
/// assert_eq!(alpha.dtype(), DType::F64);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ContractionScalar {
    F32(f32),
    F64(f64),
    C32(Complex32),
    C64(Complex64),
}

impl ContractionScalar {
    /// Return this scalar's tensor dtype.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{ContractionScalar, DType};
    ///
    /// assert_eq!(ContractionScalar::F32(1.0).dtype(), DType::F32);
    /// ```
    pub fn dtype(self) -> DType {
        match self {
            Self::F32(_) => DType::F32,
            Self::F64(_) => DType::F64,
            Self::C32(_) => DType::C32,
            Self::C64(_) => DType::C64,
        }
    }

    /// Return the multiplicative identity for a supported contraction dtype.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{ContractionScalar, DType};
    ///
    /// assert_eq!(ContractionScalar::one(DType::F64).unwrap(), ContractionScalar::F64(1.0));
    /// assert!(ContractionScalar::one(DType::I32).is_err());
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a
    /// [`crate::ValidationError::DTypeMismatch`] source when `dtype` is `I32`,
    /// `I64`, or `Bool`, which do not support contraction scalar identities.
    pub fn one(dtype: DType) -> crate::Result<Self> {
        match dtype {
            DType::F32 => Ok(Self::F32(1.0)),
            DType::F64 => Ok(Self::F64(1.0)),
            DType::C32 => Ok(Self::C32(Complex32::new(1.0, 0.0))),
            DType::C64 => Ok(Self::C64(Complex64::new(1.0, 0.0))),
            DType::I32 | DType::I64 | DType::Bool => Err(validation(
                "ContractionScalar::one",
                ValidationError::DTypeMismatch {
                    expected: crate::core_dtype(dtype),
                    actual: crate::core_dtype(DType::F32),
                },
            )),
        }
    }

    /// Return the additive identity for a supported contraction dtype.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{ContractionScalar, DType};
    ///
    /// assert_eq!(ContractionScalar::zero(DType::F64).unwrap(), ContractionScalar::F64(0.0));
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a
    /// [`crate::ValidationError::DTypeMismatch`] source when `dtype` is `I32`,
    /// `I64`, or `Bool`, which do not support contraction scalar identities.
    pub fn zero(dtype: DType) -> crate::Result<Self> {
        match dtype {
            DType::F32 => Ok(Self::F32(0.0)),
            DType::F64 => Ok(Self::F64(0.0)),
            DType::C32 => Ok(Self::C32(Complex32::new(0.0, 0.0))),
            DType::C64 => Ok(Self::C64(Complex64::new(0.0, 0.0))),
            DType::I32 | DType::I64 | DType::Bool => Err(validation(
                "ContractionScalar::zero",
                ValidationError::DTypeMismatch {
                    expected: crate::core_dtype(dtype),
                    actual: crate::core_dtype(DType::F32),
                },
            )),
        }
    }
}

/// Output-update semantics for dot-general accumulation.
///
/// This keeps contraction axes in [`DotGeneralConfig`] and output update
/// semantics here, so cached and non-cached backend traits can share the same
/// accumulation contract.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::{ContractionScalar, DotGeneralAccumulation, DType};
///
/// let accum = DotGeneralAccumulation::overwrite(DType::F64).unwrap();
/// assert_eq!(accum.alpha, ContractionScalar::F64(1.0));
/// assert_eq!(accum.beta, ContractionScalar::F64(0.0));
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DotGeneralAccumulation {
    pub lhs_conj: bool,
    pub rhs_conj: bool,
    pub alpha: ContractionScalar,
    pub beta: ContractionScalar,
}

/// One matrix multiply in a grouped GEMM over shared flat buffers.
///
/// Offsets are element offsets into the corresponding shared lhs, rhs, and
/// output buffers. Each job computes a column-major `rows x cols` output block
/// from a column-major `rows x contracted` lhs block and a column-major
/// `contracted x cols` rhs block.
///
/// Provider implementations receive these descriptors through the public
/// grouped-GEMM request accessor. The engine validates ranges and pairwise
/// output disjointness before provider entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GroupedGemmJob {
    out_offset: usize,
    lhs_offset: usize,
    rhs_offset: usize,
    rows: usize,
    contracted: usize,
    cols: usize,
}

impl GroupedGemmJob {
    /// Construct a column-major grouped-GEMM job over shared flat buffers.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        out_offset: usize,
        lhs_offset: usize,
        rhs_offset: usize,
        rows: usize,
        contracted: usize,
        cols: usize,
    ) -> Self {
        Self {
            out_offset,
            lhs_offset,
            rhs_offset,
            rows,
            contracted,
            cols,
        }
    }

    /// Return the output element offset.
    pub fn out_offset(&self) -> usize {
        self.out_offset
    }

    /// Return the left-input element offset.
    pub fn lhs_offset(&self) -> usize {
        self.lhs_offset
    }

    /// Return the right-input element offset.
    pub fn rhs_offset(&self) -> usize {
        self.rhs_offset
    }

    /// Return the output row count.
    pub fn rows(&self) -> usize {
        self.rows
    }

    /// Return the contracted dimension.
    pub fn contracted(&self) -> usize {
        self.contracted
    }

    /// Return the output column count.
    pub fn cols(&self) -> usize {
        self.cols
    }
}

/// Shared scalar/update metadata for grouped GEMM execution.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GroupedGemmConfig<'a> {
    jobs: &'a [GroupedGemmJob],
    accumulation: DotGeneralAccumulation,
}

impl<'a> GroupedGemmConfig<'a> {
    pub fn new(jobs: &'a [GroupedGemmJob], accumulation: DotGeneralAccumulation) -> Self {
        Self { jobs, accumulation }
    }

    pub fn jobs(&self) -> &'a [GroupedGemmJob] {
        self.jobs
    }

    pub fn accumulation(&self) -> DotGeneralAccumulation {
        self.accumulation
    }
}

impl DotGeneralAccumulation {
    fn identity(
        op: &'static str,
        dtype: DType,
        multiplicative: bool,
    ) -> crate::Result<ContractionScalar> {
        let result = if multiplicative {
            ContractionScalar::one(dtype)
        } else {
            ContractionScalar::zero(dtype)
        };
        result.map_err(|error| match error {
            Error::Validation { source, .. } => validation(op, source),
            error => error,
        })
    }

    /// Return overwrite semantics, `out = lhs dot rhs`, for `dtype`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{ContractionScalar, DotGeneralAccumulation, DType};
    ///
    /// let accum = DotGeneralAccumulation::overwrite(DType::F64).unwrap();
    /// assert_eq!(accum.alpha, ContractionScalar::F64(1.0));
    /// assert_eq!(accum.beta, ContractionScalar::F64(0.0));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a
    /// [`crate::ValidationError::DTypeMismatch`] source when `dtype` does not
    /// support contraction scalar identities.
    pub fn overwrite(dtype: DType) -> crate::Result<Self> {
        Ok(Self {
            lhs_conj: false,
            rhs_conj: false,
            alpha: Self::identity("DotGeneralAccumulation::overwrite", dtype, true)?,
            beta: Self::identity("DotGeneralAccumulation::overwrite", dtype, false)?,
        })
    }

    /// Return additive update semantics, `out += lhs dot rhs`, for `dtype`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{ContractionScalar, DType, DotGeneralAccumulation};
    ///
    /// let accum = DotGeneralAccumulation::add_to(DType::F64)?;
    /// assert_eq!(accum.alpha, ContractionScalar::F64(1.0));
    /// assert_eq!(accum.beta, ContractionScalar::F64(1.0));
    /// # Ok::<(), tenferro_tensor::Error>(())
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a
    /// [`crate::ValidationError::DTypeMismatch`] source when `dtype` does not
    /// support contraction scalar identities.
    pub fn add_to(dtype: DType) -> crate::Result<Self> {
        Ok(Self {
            lhs_conj: false,
            rhs_conj: false,
            alpha: Self::identity("DotGeneralAccumulation::add_to", dtype, true)?,
            beta: Self::identity("DotGeneralAccumulation::add_to", dtype, true)?,
        })
    }

    /// Return scaled update semantics, `out = alpha * lhs dot rhs + beta * out`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{ContractionScalar, DotGeneralAccumulation};
    ///
    /// let accum = DotGeneralAccumulation::scaled(
    ///     ContractionScalar::F32(0.5),
    ///     ContractionScalar::F32(2.0),
    /// )?;
    /// assert_eq!(accum.alpha, ContractionScalar::F32(0.5));
    /// # Ok::<(), tenferro_tensor::Error>(())
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a
    /// [`crate::ValidationError::DTypeMismatch`] source when `alpha` and `beta`
    /// have different dtypes.
    pub fn scaled(alpha: ContractionScalar, beta: ContractionScalar) -> crate::Result<Self> {
        if alpha.dtype() != beta.dtype() {
            return Err(validation(
                "DotGeneralAccumulation::scaled",
                ValidationError::DTypeMismatch {
                    expected: crate::core_dtype(alpha.dtype()),
                    actual: crate::core_dtype(beta.dtype()),
                },
            ));
        }
        Ok(Self {
            lhs_conj: false,
            rhs_conj: false,
            alpha,
            beta,
        })
    }

    fn validate_for_dtype(self, dtype: DType) -> crate::Result<()> {
        for scalar in [self.alpha, self.beta] {
            if scalar.dtype() != dtype {
                return Err(validation(
                    "dot_general",
                    ValidationError::DTypeMismatch {
                        expected: crate::core_dtype(scalar.dtype()),
                        actual: crate::core_dtype(dtype),
                    },
                ));
            }
        }
        Ok(())
    }
}

#[doc(hidden)]
pub fn validate_dot_general_accumulation(
    lhs: &TensorRead<'_>,
    rhs: &TensorRead<'_>,
    config: &DotGeneralConfig,
    accumulation: DotGeneralAccumulation,
    out: &TensorWrite<'_>,
    op: &'static str,
) -> crate::Result<Vec<usize>> {
    let shape = validate_dot_general_read_into(lhs, rhs, config, out, op)?;
    accumulation.validate_for_dtype(lhs.dtype())?;
    Ok(shape)
}

#[doc(hidden)]
pub fn dot_general_accum_via_temp<B: TensorDot + ?Sized>(
    backend: &mut B,
    lhs: TensorRead<'_>,
    rhs: TensorRead<'_>,
    config: &DotGeneralConfig,
    accumulation: DotGeneralAccumulation,
    mut out: TensorWrite<'_>,
) -> crate::Result<()> {
    validate_dot_general_accumulation(&lhs, &rhs, config, accumulation, &out, "dot_general")?;
    let dot = backend.dot_general_with_conj_read(
        lhs,
        rhs,
        config,
        accumulation.lhs_conj,
        accumulation.rhs_conj,
    )?;
    accumulate_dot_result_into(&dot, accumulation, &mut out)
}

fn grouped_checked_product(
    op: &'static str,
    role: &'static str,
    dims: &[usize],
) -> crate::Result<usize> {
    dims.iter().try_fold(1usize, |acc, &dim| {
        acc.checked_mul(dim).ok_or_else(|| {
            invalid_argument(
                op,
                role,
                format!("logical element count overflows usize for shape {dims:?}"),
            )
        })
    })
}

fn checked_gemm_span(
    op: &'static str,
    role: &'static str,
    offset: usize,
    rows: usize,
    cols: usize,
) -> crate::Result<Option<std::ops::Range<usize>>> {
    let len = rows.checked_mul(cols).ok_or_else(|| {
        invalid_argument(
            op,
            role,
            format!("matrix element count overflows usize: rows={rows} cols={cols}"),
        )
    })?;
    if len == 0 {
        return Ok(None);
    }
    let end = offset.checked_add(len).ok_or_else(|| {
        invalid_argument(
            op,
            role,
            format!("matrix range overflows usize: offset={offset} len={len}"),
        )
    })?;
    Ok(Some(offset..end))
}

fn validate_grouped_gemm_range(
    op: &'static str,
    role: &'static str,
    len: usize,
    range: Option<std::ops::Range<usize>>,
) -> crate::Result<()> {
    let Some(range) = range else {
        return Ok(());
    };
    if range.end > len {
        return Err(invalid_argument(
            op,
            role,
            format!(
                "matrix range {}..{} exceeds shared buffer logical length {len}",
                range.start, range.end
            ),
        ));
    }
    Ok(())
}

#[doc(hidden)]
pub fn validate_grouped_gemm(
    lhs: &TensorRead<'_>,
    rhs: &TensorRead<'_>,
    out: &TensorWrite<'_>,
    config: &GroupedGemmConfig<'_>,
    op: &'static str,
) -> crate::Result<()> {
    if lhs.dtype() != rhs.dtype() {
        return Err(validation(
            op,
            ValidationError::DTypeMismatch {
                expected: crate::core_dtype(lhs.dtype()),
                actual: crate::core_dtype(rhs.dtype()),
            },
        ));
    }
    if lhs.dtype() != out.dtype() {
        return Err(validation(
            op,
            ValidationError::DTypeMismatch {
                expected: crate::core_dtype(lhs.dtype()),
                actual: crate::core_dtype(out.dtype()),
            },
        ));
    }
    config.accumulation.validate_for_dtype(lhs.dtype())?;

    let lhs_len = grouped_checked_product(op, "lhs", lhs.shape())?;
    let rhs_len = grouped_checked_product(op, "rhs", rhs.shape())?;
    let out_len = grouped_checked_product(op, "out", out.shape())?;
    // Grouped GEMM job count is runtime-controlled and can be large. Keep the
    // validation ranges in a reserved Vec, not SmallVec, so arbitrary batches
    // avoid inline-capacity tuning and can be sorted for O(n log n) overlap
    // validation.
    let mut out_ranges = Vec::<(usize, std::ops::Range<usize>)>::with_capacity(config.jobs.len());
    for (idx, job) in config.jobs.iter().enumerate() {
        validate_grouped_gemm_range(
            op,
            "lhs",
            lhs_len,
            checked_gemm_span(op, "lhs", job.lhs_offset, job.rows, job.contracted)?,
        )?;
        validate_grouped_gemm_range(
            op,
            "rhs",
            rhs_len,
            checked_gemm_span(op, "rhs", job.rhs_offset, job.contracted, job.cols)?,
        )?;
        let out_range = checked_gemm_span(op, "out", job.out_offset, job.rows, job.cols)?;
        validate_grouped_gemm_range(op, "out", out_len, out_range.clone())?;
        if let Some(out_range) = out_range {
            out_ranges.push((idx, out_range));
        }
    }
    out_ranges.sort_unstable_by_key(|(_, range)| range.start);
    for pair in out_ranges.windows(2) {
        let (prev_idx, previous) = &pair[0];
        let (idx, current) = &pair[1];
        if previous.end > current.start {
            return Err(invalid_argument(
                op,
                "jobs",
                format!(
                    "grouped GEMM output range for job {idx} overlaps job {prev_idx} range {}..{}",
                    previous.start, previous.end
                ),
            ));
        }
    }
    Ok(())
}

fn add_element_offsets(
    op: &'static str,
    base: isize,
    offset: usize,
    role: &'static str,
) -> crate::Result<isize> {
    let offset = isize::try_from(offset).map_err(|_| {
        invalid_argument(op, role, format!("offset {offset} does not fit in isize"))
    })?;
    base.checked_add(offset).ok_or_else(|| {
        invalid_argument(
            op,
            role,
            format!("offset overflows isize: base={base} offset={offset}"),
        )
    })
}

fn dim_stride(op: &'static str, dim: usize, role: &'static str) -> crate::Result<isize> {
    isize::try_from(dim).map_err(|_| {
        invalid_argument(
            op,
            role,
            format!("leading dimension {dim} does not fit in isize"),
        )
    })
}

fn typed_read_storage<'a, T: crate::TensorScalar>(
    tensor: &'a TypedTensor<T>,
    op: &'static str,
) -> crate::Result<(&'a [T], isize)> {
    tensor.host_data().map(|data| (data, 0)).map_err(|_| {
        crate::Error::runtime_state(
            op,
            "grouped GEMM default path requires host-backed tensor storage",
        )
    })
}

fn grouped_gemm_default_config() -> DotGeneralConfig {
    // DotGeneralConfig owns Vec fields, so this rank-2 fallback config follows
    // that API boundary rather than introducing SmallVec locally.
    DotGeneralConfig {
        lhs_contracting_dims: vec![1],
        rhs_contracting_dims: vec![0],
        lhs_batch_dims: Vec::new(),
        rhs_batch_dims: Vec::new(),
    }
}

trait GroupedGemmDType<T> {
    fn wrap_read(view: TypedTensorView<'_, T>) -> TensorView<'_>;
    fn wrap_write(view: TypedTensorViewMut<'_, T>) -> TensorViewMut<'_>;
}

struct GroupedF32;
struct GroupedF64;
struct GroupedC32;
struct GroupedC64;

impl GroupedGemmDType<f32> for GroupedF32 {
    fn wrap_read(view: TypedTensorView<'_, f32>) -> TensorView<'_> {
        TensorView::F32(view)
    }

    fn wrap_write(view: TypedTensorViewMut<'_, f32>) -> TensorViewMut<'_> {
        TensorViewMut::F32(view)
    }
}

impl GroupedGemmDType<f64> for GroupedF64 {
    fn wrap_read(view: TypedTensorView<'_, f64>) -> TensorView<'_> {
        TensorView::F64(view)
    }

    fn wrap_write(view: TypedTensorViewMut<'_, f64>) -> TensorViewMut<'_> {
        TensorViewMut::F64(view)
    }
}

impl GroupedGemmDType<Complex32> for GroupedC32 {
    fn wrap_read(view: TypedTensorView<'_, Complex32>) -> TensorView<'_> {
        TensorView::C32(view)
    }

    fn wrap_write(view: TypedTensorViewMut<'_, Complex32>) -> TensorViewMut<'_> {
        TensorViewMut::C32(view)
    }
}

impl GroupedGemmDType<Complex64> for GroupedC64 {
    fn wrap_read(view: TypedTensorView<'_, Complex64>) -> TensorView<'_> {
        TensorView::C64(view)
    }

    fn wrap_write(view: TypedTensorViewMut<'_, Complex64>) -> TensorViewMut<'_> {
        TensorViewMut::C64(view)
    }
}

#[allow(clippy::too_many_arguments)]
fn grouped_gemm_default_loop<B, T, V>(
    backend: &mut B,
    lhs_data: &[T],
    lhs_base: isize,
    rhs_data: &[T],
    rhs_base: isize,
    out_view: &mut TypedTensorViewMut<'_, T>,
    config: &GroupedGemmConfig<'_>,
) -> crate::Result<()>
where
    B: TensorDot + ?Sized,
    T: 'static,
    V: GroupedGemmDType<T>,
{
    let op = "grouped_gemm";
    let dot_config = grouped_gemm_default_config();
    for job in config.jobs {
        let lhs_offset = add_element_offsets(op, lhs_base, job.lhs_offset, "lhs")?;
        let rhs_offset = add_element_offsets(op, rhs_base, job.rhs_offset, "rhs")?;
        let out_offset = add_element_offsets(op, out_view.offset(), job.out_offset, "out")?;
        let lhs_rows = dim_stride(op, job.rows, "lhs")?;
        let rhs_rows = dim_stride(op, job.contracted, "rhs")?;
        let out_rows = dim_stride(op, job.rows, "out")?;
        // TypedTensorView constructors own Vec shape/stride metadata. These
        // fallback rank-2 views are short-lived, but SmallVec is not usable
        // without changing the view API.
        let lhs_matrix = TypedTensorView::from_slice(
            vec![job.rows, job.contracted],
            vec![1, lhs_rows],
            lhs_offset,
            lhs_data,
        )?;
        let rhs_matrix = TypedTensorView::from_slice(
            vec![job.contracted, job.cols],
            vec![1, rhs_rows],
            rhs_offset,
            rhs_data,
        )?;
        let out_storage = out_view.host_storage_mut()?;
        let out_matrix = TypedTensorViewMut::from_slice(
            vec![job.rows, job.cols],
            vec![1, out_rows],
            out_offset,
            out_storage,
        )?;
        backend.dot_general_read_into_accum(
            TensorRead::from_view(V::wrap_read(lhs_matrix)),
            TensorRead::from_view(V::wrap_read(rhs_matrix)),
            &dot_config,
            config.accumulation,
            TensorWrite::from_view(V::wrap_write(out_matrix)),
        )?;
    }
    Ok(())
}

#[doc(hidden)]
pub fn grouped_gemm_via_sequential<B>(
    backend: &mut B,
    lhs: TensorRead<'_>,
    rhs: TensorRead<'_>,
    config: &GroupedGemmConfig<'_>,
    mut out: TensorWrite<'_>,
) -> crate::Result<()>
where
    B: TensorDot + ?Sized,
{
    validate_grouped_gemm(&lhs, &rhs, &out, config, "grouped_gemm")?;
    macro_rules! dispatch {
        ($variant:ident, $wrapper:ty) => {
            match (&lhs, &rhs, &mut out) {
                (
                    TensorRead::Tensor(Tensor::$variant(a)),
                    TensorRead::Tensor(Tensor::$variant(b)),
                    TensorWrite::Tensor(Tensor::$variant(c)),
                ) => {
                    let (a_data, a_base) = typed_read_storage(a, "grouped_gemm")?;
                    let (b_data, b_base) = typed_read_storage(b, "grouped_gemm")?;
                    let mut c_view = c.as_view_mut();
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a_data,
                        a_base,
                        b_data,
                        b_base,
                        &mut c_view,
                        config,
                    );
                }
                (
                    TensorRead::Tensor(Tensor::$variant(a)),
                    TensorRead::View(TensorView::$variant(b)),
                    TensorWrite::Tensor(Tensor::$variant(c)),
                ) => {
                    let (a_data, a_base) = typed_read_storage(a, "grouped_gemm")?;
                    let mut c_view = c.as_view_mut();
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a_data,
                        a_base,
                        b.host_storage()?,
                        b.offset(),
                        &mut c_view,
                        config,
                    );
                }
                (
                    TensorRead::View(TensorView::$variant(a)),
                    TensorRead::Tensor(Tensor::$variant(b)),
                    TensorWrite::Tensor(Tensor::$variant(c)),
                ) => {
                    let (b_data, b_base) = typed_read_storage(b, "grouped_gemm")?;
                    let mut c_view = c.as_view_mut();
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a.host_storage()?,
                        a.offset(),
                        b_data,
                        b_base,
                        &mut c_view,
                        config,
                    );
                }
                (
                    TensorRead::View(TensorView::$variant(a)),
                    TensorRead::View(TensorView::$variant(b)),
                    TensorWrite::Tensor(Tensor::$variant(c)),
                ) => {
                    let mut c_view = c.as_view_mut();
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a.host_storage()?,
                        a.offset(),
                        b.host_storage()?,
                        b.offset(),
                        &mut c_view,
                        config,
                    );
                }
                (
                    TensorRead::Tensor(Tensor::$variant(a)),
                    TensorRead::Tensor(Tensor::$variant(b)),
                    TensorWrite::View(TensorViewMut::$variant(c)),
                ) => {
                    let (a_data, a_base) = typed_read_storage(a, "grouped_gemm")?;
                    let (b_data, b_base) = typed_read_storage(b, "grouped_gemm")?;
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend, a_data, a_base, b_data, b_base, c, config,
                    );
                }
                (
                    TensorRead::Tensor(Tensor::$variant(a)),
                    TensorRead::View(TensorView::$variant(b)),
                    TensorWrite::View(TensorViewMut::$variant(c)),
                ) => {
                    let (a_data, a_base) = typed_read_storage(a, "grouped_gemm")?;
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a_data,
                        a_base,
                        b.host_storage()?,
                        b.offset(),
                        c,
                        config,
                    );
                }
                (
                    TensorRead::View(TensorView::$variant(a)),
                    TensorRead::Tensor(Tensor::$variant(b)),
                    TensorWrite::View(TensorViewMut::$variant(c)),
                ) => {
                    let (b_data, b_base) = typed_read_storage(b, "grouped_gemm")?;
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a.host_storage()?,
                        a.offset(),
                        b_data,
                        b_base,
                        c,
                        config,
                    );
                }
                (
                    TensorRead::View(TensorView::$variant(a)),
                    TensorRead::View(TensorView::$variant(b)),
                    TensorWrite::View(TensorViewMut::$variant(c)),
                ) => {
                    return grouped_gemm_default_loop::<_, _, $wrapper>(
                        backend,
                        a.host_storage()?,
                        a.offset(),
                        b.host_storage()?,
                        b.offset(),
                        c,
                        config,
                    );
                }
                _ => {}
            }
        };
    }

    dispatch!(F32, GroupedF32);
    dispatch!(F64, GroupedF64);
    dispatch!(C32, GroupedC32);
    dispatch!(C64, GroupedC64);
    Err(validation(
        "grouped_gemm",
        ValidationError::DTypeMismatch {
            expected: crate::core_dtype(lhs.dtype()),
            actual: crate::core_dtype(out.dtype()),
        },
    ))
}

fn grouped_gemm_default<B>(
    backend: &mut B,
    lhs: TensorRead<'_>,
    rhs: TensorRead<'_>,
    config: &GroupedGemmConfig<'_>,
    out: TensorWrite<'_>,
) -> crate::Result<()>
where
    B: TensorDot + ?Sized,
{
    grouped_gemm_via_sequential(backend, lhs, rhs, config, out)
}

#[doc(hidden)]
pub fn accumulate_dot_result_into(
    dot: &Tensor,
    accumulation: DotGeneralAccumulation,
    out: &mut TensorWrite<'_>,
) -> crate::Result<()> {
    macro_rules! dispatch {
        ($variant:ident, $ty:ty) => {
            if let (
                Tensor::$variant(dot),
                ContractionScalar::$variant(alpha),
                ContractionScalar::$variant(beta),
            ) = (dot, accumulation.alpha, accumulation.beta)
            {
                match out {
                    TensorWrite::Tensor(Tensor::$variant(out)) => {
                        let mut out = out.as_view_mut();
                        accumulate_typed(dot.as_slice()?, alpha, beta, &mut out)?;
                        return Ok(());
                    }
                    TensorWrite::View(crate::TensorViewMut::$variant(out)) => {
                        accumulate_typed(dot.as_slice()?, alpha, beta, out)?;
                        return Ok(());
                    }
                    _ => {}
                }
            }
        };
    }

    dispatch!(F32, f32);
    dispatch!(F64, f64);
    dispatch!(C32, Complex32);
    dispatch!(C64, Complex64);

    Err(validation(
        "dot_general",
        ValidationError::DTypeMismatch {
            expected: crate::core_dtype(accumulation.alpha.dtype()),
            actual: crate::core_dtype(dot.dtype()),
        },
    ))
}

fn accumulate_typed<T>(
    dot: &[T],
    alpha: T,
    beta: T,
    out: &mut TypedTensorViewMut<'_, T>,
) -> crate::Result<()>
where
    T: Copy
        + PartialEq
        + std::ops::Add<Output = T>
        + std::ops::Mul<Output = T>
        + num_traits::Zero
        + 'static,
{
    let beta_is_zero = beta == T::zero();
    if let Some(output) = compact_host_accumulation_slice(out, dot.len())? {
        for (output, dot_value) in output.iter_mut().zip(dot.iter().copied()) {
            // INVARIANT: beta == 0 follows BLAS GEMM semantics and does not read
            // the existing output element; beta != 0 requires an initialized
            // TensorWrite target and performs a read-modify-write update.
            *output = if beta_is_zero {
                alpha * dot_value
            } else {
                alpha * dot_value + beta * *output
            };
        }
        return Ok(());
    }

    for (linear, dot_value) in dot.iter().copied().enumerate() {
        let indices = flat_to_multi_for_shape(out.shape(), linear);
        let output = out.get_mut(&indices).ok_or_else(|| {
            invalid_argument(
                "dot_general",
                "output",
                format!("index {indices:?} is outside accumulation target"),
            )
        })?;
        // INVARIANT: beta == 0 follows BLAS GEMM semantics and does not read
        // the existing output element; beta != 0 requires an initialized
        // TensorWrite target and performs a read-modify-write update.
        *output = if beta_is_zero {
            alpha * dot_value
        } else {
            alpha * dot_value + beta * *output
        };
    }
    Ok(())
}

fn compact_host_accumulation_slice<'a, T: 'static>(
    out: &'a mut TypedTensorViewMut<'_, T>,
    expected_len: usize,
) -> crate::Result<Option<&'a mut [T]>> {
    if out.backend_buffer().is_some()
        || out.n_elements() != expected_len
        || !out.is_col_major_contiguous()?
    {
        return Ok(None);
    }

    let start = usize::try_from(out.offset()).map_err(|_| {
        invalid_argument("dot_general", "output", "compact output offset is negative")
    })?;
    let end = start
        .checked_add(expected_len)
        .ok_or_else(|| validation("dot_general", ValidationError::IntegerOverflow))?;
    out.host_storage_mut()?
        .get_mut(start..end)
        .map(Some)
        .ok_or_else(|| {
            invalid_argument(
                "dot_general",
                "output",
                "compact output is outside its backing storage",
            )
        })
}

fn flat_to_multi_for_shape(shape: &[usize], mut linear: usize) -> Vec<usize> {
    let mut indices = Vec::with_capacity(shape.len());
    for &dim in shape {
        if dim == 0 {
            indices.push(0);
        } else {
            indices.push(linear % dim);
            linear /= dim;
        }
    }
    indices
}

/// Canonical elementwise fusion plan shared between segmented execution and backends.
#[doc(hidden)]
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ElementwiseFusionPlan {
    dtype: crate::DType,
    input_count: usize,
    // Keep view metadata in Vecs. A/B benchmarking on the broadcast_mul
    // path showed SmallVec made this metadata path about 6-7% slower.
    input_views: Vec<ElementwiseFusionInputView>,
    outputs: Vec<usize>,
    ops: Vec<ElementwiseFusionInst>,
}

/// Metadata-only view applied to one backend fusion input.
#[doc(hidden)]
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum ElementwiseFusionInputView {
    Identity,
    BroadcastInDim {
        // Vec is intentional here; see ElementwiseFusionPlan::input_views.
        shape: Vec<usize>,
        dims: Vec<usize>,
    },
}

/// One node in a canonical elementwise fusion plan.
#[doc(hidden)]
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ElementwiseFusionInst {
    op: ElementwiseFusionOp,
    inputs: Vec<usize>,
}

tenferro_core_ops::define_elementwise_fusion_op!();

impl ElementwiseFusionPlan {
    /// Build a backend elementwise fusion plan.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::{
    ///     ElementwiseFusionInst, ElementwiseFusionOp, ElementwiseFusionPlan,
    /// };
    /// use tenferro_tensor::DType;
    ///
    /// let plan = ElementwiseFusionPlan::new(
    ///     DType::F64,
    ///     2,
    ///     vec![2],
    ///     vec![ElementwiseFusionInst::new(ElementwiseFusionOp::Add, vec![0, 1])],
    /// );
    /// assert_eq!(plan.input_count(), 2);
    /// ```
    pub fn new(
        dtype: crate::DType,
        input_count: usize,
        outputs: Vec<usize>,
        ops: Vec<ElementwiseFusionInst>,
    ) -> Self {
        Self::with_input_views(
            dtype,
            vec![ElementwiseFusionInputView::Identity; input_count],
            outputs,
            ops,
        )
    }

    /// Build a backend elementwise fusion plan with input view metadata.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::{
    ///     ElementwiseFusionInputView, ElementwiseFusionInst, ElementwiseFusionOp,
    ///     ElementwiseFusionPlan,
    /// };
    /// use tenferro_tensor::DType;
    ///
    /// let plan = ElementwiseFusionPlan::with_input_views(
    ///     DType::F64,
    ///     vec![ElementwiseFusionInputView::broadcast_in_dim(vec![2, 3], vec![0])],
    ///     vec![1],
    ///     vec![ElementwiseFusionInst::new(ElementwiseFusionOp::Negate, vec![0])],
    /// );
    /// assert_eq!(plan.input_count(), 1);
    /// ```
    pub fn with_input_views(
        dtype: crate::DType,
        input_views: impl IntoIterator<Item = ElementwiseFusionInputView>,
        outputs: Vec<usize>,
        ops: Vec<ElementwiseFusionInst>,
    ) -> Self {
        let input_views = input_views.into_iter().collect::<Vec<_>>();
        let input_count = input_views.len();
        Self {
            dtype,
            input_count,
            input_views,
            outputs,
            ops,
        }
    }

    /// Return the scalar dtype expected by this fusion plan.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::ElementwiseFusionPlan;
    /// use tenferro_tensor::DType;
    ///
    /// let plan = ElementwiseFusionPlan::new(DType::F32, 0, Vec::new(), Vec::new());
    /// assert_eq!(plan.dtype(), DType::F32);
    /// ```
    pub fn dtype(&self) -> crate::DType {
        self.dtype
    }

    /// Return the number of input tensors expected by this plan.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::ElementwiseFusionPlan;
    /// use tenferro_tensor::DType;
    ///
    /// let plan = ElementwiseFusionPlan::new(DType::F64, 3, Vec::new(), Vec::new());
    /// assert_eq!(plan.input_count(), 3);
    /// ```
    pub fn input_count(&self) -> usize {
        self.input_count
    }

    /// Return metadata views applied to fusion inputs before executing ops.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::ElementwiseFusionPlan;
    /// use tenferro_tensor::DType;
    ///
    /// let plan = ElementwiseFusionPlan::new(DType::F64, 2, Vec::new(), Vec::new());
    /// assert_eq!(plan.input_views().len(), 2);
    /// ```
    pub fn input_views(&self) -> &[ElementwiseFusionInputView] {
        &self.input_views
    }

    /// Return the value ids selected as fusion outputs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::ElementwiseFusionPlan;
    /// use tenferro_tensor::DType;
    ///
    /// let plan = ElementwiseFusionPlan::new(DType::F64, 0, vec![0], Vec::new());
    /// assert_eq!(plan.outputs(), &[0]);
    /// ```
    pub fn outputs(&self) -> &[usize] {
        &self.outputs
    }

    /// Return the fused elementwise instruction sequence.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::{
    ///     ElementwiseFusionInst, ElementwiseFusionOp, ElementwiseFusionPlan,
    /// };
    /// use tenferro_tensor::DType;
    ///
    /// let inst = ElementwiseFusionInst::new(ElementwiseFusionOp::Negate, vec![0]);
    /// let plan = ElementwiseFusionPlan::new(DType::F64, 1, vec![1], vec![inst]);
    /// assert_eq!(plan.ops().len(), 1);
    /// ```
    pub fn ops(&self) -> &[ElementwiseFusionInst] {
        &self.ops
    }
}

impl ElementwiseFusionInputView {
    /// Build metadata for a `BroadcastInDim` fusion input view.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::ElementwiseFusionInputView;
    ///
    /// let view = ElementwiseFusionInputView::broadcast_in_dim(vec![2, 3], vec![0]);
    /// assert!(matches!(view, ElementwiseFusionInputView::BroadcastInDim { .. }));
    /// ```
    pub fn broadcast_in_dim(
        shape: impl IntoIterator<Item = usize>,
        dims: impl IntoIterator<Item = usize>,
    ) -> Self {
        Self::BroadcastInDim {
            shape: shape.into_iter().collect(),
            dims: dims.into_iter().collect(),
        }
    }

    /// Return true when this fusion input is an identity view.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::ElementwiseFusionInputView;
    ///
    /// assert!(ElementwiseFusionInputView::Identity.is_identity());
    /// ```
    pub fn is_identity(&self) -> bool {
        matches!(self, Self::Identity)
    }
}

impl ElementwiseFusionInst {
    /// Build a backend elementwise fusion instruction.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::{ElementwiseFusionInst, ElementwiseFusionOp};
    ///
    /// let inst = ElementwiseFusionInst::new(ElementwiseFusionOp::Add, vec![0, 1]);
    /// assert_eq!(inst.inputs(), &[0, 1]);
    /// ```
    pub fn new(op: ElementwiseFusionOp, inputs: Vec<usize>) -> Self {
        Self { op, inputs }
    }

    /// Return the elementwise op executed by this instruction.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::{ElementwiseFusionInst, ElementwiseFusionOp};
    ///
    /// let inst = ElementwiseFusionInst::new(ElementwiseFusionOp::Negate, vec![0]);
    /// assert_eq!(inst.op(), ElementwiseFusionOp::Negate);
    /// ```
    pub fn op(&self) -> ElementwiseFusionOp {
        self.op
    }

    /// Return this instruction's input value ids.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::backend::{ElementwiseFusionInst, ElementwiseFusionOp};
    ///
    /// let inst = ElementwiseFusionInst::new(ElementwiseFusionOp::Multiply, vec![2, 0]);
    /// assert_eq!(inst.inputs(), &[2, 0]);
    /// ```
    pub fn inputs(&self) -> &[usize] {
        &self.inputs
    }
}

/// Runtime operation selected by [`TensorElementwise::elementwise_read_into`].
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ElementwiseReadOp {
    /// Binary addition.
    Add,
    /// Binary subtraction.
    Subtract,
    /// Binary multiplication.
    Multiply,
    /// Unary negation.
    Negate,
    /// Unary conjugation.
    Conj,
    /// Binary division.
    Divide,
}

impl ElementwiseReadOp {
    fn label(self) -> &'static str {
        match self {
            Self::Add => "add",
            Self::Subtract => "sub",
            Self::Multiply => "mul",
            Self::Negate => "neg",
            Self::Conj => "conj",
            Self::Divide => "div",
        }
    }

    fn arity(self) -> usize {
        match self {
            Self::Negate | Self::Conj => 1,
            Self::Add | Self::Subtract | Self::Multiply | Self::Divide => 2,
        }
    }
}

#[derive(Clone, Copy, Debug)]
enum StorageIdentity {
    Host {
        start: usize,
        end: usize,
    },
    Backend {
        domain: Option<AllocationDomainId>,
        allocation: Option<AllocationId>,
        family: &'static str,
        object: usize,
    },
}

fn host_storage_identity<T>(data: &[T]) -> StorageIdentity {
    let start = data.as_ptr() as usize;
    let bytes = std::mem::size_of_val(data);
    StorageIdentity::Host {
        start,
        end: start.saturating_add(bytes),
    }
}

fn backend_storage_identity<T: 'static>(buffer: &dyn crate::BackendStorage<T>) -> StorageIdentity {
    StorageIdentity::Backend {
        domain: buffer.allocation_domain(),
        allocation: buffer.allocation_id(),
        family: buffer.backend_family(),
        // INVARIANT: every backend buffer is borrowed from the single Box-owned
        // root allocation; the data pointer of this trait object is stable for
        // that owner and is used only as a fallback when provider identity is
        // unavailable.
        object: buffer as *const dyn crate::BackendStorage<T> as *const () as usize,
    }
}

fn typed_tensor_storage_identity<T: crate::TensorScalar>(
    tensor: &TypedTensor<T>,
) -> crate::Result<StorageIdentity> {
    if tensor.backend_buffer().is_some() {
        let buffer = tensor.backend_buffer().ok_or_else(|| {
            crate::Error::runtime_state("typed_tensor_storage_identity", "backend buffer missing")
        })?;
        Ok(backend_storage_identity(buffer))
    } else {
        Ok(host_storage_identity(tensor.host_data()?))
    }
}

fn typed_view_storage_identity<T: crate::TensorScalar + 'static>(
    view: &TypedTensorView<'_, T>,
) -> crate::Result<StorageIdentity> {
    match view.backend_buffer() {
        Some(buffer) => Ok(backend_storage_identity(buffer)),
        None => view.host_storage().map(host_storage_identity),
    }
}

fn tensor_read_storage_identity(input: &TensorRead<'_>) -> crate::Result<StorageIdentity> {
    macro_rules! typed_identity {
        ($value:expr) => {
            match $value {
                Tensor::F32(value) => typed_tensor_storage_identity(value),
                Tensor::F64(value) => typed_tensor_storage_identity(value),
                Tensor::I32(value) => typed_tensor_storage_identity(value),
                Tensor::I64(value) => typed_tensor_storage_identity(value),
                Tensor::Bool(value) => typed_tensor_storage_identity(value),
                Tensor::C32(value) => typed_tensor_storage_identity(value),
                Tensor::C64(value) => typed_tensor_storage_identity(value),
            }
        };
    }
    macro_rules! view_identity {
        ($value:expr) => {
            match $value {
                TensorView::F32(value) => typed_view_storage_identity(value),
                TensorView::F64(value) => typed_view_storage_identity(value),
                TensorView::I32(value) => typed_view_storage_identity(value),
                TensorView::I64(value) => typed_view_storage_identity(value),
                TensorView::Bool(value) => typed_view_storage_identity(value),
                TensorView::C32(value) => typed_view_storage_identity(value),
                TensorView::C64(value) => typed_view_storage_identity(value),
            }
        };
    }

    match input {
        TensorRead::Tensor(tensor) => typed_identity!(tensor),
        TensorRead::View(view) => view_identity!(view),
    }
}

fn storage_overlaps(lhs: StorageIdentity, rhs: StorageIdentity) -> bool {
    match (lhs, rhs) {
        (
            StorageIdentity::Host {
                start: lhs_start,
                end: lhs_end,
            },
            StorageIdentity::Host {
                start: rhs_start,
                end: rhs_end,
            },
        ) => lhs_start < rhs_end && rhs_start < lhs_end,
        (
            StorageIdentity::Backend {
                domain: lhs_domain,
                allocation: lhs_allocation,
                family: lhs_family,
                object: lhs_object,
            },
            StorageIdentity::Backend {
                domain: rhs_domain,
                allocation: rhs_allocation,
                family: rhs_family,
                object: rhs_object,
            },
        ) => {
            lhs_object == rhs_object
                || matches!(
                    (lhs_domain, rhs_domain, lhs_allocation, rhs_allocation),
                    (Some(lhs_domain), Some(rhs_domain), Some(lhs), Some(rhs))
                        if lhs_domain == rhs_domain && lhs == rhs
                )
                || matches!(
                    (lhs_domain, rhs_domain, lhs_allocation, rhs_allocation),
                    (None, None, Some(lhs), Some(rhs)) if lhs_family == rhs_family && lhs == rhs
                )
        }
        _ => false,
    }
}

fn validate_elementwise_output_disjoint(
    op: ElementwiseReadOp,
    inputs: &[TensorRead<'_>],
    out: &TensorWrite<'_>,
) -> crate::Result<()> {
    validate_read_into_destination(op.label(), inputs, out)
}

/// Validate that a caller-owned destination does not overlap any read input.
///
/// The check is intentionally conservative for host views: two views backed by
/// the same host allocation are treated as overlapping because the allocation
/// identity is the only stable boundary contract available to erased backend
/// code. Backend allocations use their domain/allocation identity when the
/// provider exposes it.
///
/// # Errors
///
/// Returns `tenferro_tensor_core::ValidationError::InvalidArgument` when the
/// destination storage overlaps an input, or `Error::RuntimeState` when
/// storage identity cannot be established safely.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::{Tensor, TensorRead, TensorWrite};
/// use tenferro_tensor::backend::validate_read_into_destination;
///
/// let input = Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?;
/// let mut output = Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?;
/// validate_read_into_destination(
///     "example",
///     &[TensorRead::from_tensor(&input)],
///     &TensorWrite::from_tensor(&mut output),
/// )?;
/// # Ok::<(), tenferro_tensor::Error>(())
/// ```
pub fn validate_read_into_destination(
    op: &'static str,
    inputs: &[TensorRead<'_>],
    out: &TensorWrite<'_>,
) -> crate::Result<()> {
    let output_identity = tensor_read_storage_identity(&out.as_read())?;
    for (index, input) in inputs.iter().enumerate() {
        if storage_overlaps(tensor_read_storage_identity(input)?, output_identity) {
            return Err(Error::invalid_argument(
                op,
                "out",
                format!("destination storage overlaps input {index}"),
            ));
        }
    }
    Ok(())
}

fn read_is_host(input: &TensorRead<'_>) -> bool {
    match input {
        TensorRead::Tensor(tensor) => !tensor.is_backend_buffer(),
        TensorRead::View(view) => match view {
            TensorView::F32(view) => view.backend_buffer().is_none(),
            TensorView::F64(view) => view.backend_buffer().is_none(),
            TensorView::I32(view) => view.backend_buffer().is_none(),
            TensorView::I64(view) => view.backend_buffer().is_none(),
            TensorView::Bool(view) => view.backend_buffer().is_none(),
            TensorView::C32(view) => view.backend_buffer().is_none(),
            TensorView::C64(view) => view.backend_buffer().is_none(),
        },
    }
}

fn write_is_host(out: &TensorWrite<'_>) -> bool {
    read_is_host(&out.as_read())
}

fn one_shot_supports(op: ElementwiseReadOp, dtype: DType) -> bool {
    match op {
        ElementwiseReadOp::Conj => true,
        ElementwiseReadOp::Add
        | ElementwiseReadOp::Subtract
        | ElementwiseReadOp::Multiply
        | ElementwiseReadOp::Divide
        | ElementwiseReadOp::Negate => !matches!(dtype, DType::Bool),
    }
}

fn one_shot_eligible(
    op: ElementwiseReadOp,
    inputs: &[TensorRead<'_>],
    out: &TensorWrite<'_>,
) -> bool {
    let dtype = out.dtype();
    write_is_host(out)
        && one_shot_supports(op, dtype)
        && inputs.iter().all(|input| {
            read_is_host(input) && input.dtype() == dtype && input.shape() == out.shape()
        })
}

fn tensor_write_view(out: TensorWrite<'_>) -> TensorViewMut<'_> {
    match out {
        TensorWrite::Tensor(tensor) => match tensor {
            Tensor::F32(tensor) => TensorViewMut::F32(tensor.as_view_mut()),
            Tensor::F64(tensor) => TensorViewMut::F64(tensor.as_view_mut()),
            Tensor::I32(tensor) => TensorViewMut::I32(tensor.as_view_mut()),
            Tensor::I64(tensor) => TensorViewMut::I64(tensor.as_view_mut()),
            Tensor::Bool(tensor) => TensorViewMut::Bool(tensor.as_view_mut()),
            Tensor::C32(tensor) => TensorViewMut::C32(tensor.as_view_mut()),
            Tensor::C64(tensor) => TensorViewMut::C64(tensor.as_view_mut()),
        },
        TensorWrite::View(view) => view,
    }
}

fn non_null_bytes<T>(data: &[T]) -> NonNull<u8> {
    NonNull::new(data.as_ptr().cast_mut().cast()).unwrap_or_else(NonNull::dangling)
}

fn typed_bytes<T>(data: &[T]) -> &[u8] {
    // SAFETY: u8 has alignment one and the returned bytes retain the shared
    // lifetime of the typed source slice.
    unsafe { std::slice::from_raw_parts(data.as_ptr().cast(), std::mem::size_of_val(data)) }
}

fn typed_bytes_mut<T>(data: &mut [T]) -> &mut [u8] {
    let len = std::mem::size_of_val(data);
    // SAFETY: u8 has alignment one and the returned bytes retain the unique
    // lifetime of the typed destination slice.
    unsafe { std::slice::from_raw_parts_mut(data.as_mut_ptr().cast(), len) }
}

fn erased_raw_strided_ptr<'a>(
    dtype: KernelDType,
    data: &'a [u8],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
) -> strided_kernel::Result<ErasedRawStridedPtr<'a>> {
    // SAFETY: callers derive `data` from initialized typed host storage and
    // retain the backing borrow for the returned descriptor lifetime.
    unsafe {
        ErasedRawStridedPtr::from_raw_parts(
            dtype,
            non_null_bytes(data),
            data.len(),
            dims,
            strides,
            offset,
        )
    }
}

fn erased_raw_strided_mut<'a>(
    dtype: KernelDType,
    data: &'a mut [u8],
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
) -> strided_kernel::Result<ErasedRawStridedMut<'a>> {
    let data_ptr = NonNull::new(data.as_mut_ptr()).unwrap_or_else(NonNull::dangling);
    // SAFETY: callers derive `data` from a uniquely borrowed initialized host
    // destination and retain that borrow for the returned descriptor lifetime.
    unsafe {
        ErasedRawStridedMut::from_raw_parts(dtype, data_ptr, data.len(), dims, strides, offset)
    }
}

fn execute_one_shot_map<T: 'static>(
    dtype: KernelDType,
    op: ErasedMapOp,
    ctx: &ExecContext,
    input: TypedTensorView<'_, T>,
    mut out: TypedTensorViewMut<'_, T>,
) -> crate::Result<()> {
    let input_data = input.host_storage()?;
    // INVARIANT: dtype and layout come from the same validated typed view, and
    // its host storage remains borrowed until replay returns.
    // SAFETY: input_data supplies the pointer and exact byte length; the view
    // owns the matching shape, signed strides, and in-bounds offset.
    let input_descriptor = erased_raw_strided_ptr(
        dtype,
        typed_bytes(input_data),
        input.shape(),
        input.strides(),
        input.offset(),
    )
    .map_err(|error| Error::backend_source("elementwise_read_into", error))?;

    let out_dims = SmallVec::<[usize; 8]>::from_slice(out.shape());
    let out_strides = SmallVec::<[isize; 8]>::from_slice(out.strides());
    let out_offset = out.offset();
    let out_data = out.host_storage_mut()?;
    // INVARIANT: the copied output layout describes this uniquely borrowed
    // host storage, already validated as disjoint from every input.
    let mut out_descriptor = erased_raw_strided_mut(
        dtype,
        typed_bytes_mut(out_data),
        &out_dims,
        &out_strides,
        out_offset,
    )
    .map_err(|error| Error::backend_source("elementwise_read_into", error))?;
    erased_map_into(dtype, op, ctx, &mut out_descriptor, &input_descriptor)
        .map_err(|error| Error::backend_source("elementwise_read_into", error))
}

fn execute_one_shot_zip<T: 'static>(
    dtype: KernelDType,
    op: ErasedZipOp,
    ctx: &ExecContext,
    lhs: TypedTensorView<'_, T>,
    rhs: TypedTensorView<'_, T>,
    mut out: TypedTensorViewMut<'_, T>,
) -> crate::Result<()> {
    let lhs_data = lhs.host_storage()?;
    // INVARIANT: dtype and layout come from the same validated typed view, and
    // its host storage remains borrowed until replay returns.
    // SAFETY: lhs_data supplies the pointer and exact byte length; the view
    // owns the matching shape, signed strides, and in-bounds offset.
    let lhs_descriptor = erased_raw_strided_ptr(
        dtype,
        typed_bytes(lhs_data),
        lhs.shape(),
        lhs.strides(),
        lhs.offset(),
    )
    .map_err(|error| Error::backend_source("elementwise_read_into", error))?;
    let rhs_data = rhs.host_storage()?;
    // INVARIANT: dtype and layout come from the same validated typed view, and
    // its host storage remains borrowed until replay returns.
    // SAFETY: rhs_data supplies the pointer and exact byte length; the view
    // owns the matching shape, signed strides, and in-bounds offset.
    let rhs_descriptor = erased_raw_strided_ptr(
        dtype,
        typed_bytes(rhs_data),
        rhs.shape(),
        rhs.strides(),
        rhs.offset(),
    )
    .map_err(|error| Error::backend_source("elementwise_read_into", error))?;

    let out_dims = SmallVec::<[usize; 8]>::from_slice(out.shape());
    let out_strides = SmallVec::<[isize; 8]>::from_slice(out.strides());
    let out_offset = out.offset();
    let out_data = out.host_storage_mut()?;
    // INVARIANT: the copied output layout describes this uniquely borrowed
    // host storage, already validated as disjoint from every input.
    let mut out_descriptor = erased_raw_strided_mut(
        dtype,
        typed_bytes_mut(out_data),
        &out_dims,
        &out_strides,
        out_offset,
    )
    .map_err(|error| Error::backend_source("elementwise_read_into", error))?;
    erased_zip_into(
        dtype,
        op,
        ctx,
        &mut out_descriptor,
        &lhs_descriptor,
        &rhs_descriptor,
    )
    .map_err(|error| Error::backend_source("elementwise_read_into", error))
}

fn execute_one_shot_elementwise(
    op: ElementwiseReadOp,
    inputs: &[TensorRead<'_>],
    out: TensorWrite<'_>,
    ctx: &ExecContext,
) -> crate::Result<()> {
    let out = tensor_write_view(out);
    macro_rules! dispatch_map {
        ($map_op:expr) => {{
            let input = inputs[0].clone().tensor_view();
            match (input, out) {
                (TensorView::F32(input), TensorViewMut::F32(out)) => {
                    execute_one_shot_map(KernelDType::F32, $map_op, ctx, input, out)
                }
                (TensorView::F64(input), TensorViewMut::F64(out)) => {
                    execute_one_shot_map(KernelDType::F64, $map_op, ctx, input, out)
                }
                (TensorView::I32(input), TensorViewMut::I32(out)) => {
                    execute_one_shot_map(KernelDType::I32, $map_op, ctx, input, out)
                }
                (TensorView::I64(input), TensorViewMut::I64(out)) => {
                    execute_one_shot_map(KernelDType::I64, $map_op, ctx, input, out)
                }
                (TensorView::Bool(input), TensorViewMut::Bool(out)) => {
                    execute_one_shot_map(KernelDType::Bool, $map_op, ctx, input, out)
                }
                (TensorView::C32(input), TensorViewMut::C32(out)) => {
                    execute_one_shot_map(KernelDType::C32, $map_op, ctx, input, out)
                }
                (TensorView::C64(input), TensorViewMut::C64(out)) => {
                    execute_one_shot_map(KernelDType::C64, $map_op, ctx, input, out)
                }
                _ => unreachable!("one-shot eligibility validates matching dtypes"),
            }
        }};
    }
    macro_rules! dispatch_zip {
        ($zip_op:expr) => {{
            let lhs = inputs[0].clone().tensor_view();
            let rhs = inputs[1].clone().tensor_view();
            match (lhs, rhs, out) {
                (TensorView::F32(lhs), TensorView::F32(rhs), TensorViewMut::F32(out)) => {
                    execute_one_shot_zip(KernelDType::F32, $zip_op, ctx, lhs, rhs, out)
                }
                (TensorView::F64(lhs), TensorView::F64(rhs), TensorViewMut::F64(out)) => {
                    execute_one_shot_zip(KernelDType::F64, $zip_op, ctx, lhs, rhs, out)
                }
                (TensorView::I32(lhs), TensorView::I32(rhs), TensorViewMut::I32(out)) => {
                    execute_one_shot_zip(KernelDType::I32, $zip_op, ctx, lhs, rhs, out)
                }
                (TensorView::I64(lhs), TensorView::I64(rhs), TensorViewMut::I64(out)) => {
                    execute_one_shot_zip(KernelDType::I64, $zip_op, ctx, lhs, rhs, out)
                }
                (TensorView::C32(lhs), TensorView::C32(rhs), TensorViewMut::C32(out)) => {
                    execute_one_shot_zip(KernelDType::C32, $zip_op, ctx, lhs, rhs, out)
                }
                (TensorView::C64(lhs), TensorView::C64(rhs), TensorViewMut::C64(out)) => {
                    execute_one_shot_zip(KernelDType::C64, $zip_op, ctx, lhs, rhs, out)
                }
                _ => unreachable!("one-shot eligibility validates matching dtypes"),
            }
        }};
    }

    match op {
        ElementwiseReadOp::Add => dispatch_zip!(ErasedZipOp::Add),
        ElementwiseReadOp::Subtract => dispatch_zip!(ErasedZipOp::Subtract),
        ElementwiseReadOp::Multiply => dispatch_zip!(ErasedZipOp::Multiply),
        ElementwiseReadOp::Divide => dispatch_zip!(ErasedZipOp::Divide),
        ElementwiseReadOp::Negate => dispatch_map!(ErasedMapOp::Negate),
        ElementwiseReadOp::Conj => dispatch_map!(ErasedMapOp::Conj),
    }
}

/// Execute the shared elementwise-into path with an explicit replay context.
///
/// This is backend glue for implementations that own an execution context.
///
/// # Errors
///
/// Returns [`crate::Error::Validation`] when the input arity or tensor
/// metadata is invalid, or when the destination overlaps an input. Returns
/// [`crate::Error::BackendSource`] when an eligible strided replay fails.
/// Errors returned by `fallback` are preserved unchanged.
#[doc(hidden)]
pub fn elementwise_read_into_with_context(
    op: ElementwiseReadOp,
    inputs: &[TensorRead<'_>],
    out: TensorWrite<'_>,
    ctx: &ExecContext,
    fallback: impl FnOnce(&[TensorRead<'_>], TensorWrite<'_>) -> crate::Result<()>,
) -> crate::Result<()> {
    if inputs.len() != op.arity() {
        return Err(Error::invalid_argument(
            op.label(),
            "inputs",
            format!("expected {} inputs, got {}", op.arity(), inputs.len()),
        ));
    }
    validate_elementwise_output_disjoint(op, inputs, &out)?;
    if one_shot_eligible(op, inputs, &out) {
        execute_one_shot_elementwise(op, inputs, out, ctx)
    } else {
        fallback(inputs, out)
    }
}

/// Elementwise tensor operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorElementwise;
///
/// fn accepts_elementwise<B: TensorElementwise>(_backend: &mut B) {}
/// ```
pub trait TensorElementwise: TensorStructural {
    /// Execute an elementwise operation into caller-owned storage.
    ///
    /// Backend implementations normally override this hook only to inject
    /// their explicit execution context and buffer policy. The default uses a
    /// serial host one-shot kernel and preserves the allocating fallback for
    /// device storage, dtype promotion, and broadcasting.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] when `inputs` has the wrong arity,
    /// tensor metadata is invalid, or the destination overlaps an input.
    /// Returns [`crate::Error::BackendSource`] when the strided kernel rejects
    /// an eligible host operation. Errors from the allocating backend fallback
    /// are preserved unchanged.
    fn elementwise_read_into(
        &mut self,
        op: ElementwiseReadOp,
        inputs: &[TensorRead<'_>],
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        let ctx = ExecContext::serial();
        elementwise_read_into_with_context(op, inputs, out, &ctx, |inputs, out| {
            let result = match op {
                ElementwiseReadOp::Add => self.add_read(inputs[0].clone(), inputs[1].clone())?,
                ElementwiseReadOp::Subtract => {
                    self.sub_read(inputs[0].clone(), inputs[1].clone())?
                }
                ElementwiseReadOp::Multiply => {
                    self.mul_read(inputs[0].clone(), inputs[1].clone())?
                }
                ElementwiseReadOp::Negate => self.neg_read(inputs[0].clone())?,
                ElementwiseReadOp::Conj => self.conj_read(inputs[0].clone())?,
                ElementwiseReadOp::Divide => self.div_read(inputs[0].clone(), inputs[1].clone())?,
            };
            self.copy_read_into(TensorRead::from_tensor(&result), out)
        })
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn add(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;

    /// Elementwise addition accepting either owned tensors or borrowed views.
    ///
    /// Backends that implement this method must not silently move data across
    /// devices. A backend that cannot consume views should return an explicit
    /// backend error rather than materializing or transferring implicitly.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorElementwise, TensorRead};
    ///
    /// fn add_owned<B: TensorElementwise>(
    ///     backend: &mut B,
    ///     lhs: &Tensor,
    ///     rhs: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.add_read(TensorRead::from_tensor(lhs), TensorRead::from_tensor(rhs))
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn add_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.add(read_tensor("add", lhs)?, read_tensor("add", rhs)?)
    }

    /// Overwrite caller-provided output with elementwise addition.
    ///
    /// `_into` methods never accumulate into the previous output value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorElementwise, TensorWrite};
    ///
    /// fn add_into<B: TensorElementwise>(
    ///     backend: &mut B,
    ///     lhs: &Tensor,
    ///     rhs: &Tensor,
    ///     mut out: Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.add_into(lhs, rhs, TensorWrite::from_tensor(&mut out))?;
    ///     Ok(out)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn add_into(&mut self, lhs: &Tensor, rhs: &Tensor, out: TensorWrite<'_>) -> crate::Result<()> {
        self.add_read_into(
            TensorRead::from_tensor(lhs),
            TensorRead::from_tensor(rhs),
            out,
        )
    }

    /// Overwrite caller-provided output with elementwise addition from reads.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{TensorElementwise, TensorRead, TensorWrite};
    ///
    /// fn add_read_into<B: TensorElementwise>(
    ///     backend: &mut B,
    ///     lhs: TensorRead<'_>,
    ///     rhs: TensorRead<'_>,
    ///     out: TensorWrite<'_>,
    /// ) -> tenferro_tensor::Result<()> {
    ///     backend.add_read_into(lhs, rhs, out)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn add_read_into(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        self.elementwise_read_into(ElementwiseReadOp::Add, &[lhs, rhs], out)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sub(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;

    /// Elementwise subtraction accepting either owned tensors or borrowed views.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorElementwise, TensorRead};
    ///
    /// fn sub_owned<B: TensorElementwise>(
    ///     backend: &mut B,
    ///     lhs: &Tensor,
    ///     rhs: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.sub_read(TensorRead::from_tensor(lhs), TensorRead::from_tensor(rhs))
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sub_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.sub(read_tensor("sub", lhs)?, read_tensor("sub", rhs)?)
    }

    /// Overwrite caller-provided output with elementwise subtraction.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sub_into(&mut self, lhs: &Tensor, rhs: &Tensor, out: TensorWrite<'_>) -> crate::Result<()> {
        self.sub_read_into(
            TensorRead::from_tensor(lhs),
            TensorRead::from_tensor(rhs),
            out,
        )
    }

    /// Overwrite caller-provided output with elementwise subtraction from reads.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sub_read_into(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        self.elementwise_read_into(ElementwiseReadOp::Subtract, &[lhs, rhs], out)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn mul(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn mul_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.mul(read_tensor("mul", lhs)?, read_tensor("mul", rhs)?)
    }

    /// Overwrite caller-provided output with elementwise multiplication.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn mul_into(&mut self, lhs: &Tensor, rhs: &Tensor, out: TensorWrite<'_>) -> crate::Result<()> {
        self.mul_read_into(
            TensorRead::from_tensor(lhs),
            TensorRead::from_tensor(rhs),
            out,
        )
    }

    /// Overwrite caller-provided output with elementwise multiplication from reads.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn mul_read_into(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        self.elementwise_read_into(ElementwiseReadOp::Multiply, &[lhs, rhs], out)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn neg(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn neg_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.neg(read_tensor("neg", input)?)
    }

    /// Overwrite caller-provided output with elementwise negation.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn neg_into(&mut self, input: &Tensor, out: TensorWrite<'_>) -> crate::Result<()> {
        self.neg_read_into(TensorRead::from_tensor(input), out)
    }

    /// Overwrite caller-provided output with elementwise negation from a read.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn neg_read_into(&mut self, input: TensorRead<'_>, out: TensorWrite<'_>) -> crate::Result<()> {
        self.elementwise_read_into(ElementwiseReadOp::Negate, &[input], out)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn conj(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn conj_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.conj(read_tensor("conj", input)?)
    }

    /// Overwrite caller-provided output with elementwise conjugation.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn conj_into(&mut self, input: &Tensor, out: TensorWrite<'_>) -> crate::Result<()> {
        self.conj_read_into(TensorRead::from_tensor(input), out)
    }

    /// Overwrite caller-provided output with elementwise conjugation from a read.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn conj_read_into(&mut self, input: TensorRead<'_>, out: TensorWrite<'_>) -> crate::Result<()> {
        self.elementwise_read_into(ElementwiseReadOp::Conj, &[input], out)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn div(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn div_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.div(read_tensor("div", lhs)?, read_tensor("div", rhs)?)
    }

    /// Overwrite caller-provided output with elementwise division.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn div_into(&mut self, lhs: &Tensor, rhs: &Tensor, out: TensorWrite<'_>) -> crate::Result<()> {
        self.div_read_into(
            TensorRead::from_tensor(lhs),
            TensorRead::from_tensor(rhs),
            out,
        )
    }

    /// Overwrite caller-provided output with elementwise division from reads.
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn div_read_into(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        self.elementwise_read_into(ElementwiseReadOp::Divide, &[lhs, rhs], out)
    }

    /// Elementwise remainder.
    ///
    /// The default is an explicit unsupported error so backend implementors can
    /// opt in without silent fallback.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorElementwise};
    ///
    /// fn rem_owned<B: TensorElementwise>(
    ///     backend: &mut B,
    ///     lhs: &Tensor,
    ///     rhs: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.rem(lhs, rhs)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn rem(&mut self, lhs: &Tensor, _rhs: &Tensor) -> crate::Result<Tensor> {
        Err(crate::Error::unsupported(
            "rem",
            format!("backend does not implement rem for dtype {:?}", lhs.dtype()),
        ))
    }

    /// Elementwise remainder accepting owned tensors or borrowed views.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorElementwise, TensorRead};
    ///
    /// fn rem_read<B: TensorElementwise>(
    ///     backend: &mut B,
    ///     lhs: &Tensor,
    ///     rhs: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.rem_read(TensorRead::from_tensor(lhs), TensorRead::from_tensor(rhs))
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn rem_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.rem(read_tensor("rem", lhs)?, read_tensor("rem", rhs)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn abs(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn abs_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.abs(read_tensor("abs", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sign(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sign_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.sign(read_tensor("sign", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn maximum(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn maximum_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.maximum(read_tensor("maximum", lhs)?, read_tensor("maximum", rhs)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn minimum(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn minimum_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.minimum(read_tensor("minimum", lhs)?, read_tensor("minimum", rhs)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn compare(&mut self, lhs: &Tensor, rhs: &Tensor, dir: &CompareDir) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn compare_read(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        dir: &CompareDir,
    ) -> crate::Result<Tensor> {
        self.compare(
            read_tensor("compare", lhs)?,
            read_tensor("compare", rhs)?,
            dir,
        )
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn select(
        &mut self,
        pred: &Tensor,
        on_true: &Tensor,
        on_false: &Tensor,
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn select_read(
        &mut self,
        pred: TensorRead<'_>,
        on_true: TensorRead<'_>,
        on_false: TensorRead<'_>,
    ) -> crate::Result<Tensor> {
        self.select(
            read_tensor("select", pred)?,
            read_tensor("select", on_true)?,
            read_tensor("select", on_false)?,
        )
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn clamp(&mut self, input: &Tensor, lower: &Tensor, upper: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn clamp_read(
        &mut self,
        input: TensorRead<'_>,
        lower: TensorRead<'_>,
        upper: TensorRead<'_>,
    ) -> crate::Result<Tensor> {
        self.clamp(
            read_tensor("clamp", input)?,
            read_tensor("clamp", lower)?,
            read_tensor("clamp", upper)?,
        )
    }
}

/// Analytic unary and binary tensor operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorAnalytic;
///
/// fn accepts_analytic<B: TensorAnalytic>(_backend: &mut B) {}
/// ```
pub trait TensorAnalytic {
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn exp(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn exp_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.exp(read_tensor("exp", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn log(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn log_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.log(read_tensor("log", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sin(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sin_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.sin(read_tensor("sin", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn cos(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn cos_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.cos(read_tensor("cos", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn tanh(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn tanh_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.tanh(read_tensor("tanh", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sqrt(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn sqrt_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.sqrt(read_tensor("sqrt", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn rsqrt(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn rsqrt_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.rsqrt(read_tensor("rsqrt", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn pow(&mut self, lhs: &Tensor, rhs: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn pow_read(&mut self, lhs: TensorRead<'_>, rhs: TensorRead<'_>) -> crate::Result<Tensor> {
        self.pow(read_tensor("pow", lhs)?, read_tensor("pow", rhs)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn expm1(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn expm1_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.expm1(read_tensor("expm1", input)?)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn log1p(&mut self, input: &Tensor) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn log1p_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        self.log1p(read_tensor("log1p", input)?)
    }
}

/// Shape, layout, and dtype transformation operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorStructural;
///
/// fn accepts_structural<B: TensorStructural>(_backend: &mut B) {}
/// ```
pub trait TensorStructural {
    /// Materialize an owned tensor or borrowed view into fresh compact storage.
    ///
    /// The result has the input's shape and dtype, uses compact column-major
    /// layout, and remains in the input's placement. This operation is a
    /// same-placement canonicalization boundary, never an implicit host/device
    /// transfer. The conservative default accepts only compact host-owned
    /// tensors and clones them; it rejects views, backend buffers, and device
    /// placement because only an owning backend can materialize those safely.
    ///
    /// Backend overrides may accept strided views. CUDA accepts numeric and
    /// complex views on its active device, including arbitrary valid strides,
    /// but currently reports an explicit unsupported-dtype error for `Bool`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{DType, Tensor, TensorRead, TensorStructural};
    ///
    /// struct HostDefaults;
    /// impl TensorStructural for HostDefaults {
    ///     fn transpose(&mut self, _: &Tensor, _: &[usize]) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn reshape(&mut self, _: &Tensor, _: &[usize]) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn broadcast_in_dim(&mut self, _: &Tensor, _: &[usize], _: &[usize]) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn cast(&mut self, _: &Tensor, _: DType) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn extract_diagonal(&mut self, _: &Tensor, _: usize, _: usize) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn embed_diagonal(&mut self, _: &Tensor, _: usize, _: usize) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn tril(&mut self, _: &Tensor, _: i64) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn triu(&mut self, _: &Tensor, _: i64) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    /// }
    ///
    /// let input = Tensor::from_vec_col_major(vec![2], vec![1_i32, 2])?;
    /// let mut backend = HostDefaults;
    /// let structural: &mut dyn TensorStructural = &mut backend;
    /// let output = structural.to_contiguous_read(TensorRead::from_tensor(&input))?;
    /// assert_eq!(output.shape(), &[2]);
    /// assert_eq!(output.as_slice::<i32>()?, &[1, 2]);
    /// # Ok::<(), tenferro_tensor::Error>(())
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn to_contiguous_read(&mut self, input: TensorRead<'_>) -> crate::Result<Tensor> {
        match input {
            TensorRead::Tensor(input) => {
                if input.is_backend_buffer()
                    || !matches!(
                        input.placement().memory_kind,
                        crate::MemoryKind::PinnedHost | crate::MemoryKind::UnpinnedHost
                    )
                {
                    return Err(crate::Error::runtime_state(
                        "to_contiguous_read",
                        "default materialization accepts only host-owned tensors; use the storage's owning backend",
                    ));
                }
                input.duplicate()
            }
            TensorRead::View(view) => {
                if view.backend_family().is_some()
                    || !matches!(
                        view.placement().memory_kind,
                        crate::MemoryKind::PinnedHost | crate::MemoryKind::UnpinnedHost
                    )
                {
                    return Err(crate::Error::runtime_state(
                        "to_contiguous_read",
                        "default materialization accepts only host-owned tensors; use the storage's owning backend",
                    ));
                }
                view.duplicate()
            }
        }
    }

    /// Overwrite caller-provided storage from a readable tensor or view.
    ///
    /// Source and destination must have identical dtype and shape and belong to
    /// the executing backend's placement. The destination is not resized, and
    /// every logical destination element is overwritten without reading its old
    /// value. Source and destination allocations must not alias. Implementations
    /// must not materialize through host memory or perform an implicit transfer.
    ///
    /// CPU accepts arbitrary valid source and destination strides and performs
    /// no tensor allocation. CUDA currently accepts only a compact column-major
    /// source with offset zero covering its full allocation; CUDA destinations
    /// may be arbitrary valid non-overlapping views. CUDA rejects aliased
    /// allocations and currently reports an explicit unsupported-dtype error
    /// for `Bool`. The conservative default is explicitly unsupported.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{DType, Tensor, TensorRead, TensorStructural, TensorWrite};
    ///
    /// struct ConservativeDefaults;
    /// impl TensorStructural for ConservativeDefaults {
    ///     fn transpose(&mut self, _: &Tensor, _: &[usize]) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn reshape(&mut self, _: &Tensor, _: &[usize]) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn broadcast_in_dim(&mut self, _: &Tensor, _: &[usize], _: &[usize]) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn cast(&mut self, _: &Tensor, _: DType) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn extract_diagonal(&mut self, _: &Tensor, _: usize, _: usize) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn embed_diagonal(&mut self, _: &Tensor, _: usize, _: usize) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn tril(&mut self, _: &Tensor, _: i64) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    ///     fn triu(&mut self, _: &Tensor, _: i64) -> tenferro_tensor::Result<Tensor> { unimplemented!() }
    /// }
    ///
    /// let src = Tensor::from_vec_col_major(vec![2], vec![1_i32, 2])?;
    /// let mut dst = Tensor::from_vec_col_major(vec![2], vec![0_i32, 0])?;
    /// let mut backend = ConservativeDefaults;
    /// let structural: &mut dyn TensorStructural = &mut backend;
    /// let error = structural.copy_read_into(
    ///     TensorRead::from_tensor(&src),
    ///     TensorWrite::from_tensor(&mut dst),
    /// ).unwrap_err();
    /// assert!(error.to_string().contains("unsupported"));
    /// assert_eq!(dst.as_slice::<i32>()?, &[0, 0]);
    /// # Ok::<(), tenferro_tensor::Error>(())
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn copy_read_into(&mut self, _src: TensorRead<'_>, _dst: TensorWrite<'_>) -> crate::Result<()> {
        Err(crate::Error::unsupported(
            "copy_read_into",
            "backend-owned runtime copy is unsupported by this backend",
        ))
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn transpose(&mut self, input: &Tensor, perm: &[usize]) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn transpose_read(&mut self, input: TensorRead<'_>, perm: &[usize]) -> crate::Result<Tensor> {
        self.transpose(read_tensor("transpose", input)?, perm)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reshape(&mut self, input: &Tensor, shape: &[usize]) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reshape_read(&mut self, input: TensorRead<'_>, shape: &[usize]) -> crate::Result<Tensor> {
        self.reshape(read_tensor("reshape", input)?, shape)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn broadcast_in_dim(
        &mut self,
        input: &Tensor,
        shape: &[usize],
        dims: &[usize],
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn broadcast_in_dim_read(
        &mut self,
        input: TensorRead<'_>,
        shape: &[usize],
        dims: &[usize],
    ) -> crate::Result<Tensor> {
        self.broadcast_in_dim(read_tensor("broadcast_in_dim", input)?, shape, dims)
    }

    /// Cast a tensor to another dtype using explicit dtype projection.
    ///
    /// Backends may truncate, narrow precision, project complex values, or use
    /// boolean truthiness according to their documented cast support.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{DType, Tensor, TensorStructural};
    ///
    /// fn cast_to_i32<B: TensorStructural>(
    ///     backend: &mut B,
    ///     input: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.cast(input, DType::I32)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn cast(&mut self, input: &Tensor, to: crate::DType) -> crate::Result<Tensor>;

    /// Convert a tensor to another dtype using checked dtype conversion.
    ///
    /// `convert` accepts only conversions allowed by tenferro's dtype-promotion
    /// lattice. Use [`TensorStructural::cast`] for explicit lossy projection.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{DType, Tensor, TensorStructural};
    ///
    /// fn convert_to_f64<B: TensorStructural>(
    ///     backend: &mut B,
    ///     input: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.convert(input, DType::F64)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn convert(&mut self, input: &Tensor, to: crate::DType) -> crate::Result<Tensor> {
        validate_convert_dtype("convert", input.dtype(), to)?;
        self.cast(input, to)
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn extract_diagonal(
        &mut self,
        input: &Tensor,
        axis_a: usize,
        axis_b: usize,
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn embed_diagonal(
        &mut self,
        input: &Tensor,
        axis_a: usize,
        axis_b: usize,
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn tril(&mut self, input: &Tensor, k: i64) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn triu(&mut self, input: &Tensor, k: i64) -> crate::Result<Tensor>;
}

/// Reduction operations.
///
/// Reducing over an axis whose extent is zero returns an error for every
/// reduction operation. Passing an empty `axes` slice is a no-op for the public
/// reductions and returns the input values unchanged. Internal mapped
/// reductions document their own empty-axis semantics.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorReduction;
///
/// fn accepts_reduction<B: TensorReduction>(_backend: &mut B) {}
/// ```
pub trait TensorReduction {
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_sum(&mut self, input: &Tensor, axes: &[usize]) -> crate::Result<Tensor>;

    /// Sum elements across axes from an owned tensor or borrowed view.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorRead, TensorReduction};
    ///
    /// fn sum_owned<B: TensorReduction>(
    ///     backend: &mut B,
    ///     input: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.reduce_sum_read(TensorRead::from_tensor(input), &[0])
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_sum_read(&mut self, input: TensorRead<'_>, axes: &[usize]) -> crate::Result<Tensor> {
        match input.as_tensor() {
            Some(input) => self.reduce_sum(input, axes),
            None => Err(crate::Error::unsupported(
                "reduce_sum",
                "backend does not accept borrowed tensor views at this execution boundary",
            )),
        }
    }

    /// Sum elementwise squares across axes.
    ///
    /// This execution hook is used by composite operations that avoid a
    /// materialized square. Empty axes produce an elementwise square. Backends
    /// that support this optimized path must override the hook directly.
    ///
    /// # Errors
    ///
    /// Returns the typed validation, unsupported, runtime-state, or backend
    /// error produced by multiplication or reduction.
    #[doc(hidden)]
    fn reduce_sum_squares_read(
        &mut self,
        _input: TensorRead<'_>,
        _axes: &[usize],
    ) -> crate::Result<Tensor> {
        Err(crate::Error::unsupported(
            "reduce_sum_squares",
            "backend does not implement fused sum-of-squares reduction",
        ))
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_prod(&mut self, input: &Tensor, axes: &[usize]) -> crate::Result<Tensor>;

    /// Multiply elements across axes from an owned tensor or borrowed view.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorRead, TensorReduction};
    ///
    /// fn prod_owned<B: TensorReduction>(
    ///     backend: &mut B,
    ///     input: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.reduce_prod_read(TensorRead::from_tensor(input), &[0])
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_prod_read(&mut self, input: TensorRead<'_>, axes: &[usize]) -> crate::Result<Tensor> {
        match input.as_tensor() {
            Some(input) => self.reduce_prod(input, axes),
            None => Err(crate::Error::unsupported(
                "reduce_prod",
                "backend does not accept borrowed tensor views at this execution boundary",
            )),
        }
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_max(&mut self, input: &Tensor, axes: &[usize]) -> crate::Result<Tensor>;

    /// Take maximum values across axes from an owned tensor or borrowed view.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorRead, TensorReduction};
    ///
    /// fn max_owned<B: TensorReduction>(
    ///     backend: &mut B,
    ///     input: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.reduce_max_read(TensorRead::from_tensor(input), &[0])
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_max_read(&mut self, input: TensorRead<'_>, axes: &[usize]) -> crate::Result<Tensor> {
        match input.as_tensor() {
            Some(input) => self.reduce_max(input, axes),
            None => Err(crate::Error::unsupported(
                "reduce_max",
                "backend does not accept borrowed tensor views at this execution boundary",
            )),
        }
    }

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_min(&mut self, input: &Tensor, axes: &[usize]) -> crate::Result<Tensor>;

    /// Take minimum values across axes from an owned tensor or borrowed view.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{Tensor, TensorRead, TensorReduction};
    ///
    /// fn min_owned<B: TensorReduction>(
    ///     backend: &mut B,
    ///     input: &Tensor,
    /// ) -> tenferro_tensor::Result<Tensor> {
    ///     backend.reduce_min_read(TensorRead::from_tensor(input), &[0])
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reduce_min_read(&mut self, input: TensorRead<'_>, axes: &[usize]) -> crate::Result<Tensor> {
        match input.as_tensor() {
            Some(input) => self.reduce_min(input, axes),
            None => Err(crate::Error::unsupported(
                "reduce_min",
                "backend does not accept borrowed tensor views at this execution boundary",
            )),
        }
    }
}

/// Dot-general operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorDot;
///
/// fn accepts_dot<B: TensorDot>(_backend: &mut B) {}
/// ```
pub trait TensorDot: TensorElementwise {
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dot_general(
        &mut self,
        lhs: &Tensor,
        rhs: &Tensor,
        config: &DotGeneralConfig,
    ) -> crate::Result<Tensor>;

    #[doc(hidden)]
    fn dot_general_read(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
    ) -> crate::Result<Tensor> {
        match (lhs.as_tensor(), rhs.as_tensor()) {
            (Some(lhs), Some(rhs)) => self.dot_general(lhs, rhs, config),
            _ => {
                let lhs = self.to_contiguous_read(lhs)?;
                let rhs = self.to_contiguous_read(rhs)?;
                self.dot_general(&lhs, &rhs, config)
            }
        }
    }

    /// Overwrite caller-provided output with dot-general from read inputs.
    ///
    /// This is the dot/GEMM spelling of `_into`: the previous output value is
    /// not read. Use [`TensorDot::dot_general_read_into_accum`] for explicit
    /// read-modify-write accumulation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{DotGeneralConfig, TensorDot, TensorRead, TensorWrite};
    ///
    /// fn dot_into<B: TensorDot>(
    ///     backend: &mut B,
    ///     lhs: TensorRead<'_>,
    ///     rhs: TensorRead<'_>,
    ///     config: &DotGeneralConfig,
    ///     out: TensorWrite<'_>,
    /// ) -> tenferro_tensor::Result<()> {
    ///     backend.dot_general_read_into(lhs, rhs, config, out)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dot_general_read_into(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        let accumulation = DotGeneralAccumulation::overwrite(lhs.dtype())?;
        self.dot_general_read_into_accum(lhs, rhs, config, accumulation, out)
    }

    #[doc(hidden)]
    fn dot_general_with_conj(
        &mut self,
        lhs: &Tensor,
        rhs: &Tensor,
        config: &DotGeneralConfig,
        lhs_conj: bool,
        rhs_conj: bool,
    ) -> crate::Result<Tensor> {
        if !lhs_conj && !rhs_conj {
            return self.dot_general(lhs, rhs, config);
        }

        let lhs_tmp;
        let lhs_ref = if lhs_conj {
            lhs_tmp = self.conj(lhs)?;
            &lhs_tmp
        } else {
            lhs
        };
        let rhs_tmp;
        let rhs_ref = if rhs_conj {
            rhs_tmp = self.conj(rhs)?;
            &rhs_tmp
        } else {
            rhs
        };
        self.dot_general(lhs_ref, rhs_ref, config)
    }

    #[allow(clippy::too_many_arguments)]
    #[doc(hidden)]
    fn dot_general_with_conj_read(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        lhs_conj: bool,
        rhs_conj: bool,
    ) -> crate::Result<Tensor> {
        if !lhs_conj && !rhs_conj {
            return self.dot_general_read(lhs, rhs, config);
        }

        let lhs_tmp;
        let lhs_ref = if let Some(tensor) = lhs.as_tensor() {
            tensor
        } else {
            lhs_tmp = self.to_contiguous_read(lhs)?;
            &lhs_tmp
        };
        let rhs_tmp;
        let rhs_ref = if let Some(tensor) = rhs.as_tensor() {
            tensor
        } else {
            rhs_tmp = self.to_contiguous_read(rhs)?;
            &rhs_tmp
        };
        self.dot_general_with_conj(lhs_ref, rhs_ref, config, lhs_conj, rhs_conj)
    }

    /// Apply scaled dot-general accumulation into caller-provided output.
    ///
    /// This is explicitly read-modify-write when `accumulation.beta` is nonzero:
    /// `out = alpha * dot_general(lhs, rhs) + beta * out`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{
    ///     DotGeneralAccumulation, DotGeneralConfig, TensorDot, TensorRead, TensorWrite,
    /// };
    ///
    /// fn dot_add_to<B: TensorDot>(
    ///     backend: &mut B,
    ///     lhs: TensorRead<'_>,
    ///     rhs: TensorRead<'_>,
    ///     config: &DotGeneralConfig,
    ///     out: TensorWrite<'_>,
    /// ) -> tenferro_tensor::Result<()> {
    ///     let accumulation = DotGeneralAccumulation::add_to(lhs.dtype())?;
    ///     backend.dot_general_read_into_accum(lhs, rhs, config, accumulation, out)
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dot_general_read_into_accum(
        &mut self,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        accumulation: DotGeneralAccumulation,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        dot_general_accum_via_temp(self, lhs, rhs, config, accumulation, out)
    }
}

/// Session-scoped cached dot-general operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::BackendSession;
///
/// fn accepts_session_dot<S: BackendSession + ?Sized>(_session: &mut S) {}
/// ```
pub trait SessionCachedDot: TensorDot {
    #[doc(hidden)]
    fn dot_general_cached(
        &mut self,
        _cache_slot: Option<usize>,
        lhs: &Tensor,
        rhs: &Tensor,
        config: &DotGeneralConfig,
    ) -> crate::Result<Tensor> {
        self.dot_general(lhs, rhs, config)
    }

    #[doc(hidden)]
    fn dot_general_read_cached(
        &mut self,
        cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
    ) -> crate::Result<Tensor> {
        match (lhs.as_tensor(), rhs.as_tensor()) {
            (Some(lhs), Some(rhs)) => self.dot_general_cached(cache_slot, lhs, rhs, config),
            _ => {
                let lhs = self.to_contiguous_read(lhs)?;
                let rhs = self.to_contiguous_read(rhs)?;
                self.dot_general_cached(cache_slot, &lhs, &rhs, config)
            }
        }
    }

    // Mirrors the dot-general signature plus runtime-cache metadata.
    #[allow(clippy::too_many_arguments)]
    #[doc(hidden)]
    fn dot_general_with_conj_cached(
        &mut self,
        _cache_slot: Option<usize>,
        lhs: &Tensor,
        rhs: &Tensor,
        config: &DotGeneralConfig,
        lhs_conj: bool,
        rhs_conj: bool,
    ) -> crate::Result<Tensor> {
        self.dot_general_with_conj(lhs, rhs, config, lhs_conj, rhs_conj)
    }

    // Mirrors the dot-general read signature plus runtime-cache metadata.
    #[allow(clippy::too_many_arguments)]
    #[doc(hidden)]
    fn dot_general_with_conj_read_cached(
        &mut self,
        cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        lhs_conj: bool,
        rhs_conj: bool,
    ) -> crate::Result<Tensor> {
        if !lhs_conj && !rhs_conj {
            return self.dot_general_read_cached(cache_slot, lhs, rhs, config);
        }

        let lhs_tmp;
        let lhs_ref = if let Some(tensor) = lhs.as_tensor() {
            tensor
        } else {
            lhs_tmp = self.to_contiguous_read(lhs)?;
            &lhs_tmp
        };
        let rhs_tmp;
        let rhs_ref = if let Some(tensor) = rhs.as_tensor() {
            tensor
        } else {
            rhs_tmp = self.to_contiguous_read(rhs)?;
            &rhs_tmp
        };
        self.dot_general_with_conj_cached(cache_slot, lhs_ref, rhs_ref, config, lhs_conj, rhs_conj)
    }

    /// Apply session-cached scaled dot-general accumulation into output.
    ///
    /// The cache slot is session-local metadata; `accumulation` still controls
    /// overwrite versus read-modify-write semantics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{
    ///     DotGeneralAccumulation, DotGeneralConfig, SessionCachedDot, TensorRead, TensorWrite,
    /// };
    ///
    /// fn session_cached_dot_add_to<S: SessionCachedDot + ?Sized>(
    ///     session: &mut S,
    ///     lhs: TensorRead<'_>,
    ///     rhs: TensorRead<'_>,
    ///     config: &DotGeneralConfig,
    ///     out: TensorWrite<'_>,
    /// ) -> tenferro_tensor::Result<()> {
    ///     let accumulation = DotGeneralAccumulation::add_to(lhs.dtype())?;
    ///     session.dot_general_read_into_accum_cached(
    ///         Some(0),
    ///         lhs,
    ///         rhs,
    ///         config,
    ///         accumulation,
    ///         out,
    ///     )
    /// }
    /// ```
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dot_general_read_into_accum_cached(
        &mut self,
        _cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        accumulation: DotGeneralAccumulation,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        self.dot_general_read_into_accum(lhs, rhs, config, accumulation, out)
    }

    #[doc(hidden)]
    fn grouped_gemm_cached(
        &mut self,
        _cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &GroupedGemmConfig<'_>,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        grouped_gemm_default(self, lhs, rhs, config, out)
    }
}

/// Indexing, slicing, and padding operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorIndexing;
///
/// fn accepts_indexing<B: TensorIndexing>(_backend: &mut B) {}
/// ```
pub trait TensorIndexing {
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn gather(
        &mut self,
        operand: &Tensor,
        start_indices: &Tensor,
        config: &GatherConfig,
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn scatter(
        &mut self,
        operand: &Tensor,
        scatter_indices: &Tensor,
        updates: &Tensor,
        config: &ScatterConfig,
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. In
    /// particular, a limit greater than the corresponding input dimension is
    /// reported as [`crate::ValidationError::InvalidArgument`] with the
    /// `"configuration"` argument. It returns [`crate::Error::BackendFailure`]
    /// or [`crate::Error::BackendSource`] when backend execution or storage
    /// access cannot provide the requested result.
    fn slice(&mut self, input: &Tensor, config: &SliceConfig) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dynamic_slice(
        &mut self,
        input: &Tensor,
        starts: &Tensor,
        slice_sizes: &[usize],
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dynamic_update_slice(
        &mut self,
        operand: &Tensor,
        update: &Tensor,
        starts: &Tensor,
    ) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn pad(&mut self, input: &Tensor, config: &PadConfig) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn concatenate(&mut self, inputs: &[&Tensor], axis: usize) -> crate::Result<Tensor>;
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn reverse(&mut self, input: &Tensor, axes: &[usize]) -> crate::Result<Tensor>;
}

/// Backend-owned canonicalization for typed tensor views.
///
/// Implementations must preserve the input placement family. CPU backends
/// canonicalize host views through explicit host copies and reject backend
/// buffers with a diagnostic that asks the caller to download first. GPU
/// backends canonicalize GPU-resident views on the same device and reject host
/// buffers with an upload hint.
///
/// [`TensorViewCanonicalization::copy_into`] requires source and destination
/// shapes, scalar dtypes, and placement families to match. The destination
/// view must be internally non-overlapping, and source and destination backing
/// allocations must not alias unless an implementation explicitly documents
/// and supports that case. Implementations may reject layouts their native
/// kernels cannot consume.
///
/// CUDA currently accepts only a compact column-major source view with offset
/// zero that covers its full allocation; arbitrary-stride destinations remain
/// supported. Canonicalization and copying are same-placement operations: they
/// must not perform hidden host/device transfers or silently materialize an
/// unsupported source layout.
///
/// This trait is intentionally separate from [`BackendSession`] so generic
/// typed methods do not change the object-safety contract of `dyn BackendSession`.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::{DynRank, TensorViewCanonicalization, TypedTensor};
///
/// fn compact_i32<B: TensorViewCanonicalization<i32, DynRank>>(
///     backend: &mut B,
///     tensor: &TypedTensor<i32>,
/// ) -> tenferro_tensor::Result<TypedTensor<i32>> {
///     backend.to_contiguous(&tensor.as_view())
/// }
///
/// fn copy_i32<B: TensorViewCanonicalization<i32, DynRank>>(
///     backend: &mut B,
///     src: &TypedTensor<i32>,
///     dst: &mut TypedTensor<i32>,
/// ) -> tenferro_tensor::Result<()> {
///     backend.copy_into(&src.as_view(), &mut dst.as_view_mut())
/// }
/// ```
pub trait TensorViewCanonicalization<T: TensorScalar, R: TensorRank> {
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn to_contiguous(
        &mut self,
        view: &TypedTensorView<'_, T, R>,
    ) -> crate::Result<TypedTensor<T, R>>;

    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn copy_into(
        &mut self,
        src: &TypedTensorView<'_, T, R>,
        dst: &mut TypedTensorViewMut<'_, T, R>,
    ) -> crate::Result<()>;
}

/// Optional elementwise fusion execution.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorFusion;
///
/// fn accepts_fusion<B: TensorFusion>(_backend: &mut B) {}
/// ```
pub trait TensorFusion {
    #[doc(hidden)]
    fn execute_elementwise_fusion(
        &mut self,
        _inputs: &[&Tensor],
        _plan: &ElementwiseFusionPlan,
    ) -> crate::Result<Option<Vec<Tensor>>> {
        Ok(None)
    }

    #[doc(hidden)]
    #[allow(clippy::too_many_arguments)]
    fn execute_broadcast_multiply(
        &mut self,
        _lhs: TensorRead<'_>,
        _lhs_shape: &[usize],
        _lhs_dims: &[usize],
        _rhs: TensorRead<'_>,
        _rhs_shape: &[usize],
        _rhs_dims: &[usize],
    ) -> crate::Result<Option<Tensor>> {
        Ok(None)
    }

    #[doc(hidden)]
    #[allow(clippy::too_many_arguments)]
    fn execute_broadcast_multiply_value(
        &mut self,
        lhs: TensorRead<'_>,
        lhs_shape: &[usize],
        lhs_dims: &[usize],
        rhs: TensorRead<'_>,
        rhs_shape: &[usize],
        rhs_dims: &[usize],
    ) -> crate::Result<Option<TensorValue>> {
        self.execute_broadcast_multiply(lhs, lhs_shape, lhs_dims, rhs, rhs_shape, rhs_dims)
            .map(|tensor| tensor.map(TensorValue::from_tensor))
    }
}

/// Backend buffer lifecycle operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorBuffer;
///
/// fn accepts_buffer<B: TensorBuffer>(_backend: &mut B) {}
/// ```
pub trait TensorBuffer {
    fn reclaim_buffer(&mut self, _tensor: Tensor) {}
}

/// Device transfer operations on backend boundaries.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorDeviceTransfer;
///
/// fn accepts_transfer<B: TensorDeviceTransfer>(_backend: &mut B) {}
/// ```
pub trait TensorDeviceTransfer {
    /// Explicitly copy a provider-owned read target into host storage.
    ///
    /// Implementations must not return the input unchanged or stage through an
    /// unrelated provider. A backend that cannot transfer the requested read
    /// target returns a typed unsupported error.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Unsupported`] when the implementation cannot
    /// perform the requested transfer, or a typed validation/backend error when
    /// the source cannot be read.
    fn download_to_host(&mut self, tensor: TensorRead<'_>) -> crate::Result<Tensor>;

    /// Explicitly copy a host read target into provider storage.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Unsupported`] when the implementation cannot
    /// perform the requested transfer, or a typed validation/backend error when
    /// the source cannot be read.
    fn upload_host_tensor(&mut self, tensor: TensorRead<'_>) -> crate::Result<Tensor>;
}

/// Runtime cache associated with a backend.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::BackendRuntimeCache;
///
/// fn accepts_runtime_cache<B: BackendRuntimeCache>(_backend: &B) {}
/// ```
pub trait BackendRuntimeCache {
    #[doc(hidden)]
    type RuntimeCache: RuntimeCacheControl + Send + Sync + 'static;
}

/// Backend-owned cached dot-general operations.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::BackendCachedDot;
///
/// fn accepts_backend_cached_dot<B: BackendCachedDot>(_backend: &mut B) {}
/// ```
pub trait BackendCachedDot: BackendRuntimeCache + TensorDot {
    #[doc(hidden)]
    fn dot_general_cached(
        &mut self,
        _cache: &mut Self::RuntimeCache,
        _cache_slot: Option<usize>,
        lhs: &Tensor,
        rhs: &Tensor,
        config: &DotGeneralConfig,
    ) -> crate::Result<Tensor> {
        self.dot_general(lhs, rhs, config)
    }

    #[doc(hidden)]
    fn dot_general_read_cached(
        &mut self,
        cache: &mut Self::RuntimeCache,
        cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
    ) -> crate::Result<Tensor> {
        match (lhs.as_tensor(), rhs.as_tensor()) {
            (Some(lhs), Some(rhs)) => self.dot_general_cached(cache, cache_slot, lhs, rhs, config),
            _ => {
                let lhs = self.to_contiguous_read(lhs)?;
                let rhs = self.to_contiguous_read(rhs)?;
                self.dot_general_cached(cache, cache_slot, &lhs, &rhs, config)
            }
        }
    }

    // Mirrors the dot-general signature plus runtime-cache metadata.
    #[allow(clippy::too_many_arguments)]
    #[doc(hidden)]
    fn dot_general_with_conj_cached(
        &mut self,
        _cache: &mut Self::RuntimeCache,
        _cache_slot: Option<usize>,
        lhs: &Tensor,
        rhs: &Tensor,
        config: &DotGeneralConfig,
        lhs_conj: bool,
        rhs_conj: bool,
    ) -> crate::Result<Tensor> {
        self.dot_general_with_conj(lhs, rhs, config, lhs_conj, rhs_conj)
    }

    // Mirrors the dot-general read signature plus runtime-cache metadata.
    #[allow(clippy::too_many_arguments)]
    #[doc(hidden)]
    fn dot_general_with_conj_read_cached(
        &mut self,
        cache: &mut Self::RuntimeCache,
        cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        lhs_conj: bool,
        rhs_conj: bool,
    ) -> crate::Result<Tensor> {
        if !lhs_conj && !rhs_conj {
            return self.dot_general_read_cached(cache, cache_slot, lhs, rhs, config);
        }

        let lhs_tmp;
        let lhs_ref = if let Some(tensor) = lhs.as_tensor() {
            tensor
        } else {
            lhs_tmp = self.to_contiguous_read(lhs)?;
            &lhs_tmp
        };
        let rhs_tmp;
        let rhs_ref = if let Some(tensor) = rhs.as_tensor() {
            tensor
        } else {
            rhs_tmp = self.to_contiguous_read(rhs)?;
            &rhs_tmp
        };
        self.dot_general_with_conj_cached(
            cache, cache_slot, lhs_ref, rhs_ref, config, lhs_conj, rhs_conj,
        )
    }

    /// Apply cached scaled dot-general accumulation into caller-provided output.
    ///
    /// The cache slot identifies backend-local analysis metadata only; output
    /// semantics are still fully described by `accumulation`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tenferro_tensor::{
    ///     BackendCachedDot, BackendRuntimeCache, DotGeneralAccumulation, DotGeneralConfig,
    ///     TensorRead, TensorWrite,
    /// };
    ///
    /// fn cached_dot_add_to<B: BackendCachedDot>(
    ///     backend: &mut B,
    ///     cache: &mut B::RuntimeCache,
    ///     lhs: TensorRead<'_>,
    ///     rhs: TensorRead<'_>,
    ///     config: &DotGeneralConfig,
    ///     out: TensorWrite<'_>,
    /// ) -> tenferro_tensor::Result<()>
    /// where
    ///     B: BackendRuntimeCache,
    /// {
    ///     let accumulation = DotGeneralAccumulation::add_to(lhs.dtype())?;
    ///     backend.dot_general_read_into_accum_cached(
    ///         cache,
    ///         Some(0),
    ///         lhs,
    ///         rhs,
    ///         config,
    ///         accumulation,
    ///         out,
    ///     )
    /// }
    /// ```
    #[allow(clippy::too_many_arguments)]
    /// # Errors
    ///
    /// Returns [`crate::Error::Validation`] with a typed `ValidationError` source
    /// for invalid shapes, ranks, axes, dtypes, or output metadata. It returns
    /// [`crate::Error::BackendFailure`] or [`crate::Error::BackendSource`] when
    /// backend execution or storage access cannot provide the requested result.
    fn dot_general_read_into_accum_cached(
        &mut self,
        _cache: &mut Self::RuntimeCache,
        _cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &DotGeneralConfig,
        accumulation: DotGeneralAccumulation,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        self.dot_general_read_into_accum(lhs, rhs, config, accumulation, out)
    }

    #[doc(hidden)]
    fn grouped_gemm_cached(
        &mut self,
        _cache: &mut Self::RuntimeCache,
        _cache_slot: Option<usize>,
        lhs: TensorRead<'_>,
        rhs: TensorRead<'_>,
        config: &GroupedGemmConfig<'_>,
        out: TensorWrite<'_>,
    ) -> crate::Result<()> {
        grouped_gemm_default(self, lhs, rhs, config, out)
    }
}

/// Backend execution-session entry points.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::BackendSessionHost;
///
/// fn accepts_session_host<B: BackendSessionHost>(_backend: &mut B) {}
/// ```
pub trait BackendSessionHost: BackendRuntimeCache {
    fn with_backend_session<R: Send>(
        &mut self,
        f: impl FnOnce(&mut dyn BackendSession) -> R + Send,
    ) -> R
    where
        Self: TensorBackend + Sized,
    {
        default_backend_session(self, f)
    }

    #[doc(hidden)]
    fn with_backend_session_cached<R: Send>(
        &mut self,
        _cache: &mut Self::RuntimeCache,
        f: impl FnOnce(&mut dyn BackendSession) -> R + Send,
    ) -> R
    where
        Self: TensorBackend + Sized,
    {
        self.with_backend_session(f)
    }
}

/// Operation capabilities shared by backends and backend sessions.
#[doc(hidden)]
pub trait TensorBackendOps:
    TensorElementwise
    + TensorAnalytic
    + TensorStructural
    + TensorReduction
    + TensorIndexing
    + TensorDot
    + TensorFusion
    + TensorBuffer
{
}

impl<T> TensorBackendOps for T where
    T: TensorElementwise
        + TensorAnalytic
        + TensorStructural
        + TensorReduction
        + TensorIndexing
        + TensorDot
        + TensorFusion
        + TensorBuffer
        + ?Sized
{
}

/// Execution session surface for dense tensor backends.
///
/// All operations run within a backend-owned execution scope such as a CPU
/// thread policy or a GPU stream. Individual ops must not try to re-enter that
/// scope.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::{BackendSessionHost, Tensor, TypedTensor};
///
/// fn add_in_session<B: BackendSessionHost>(
///     backend: &mut B,
///     a: &Tensor,
///     b: &Tensor,
/// ) -> tenferro_tensor::Result<Tensor>
/// where
///     B: tenferro_tensor::TensorBackend,
/// {
///     backend.with_backend_session(|exec| exec.add(a, b))
/// }
/// ```
pub trait BackendSession: TensorBackendOps + SessionCachedDot + TensorDeviceTransfer {
    /// Build-local identity for backend-extension session capability dispatch.
    #[doc(hidden)]
    fn session_type_id(&self) -> TypeId;

    /// Erased pointer used only by backend leaf crates for a checked session
    /// capability bridge. The pointer is borrowed for the lifetime of `self`.
    ///
    /// # Safety
    ///
    /// The implementation must return a pointer to the same value represented
    /// by `self`, and that pointer must remain valid and uniquely borrowed for
    /// the duration of the `&mut self` borrow. Backend leaf crates may use this
    /// contract to recover a concrete session capability after checking
    /// [`Self::session_type_id`].
    #[doc(hidden)]
    unsafe fn session_data_mut(&mut self) -> *mut ();
}

/// Standard runtime backend over dynamic [`Tensor`] values.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::TensorBackend;
///
/// fn accepts_backend<B: TensorBackend>(_backend: &mut B) {}
/// ```
pub trait TensorBackend:
    BackendRuntimeCache
    + BackendSession
    + TensorBackendOps
    + BackendCachedDot
    + TensorDeviceTransfer
    + BackendSessionHost
{
}

impl<T> SessionCachedDot for T where T: TensorBackend + ?Sized {}

/// Run a closure using the backend itself as a default execution session.
///
/// This is suitable for backends whose individual ops already manage their own
/// execution context.
///
/// # Examples
///
/// ```rust
/// use tenferro_tensor::{default_backend_session, TensorBackend};
///
/// fn run_with_default_session<B: TensorBackend>(backend: &mut B) -> usize {
///     default_backend_session(backend, |_exec| 1usize)
/// }
/// ```
pub fn default_backend_session<B: TensorBackend, R: Send>(
    backend: &mut B,
    f: impl FnOnce(&mut dyn BackendSession) -> R + Send,
) -> R {
    f(backend)
}