eredu-nn 0.2.1

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

#![warn(missing_docs)]

extern crate self as eredu_nn;

use std::fmt::Debug;

use eredu_checkpoint::LinearFormat;

pub use eredu_nn_macros::Parameterized;

/// Reusable patch projection and multi-axis position operations.
pub mod multimodal;
/// Checked tensor-independent normalization and mask geometry.
pub mod operation_geometry;
/// Typed pre-dispatch controls for architecture-configured expert selectors.
pub mod routing_intervention;
/// Pure sequence layouts shared by patch-based encoders.
pub mod sequence_layout;

/// Backend operation failure.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{message}")]
pub struct Error {
    message: String,
}

impl Error {
    /// Creates a backend operation failure without exposing backend-native
    /// exception types through architecture code.
    pub fn backend(error: impl std::fmt::Display) -> Self {
        Self {
            message: error.to_string(),
        }
    }
}

/// One axis of a backend-neutral tensor view.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Index {
    /// Retains the complete axis.
    Full,
    /// Selects one element and removes the axis.
    At(i32),
    /// Retains the half-open interval `[start, end)`.
    Range(i32, i32),
}

/// Padding behavior for convolutional architecture components.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PadMode {
    /// Pads with zeroes.
    Constant,
    /// Repeats the nearest edge value.
    Edge,
}

/// Attention masking selected by architecture code.
#[derive(Debug, Clone, Copy)]
pub enum AttentionMask<'a, T> {
    /// No attention mask.
    None,
    /// Standard causal mask.
    Causal,
    /// Backend tensor added to attention logits.
    Tensor(&'a T),
}

/// Validated expansion from a smaller logical head axis to a repeated head
/// axis. Repetition preserves grouped order: each source head is repeated
/// contiguously `target_heads / source_heads` times.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct HeadExpansion {
    /// Tensor axis containing source heads.
    pub axis: usize,
    /// Number of source heads.
    pub source_heads: i32,
    /// Number of heads after expansion.
    pub target_heads: i32,
}

impl HeadExpansion {
    /// Validates the head counts and the selected tensor axis.
    pub fn validate<T: Tensor>(&self, input: &T) -> Result<(), Error> {
        let shape = input.shape();
        if self.source_heads <= 0
            || self.target_heads <= 0
            || self.target_heads % self.source_heads != 0
            || shape.get(self.axis).copied() != Some(self.source_heads)
        {
            return Err(Error::backend(format!(
                "invalid head expansion axis={} source={} target={} shape={shape:?}",
                self.axis, self.source_heads, self.target_heads
            )));
        }
        Ok(())
    }

    /// Number of adjacent copies of each source head.
    pub const fn repeats(self) -> i32 {
        self.target_heads / self.source_heads
    }
}

/// One unmasked attention request over validated contiguous sequence segments.
#[derive(Debug, Clone, Copy)]
pub struct SegmentedAttentionInput<'a, T> {
    /// Queries shaped `[tokens, heads, dimensions]`.
    pub queries: &'a T,
    /// Keys shaped `[tokens, heads, dimensions]`.
    pub keys: &'a T,
    /// Values shaped `[tokens, heads, value_dimensions]`.
    pub values: &'a T,
    /// Positive contiguous segment lengths whose sum equals `tokens`.
    pub segment_lengths: &'a [i32],
    /// Query/key score multiplier.
    pub scale: f32,
}

impl<T: Tensor> SegmentedAttentionInput<'_, T> {
    /// Validates tensor and segment geometry without inspecting tensor values.
    pub fn validate(&self) -> Result<(), Error> {
        let query = self.queries.shape();
        let key = self.keys.shape();
        let value = self.values.shape();
        if query.len() != 3
            || key.len() != 3
            || value.len() != 3
            || query[0] <= 0
            || query[1] <= 0
            || query[2] <= 0
            || query[0] != key[0]
            || query[0] != value[0]
            || query[1] != key[1]
            || query[1] != value[1]
            || query[2] != key[2]
            || value[2] <= 0
            || !self.scale.is_finite()
            || self.scale <= 0.0
        {
            return Err(Error::backend(format!(
                "invalid segmented attention geometry q={query:?} k={key:?} v={value:?} scale={}",
                self.scale
            )));
        }
        validate_segment_lengths(query[0], self.segment_lengths)
    }
}

/// Validates positive contiguous segment lengths and their exact total.
pub fn validate_segment_lengths(total: i32, segment_lengths: &[i32]) -> Result<(), Error> {
    if total <= 0 || segment_lengths.is_empty() {
        return Err(Error::backend(format!(
            "segmented attention requires a positive total and at least one segment, got total={total} segments={segment_lengths:?}"
        )));
    }
    let mut sum = 0i32;
    for &length in segment_lengths {
        if length <= 0 {
            return Err(Error::backend(format!(
                "segmented attention lengths must be positive, got {segment_lengths:?}"
            )));
        }
        sum = sum.checked_add(length).ok_or_else(|| {
            Error::backend("segmented attention length total overflowed signed 32-bit geometry")
        })?;
        if sum > total {
            return Err(Error::backend(format!(
                "segmented attention lengths exceed total {total}: {segment_lengths:?}"
            )));
        }
    }
    if sum != total {
        return Err(Error::backend(format!(
            "segmented attention lengths sum to {sum}, expected {total}"
        )));
    }
    Ok(())
}

/// Deterministic host reference for grouped head repetition.
pub fn reference_expand_heads(
    values: &[f32],
    shape: &[usize],
    axis: usize,
    target_heads: usize,
) -> Result<(Vec<f32>, Vec<usize>), Error> {
    let source_heads = shape.get(axis).copied().unwrap_or(0);
    if source_heads == 0 || target_heads == 0 || !target_heads.is_multiple_of(source_heads) {
        return Err(Error::backend(format!(
            "invalid reference head expansion axis={axis} target={target_heads} shape={shape:?}"
        )));
    }
    let elements = shape.iter().try_fold(1usize, |total, width| {
        total
            .checked_mul(*width)
            .ok_or_else(|| Error::backend("reference head expansion element count overflowed"))
    })?;
    if elements != values.len() {
        return Err(Error::backend(format!(
            "reference head expansion expected {elements} values, got {}",
            values.len()
        )));
    }
    let outer = shape[..axis].iter().product::<usize>();
    let inner = shape[axis + 1..].iter().product::<usize>();
    let repeats = target_heads / source_heads;
    let mut output = Vec::with_capacity(outer * target_heads * inner);
    for outer_index in 0..outer {
        for source in 0..source_heads {
            let start = (outer_index * source_heads + source) * inner;
            for _ in 0..repeats {
                output.extend_from_slice(&values[start..start + inner]);
            }
        }
    }
    let mut output_shape = shape.to_vec();
    output_shape[axis] = target_heads;
    Ok((output, output_shape))
}

/// Deterministic host reference for unmasked segmented scaled-dot-product
/// attention. Inputs and output use token-major `[tokens, heads, dimensions]`
/// storage.
#[allow(clippy::too_many_arguments)]
pub fn reference_segmented_attention(
    tokens: usize,
    heads: usize,
    dimensions: usize,
    value_dimensions: usize,
    queries: &[f32],
    keys: &[f32],
    values: &[f32],
    segment_lengths: &[i32],
    scale: f32,
) -> Result<Vec<f32>, Error> {
    let tokens_i32 = i32::try_from(tokens)
        .map_err(|_| Error::backend("reference segmented attention token count exceeds i32"))?;
    validate_segment_lengths(tokens_i32, segment_lengths)?;
    if heads == 0
        || dimensions == 0
        || value_dimensions == 0
        || !scale.is_finite()
        || scale <= 0.0
        || queries.len() != tokens * heads * dimensions
        || keys.len() != tokens * heads * dimensions
        || values.len() != tokens * heads * value_dimensions
    {
        return Err(Error::backend(
            "invalid reference segmented attention geometry",
        ));
    }
    let mut output = vec![0.0f32; tokens * heads * value_dimensions];
    let mut segment_start = 0usize;
    for &length in segment_lengths {
        let length = usize::try_from(length).expect("validated positive segment length");
        let segment_end = segment_start + length;
        for query_token in segment_start..segment_end {
            for head in 0..heads {
                let mut scores = Vec::with_capacity(length);
                for key_token in segment_start..segment_end {
                    let mut score = 0.0f32;
                    for dimension in 0..dimensions {
                        let query_index = (query_token * heads + head) * dimensions + dimension;
                        let key_index = (key_token * heads + head) * dimensions + dimension;
                        score += queries[query_index] * keys[key_index];
                    }
                    scores.push(score * scale);
                }
                let maximum = scores.iter().copied().fold(f32::NEG_INFINITY, f32::max);
                let denominator = scores
                    .iter_mut()
                    .map(|score| {
                        *score = (*score - maximum).exp();
                        *score
                    })
                    .sum::<f32>();
                for value_dimension in 0..value_dimensions {
                    let mut result = 0.0f32;
                    for (relative, key_token) in (segment_start..segment_end).enumerate() {
                        let value_index =
                            (key_token * heads + head) * value_dimensions + value_dimension;
                        result += scores[relative] / denominator * values[value_index];
                    }
                    let output_index =
                        (query_token * heads + head) * value_dimensions + value_dimension;
                    output[output_index] = result;
                }
            }
        }
        segment_start = segment_end;
    }
    Ok(output)
}

/// Value source for an attention unit that owns key/value state.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum AttentionValueSource {
    /// Values are produced by an independent projection.
    Projected,
    /// Projected keys are reused as values.
    ReuseKey,
}

/// Typed source and publication policy for attention key/value state.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum AttentionStateSource {
    /// Own projections and retain state only for this attention unit.
    Local {
        /// Value projection topology.
        value: AttentionValueSource,
    },
    /// Own projections and publish state for later consumers.
    Publish {
        /// Value projection topology.
        value: AttentionValueSource,
    },
    /// Consume state published by another unit or supplied externally.
    Shared,
}

impl AttentionStateSource {
    /// Returns whether the attention unit owns projections and mutable state.
    pub const fn owns_state(self) -> bool {
        !matches!(self, Self::Shared)
    }

    /// Returns whether the resulting state must be published.
    pub const fn publishes_state(self) -> bool {
        matches!(self, Self::Publish { .. })
    }

    /// Returns the value source for a state-owning unit.
    pub const fn value(self) -> Option<AttentionValueSource> {
        match self {
            Self::Local { value } | Self::Publish { value } => Some(value),
            Self::Shared => None,
        }
    }
}

#[cfg(test)]
mod attention_state_source_tests {
    use super::{AttentionStateSource, AttentionValueSource};

    #[test]
    fn ownership_publication_and_key_as_value_are_independent() {
        let local = AttentionStateSource::Local {
            value: AttentionValueSource::Projected,
        };
        let publisher = AttentionStateSource::Publish {
            value: AttentionValueSource::ReuseKey,
        };
        assert!(local.owns_state());
        assert!(!local.publishes_state());
        assert_eq!(local.value(), Some(AttentionValueSource::Projected));
        assert!(publisher.owns_state());
        assert!(publisher.publishes_state());
        assert_eq!(publisher.value(), Some(AttentionValueSource::ReuseKey));
        assert!(!AttentionStateSource::Shared.owns_state());
        assert_eq!(AttentionStateSource::Shared.value(), None);
    }
}

#[cfg(test)]
mod recurrent_encoder_contract_tests {
    use super::{
        reference_expand_heads, reference_segmented_attention, validate_segment_lengths,
        NormalizationConstructionSpec, NormalizationScale,
    };

    #[test]
    fn normalization_construction_rejects_invalid_geometry_and_scalars() {
        assert!(NormalizationConstructionSpec {
            dimensions: 8,
            epsilon: 1e-6,
            scale: NormalizationScale::Unit,
        }
        .validate()
        .is_ok());
        assert!(NormalizationConstructionSpec {
            dimensions: 0,
            epsilon: 1e-6,
            scale: NormalizationScale::Unit,
        }
        .validate()
        .is_err());
        assert!(NormalizationConstructionSpec {
            dimensions: 8,
            epsilon: f32::NAN,
            scale: NormalizationScale::Unit,
        }
        .validate()
        .is_err());
    }

    #[test]
    fn head_expansion_reference_preserves_grouped_row_order() {
        let (values, shape) =
            reference_expand_heads(&[1.0, 2.0, 3.0, 4.0], &[1, 2, 2], 1, 4).unwrap();
        assert_eq!(shape, vec![1, 4, 2]);
        assert_eq!(values, vec![1.0, 2.0, 1.0, 2.0, 3.0, 4.0, 3.0, 4.0]);
        assert!(reference_expand_heads(&[1.0, 2.0], &[1, 2], 1, 3).is_err());
    }

    #[test]
    fn segmented_attention_reference_is_independent_per_contiguous_segment() {
        let output = reference_segmented_attention(
            3,
            1,
            1,
            1,
            &[0.0, 0.0, 0.0],
            &[0.0, 0.0, 0.0],
            &[2.0, 4.0, 9.0],
            &[2, 1],
            1.0,
        )
        .unwrap();
        assert_eq!(output, vec![3.0, 3.0, 9.0]);
        assert!(validate_segment_lengths(3, &[]).is_err());
        assert!(validate_segment_lengths(3, &[2, 0, 1]).is_err());
        assert!(validate_segment_lengths(3, &[2]).is_err());
        assert!(validate_segment_lengths(3, &[2, 2]).is_err());
        assert!(validate_segment_lengths(i32::MAX, &[i32::MAX, 1]).is_err());
    }
}

/// Typed sparse/indexed attention request.
///
/// Architecture code owns how positions are selected, causal eligibility,
/// compression ratios, top-k, and sink policy. A backend may fuse gathering,
/// shared-softmax attention, and value reduction without exposing an
/// accelerator-specific indexing API.
#[derive(Debug, Clone, Copy)]
pub struct IndexedAttentionInput<'a, T> {
    /// Queries shaped `[batch, heads, query_tokens, key_dimensions]`.
    pub queries: &'a T,
    /// Bounded local keys shaped `[batch, local_tokens, key_dimensions]`.
    pub local_keys: &'a T,
    /// Bounded local values shaped `[batch, local_tokens, value_dimensions]`.
    pub local_values: &'a T,
    /// Compressed/indexable keys shaped `[batch, pooled_tokens, key_dimensions]`.
    pub pooled_keys: &'a T,
    /// Compressed/indexable values shaped `[batch, pooled_tokens, value_dimensions]`.
    pub pooled_values: &'a T,
    /// Selected pooled positions shaped `[batch, query_tokens, selected]`.
    pub selected_positions: &'a T,
    /// Query/key score multiplier.
    pub scale: f32,
    /// Optional mask broadcastable to local scores.
    pub local_mask: Option<&'a T>,
    /// Optional mask broadcastable to selected pooled scores.
    pub pooled_mask: Option<&'a T>,
    /// Optional learned per-head sink logits.
    pub sinks: Option<&'a T>,
}

/// Dense attention over bounded local keys plus complete pooled history.
#[derive(Debug, Clone, Copy)]
pub struct PooledAttentionInput<'a, T> {
    /// Queries shaped `[batch, heads, query_tokens, dimensions]`.
    pub queries: &'a T,
    /// Bounded local keys and values shaped `[batch, local_tokens, dimensions]`.
    pub local: &'a T,
    /// Complete pooled keys and values shaped `[batch, pooled_tokens, dimensions]`.
    pub pooled: &'a T,
    /// Query/key score multiplier.
    pub scale: f32,
    /// Optional mask broadcastable to local scores.
    pub local_mask: Option<&'a T>,
    /// Optional mask broadcastable to pooled scores.
    pub pooled_mask: Option<&'a T>,
    /// Optional learned per-head sink logits.
    pub sinks: Option<&'a T>,
}

/// Architecture-selected pooled-position scoring request.
///
/// Backends may fuse score construction, causal masking, and top-k selection
/// without exposing device-specific partition or gather operations.
#[derive(Debug, Clone, Copy)]
pub struct PooledPositionInput<'a, T> {
    /// Rotary queries shaped `[batch, heads, query_tokens, dimensions]`.
    pub queries: &'a T,
    /// Compressed index keys shaped `[batch, pooled_tokens, dimensions]`.
    pub pooled_keys: &'a T,
    /// Per-token head weights shaped `[batch, query_tokens, heads]`.
    pub head_weights: &'a T,
    /// Optional eligibility mask shaped `[query_tokens, pooled_tokens]` or a
    /// broadcast-compatible batch variant.
    pub mask: Option<&'a T>,
    /// Number of pooled positions selected per query token.
    pub top_k: i32,
    /// Score multiplier applied after nonnegative clamping.
    pub scale: f32,
    /// Head-weight multiplier applied before reducing the head axis.
    pub head_scale: f32,
}

/// Causal attention with a learned relative-position profile.
///
/// Architecture code projects per-token relative features into `profiles`;
/// the backend owns position-index gathering and score materialization so no
/// device values cross the host boundary.
#[derive(Debug, Clone, Copy)]
pub struct RelativeAttentionInput<'a, T> {
    /// Normalized queries shaped `[batch, heads, query_tokens, dimensions]`.
    pub queries: &'a T,
    /// Normalized keys shaped `[batch, kv_heads, key_tokens, dimensions]`.
    pub keys: &'a T,
    /// Values shaped `[batch, kv_heads, key_tokens, dimensions]`.
    pub values: &'a T,
    /// Learned profiles shaped `[batch, heads, query_tokens, relative_extent]`.
    pub profiles: &'a T,
    /// Absolute position of the first query token.
    pub query_offset: i32,
    /// Absolute position of the first retained key token.
    pub key_offset: i32,
    /// Optional causal sliding-window width.
    pub window: Option<i32>,
    /// Optional position floor for logarithmic global-attention scaling.
    pub log_scaling_floor: Option<i32>,
    /// Multiplier applied to the logarithmic scale above the floor.
    pub log_scaling_alpha: f32,
}

impl<T: Tensor> RelativeAttentionInput<'_, T> {
    /// Validates exact head, sequence, and relative-profile geometry.
    pub fn validate(&self) -> Result<(), Error> {
        let query = self.queries.shape();
        let key = self.keys.shape();
        let value = self.values.shape();
        let profiles = self.profiles.shape();
        if query.len() != 4
            || key.len() != 4
            || value.len() != 4
            || profiles.len() != 4
            || query[0] != key[0]
            || key != value
            || query[2] != profiles[2]
            || query[0] != profiles[0]
            || query[1] != profiles[1]
            || query[3] != key[3]
            || query[1] % key[1] != 0
            || profiles[3] <= 0
            || self.window.is_some_and(|window| window <= 0)
            || self.log_scaling_floor.is_some_and(|floor| floor <= 0)
            || !self.log_scaling_alpha.is_finite()
        {
            return Err(Error::backend(format!(
                "invalid relative attention geometry q={query:?} k={key:?} v={value:?} profiles={profiles:?} window={:?} floor={:?} alpha={}",
                self.window, self.log_scaling_floor, self.log_scaling_alpha
            )));
        }
        Ok(())
    }
}

impl<T: Tensor> IndexedAttentionInput<'_, T> {
    /// Validates semantic ranks and exact non-broadcast geometry without
    /// materializing any backend values.
    pub fn validate(&self) -> Result<(), Error> {
        let query = self.queries.shape();
        let local_keys = self.local_keys.shape();
        let local_values = self.local_values.shape();
        let pooled_keys = self.pooled_keys.shape();
        let pooled_values = self.pooled_values.shape();
        let selected = self.selected_positions.shape();
        if query.len() != 4
            || local_keys.len() != 3
            || local_values.len() != 3
            || pooled_keys.len() != 3
            || pooled_values.len() != 3
            || selected.len() != 3
            || query[0] != local_keys[0]
            || query[0] != local_values[0]
            || query[0] != pooled_keys[0]
            || query[0] != pooled_values[0]
            || query[0] != selected[0]
            || query[2] != selected[1]
            || query[3] != local_keys[2]
            || query[3] != pooled_keys[2]
            || local_keys[1] != local_values[1]
            || pooled_keys[1] != pooled_values[1]
            || local_values[2] != pooled_values[2]
            || selected[2] <= 0
            || pooled_keys[1] <= 0
        {
            return Err(Error::backend(format!(
                "invalid indexed-attention geometry: queries={query:?} local_keys={local_keys:?} local_values={local_values:?} pooled_keys={pooled_keys:?} pooled_values={pooled_values:?} selected={selected:?}"
            )));
        }
        if !self.scale.is_finite() || self.scale <= 0.0 {
            return Err(Error::backend(format!(
                "indexed-attention scale must be finite and positive, got {}",
                self.scale
            )));
        }
        if let Some(sinks) = self.sinks {
            if sinks.shape() != [query[1]] {
                return Err(Error::backend(format!(
                    "indexed-attention sinks require shape [{}], got {:?}",
                    query[1],
                    sinks.shape()
                )));
            }
        }
        Ok(())
    }
}

/// Stable authoritative identity of one logical model parameter.
#[derive(Debug, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ParameterId(String);

impl ParameterId {
    /// Creates a non-empty parameter identity.
    pub fn new(id: impl Into<String>) -> Result<Self, ParameterTopologyError> {
        let id = id.into();
        if id.trim().is_empty() {
            return Err(ParameterTopologyError::EmptyId);
        }
        Ok(Self(id))
    }

    /// Returns the stable checkpoint-facing identity.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for ParameterId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// Complete logical declaration for one parameter slot.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ParameterSpec {
    /// Stable authoritative identity.
    pub id: ParameterId,
    /// Whether optimizers may update this parameter by default.
    pub trainable: bool,
    /// Authoritative destination when this slot aliases a tied parameter.
    pub alias_of: Option<ParameterId>,
    /// Optional atomic encoding or sharding group.
    pub group: Option<String>,
    /// Semantic role within an encoded linear parameter group.
    pub linear_companion: Option<LinearCompanionRole>,
    /// Primary linear weight owned by this physical companion.
    pub linear_companion_of: Option<ParameterId>,
}

impl ParameterSpec {
    /// Declares an ordinary trainable parameter.
    pub fn trainable(id: impl Into<String>) -> Result<Self, ParameterTopologyError> {
        Ok(Self {
            id: ParameterId::new(id)?,
            trainable: true,
            alias_of: None,
            group: None,
            linear_companion: None,
            linear_companion_of: None,
        })
    }
}

/// Semantic role of a physical companion in an encoded linear parameter.
#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
pub enum LinearCompanionRole {
    /// Per-group or per-block scale tensor.
    Scale,
    /// Per-group affine zero-point/bias tensor.
    AffineBias,
}

/// Parameter metadata observed during traversal.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ParameterMetadata {
    /// Stable authoritative identity.
    pub id: ParameterId,
    /// Current trainable state.
    pub trainable: bool,
    /// Authoritative destination for a tied alias.
    pub alias_of: Option<ParameterId>,
    /// Optional atomic parameter group.
    pub group: Option<String>,
    /// Semantic role within an encoded linear parameter group.
    pub linear_companion: Option<LinearCompanionRole>,
    /// Primary linear weight owned by this physical companion.
    pub linear_companion_of: Option<ParameterId>,
}

impl ParameterMetadata {
    /// Creates traversal metadata from a construction specification.
    pub fn from_spec(spec: &ParameterSpec, trainable: bool) -> Self {
        Self {
            id: spec.id.clone(),
            trainable,
            alias_of: spec.alias_of.clone(),
            group: spec.group.clone(),
            linear_companion: spec.linear_companion,
            linear_companion_of: spec.linear_companion_of.clone(),
        }
    }
}

/// Invalid stable parameter topology.
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
pub enum ParameterTopologyError {
    /// A parameter identity is empty.
    #[error("parameter identity must not be empty")]
    EmptyId,
    /// The same stable identity was visited more than once.
    #[error("parameter identity {0} is duplicated")]
    DuplicateId(ParameterId),
    /// A tied alias points to an identity that is not in the topology.
    #[error("parameter alias {alias} points to missing destination {destination}")]
    MissingAliasDestination {
        /// Identity of the aliasing slot.
        alias: ParameterId,
        /// Missing authoritative destination.
        destination: ParameterId,
    },
    /// A tied alias points to another alias instead of an authoritative slot.
    #[error("parameter alias {alias} points to non-authoritative alias {destination}")]
    AliasTargetsAlias {
        /// Identity of the aliasing slot.
        alias: ParameterId,
        /// Non-authoritative destination.
        destination: ParameterId,
    },
}

/// Immutable statically dispatched parameter visitor.
pub trait ParameterVisitor<'a, T: 'a> {
    /// Visits one authoritative parameter slot.
    fn visit(&mut self, metadata: ParameterMetadata, value: &'a T);
}

/// Mutable statically dispatched parameter visitor.
pub trait ParameterVisitorMut<'a, T: 'a> {
    /// Visits one authoritative mutable parameter slot.
    fn visit_mut(&mut self, metadata: ParameterMetadata, value: &'a mut T);
}

/// Backend-neutral parameter topology for a module or operator.
///
/// Immutable and mutable traversal must expose the same complete set of stable
/// identities. Repeated mutable traversals must preserve that set until a
/// visitor replaces a parameter value; runtime binding relies on this law to
/// validate the whole topology before publishing any replacement.
pub trait Parameterized<T: 'static> {
    /// Visits every parameter exactly once using stable identities.
    fn visit_parameters<'a, V>(&'a self, visitor: &mut V)
    where
        V: ParameterVisitor<'a, T>;

    /// Mutably visits every parameter exactly once using stable identities.
    fn visit_parameters_mut<'a, V>(&'a mut self, visitor: &mut V)
    where
        V: ParameterVisitorMut<'a, T>;

    /// Updates whether all parameters in this module are trainable.
    fn set_trainable(&mut self, trainable: bool);
}

/// Collects and validates the stable parameter topology exposed by a module.
pub fn validate_parameter_topology<T: 'static, M>(
    module: &M,
) -> Result<Vec<ParameterMetadata>, ParameterTopologyError>
where
    M: Parameterized<T>,
{
    struct Collector(Vec<ParameterMetadata>);
    impl<'a, T: 'a> ParameterVisitor<'a, T> for Collector {
        fn visit(&mut self, metadata: ParameterMetadata, _value: &'a T) {
            self.0.push(metadata);
        }
    }

    let mut collector = Collector(Vec::new());
    module.visit_parameters(&mut collector);
    let mut topology = std::collections::BTreeMap::new();
    for metadata in &collector.0 {
        if topology.insert(metadata.id.clone(), metadata).is_some() {
            return Err(ParameterTopologyError::DuplicateId(metadata.id.clone()));
        }
    }
    for metadata in &collector.0 {
        let Some(destination) = &metadata.alias_of else {
            continue;
        };
        let Some(target) = topology.get(destination) else {
            return Err(ParameterTopologyError::MissingAliasDestination {
                alias: metadata.id.clone(),
                destination: destination.clone(),
            });
        };
        if target.alias_of.is_some() {
            return Err(ParameterTopologyError::AliasTargetsAlias {
                alias: metadata.id.clone(),
                destination: destination.clone(),
            });
        }
    }
    Ok(collector.0)
}

/// Shape and checkpoint identity for an affine projection.
#[derive(Debug, Clone)]
pub struct LinearSpec {
    /// Input feature count.
    pub input: i32,
    /// Output feature count.
    pub output: i32,
    /// Stable weight slot.
    pub weight: ParameterSpec,
    /// Optional stable bias slot.
    pub bias: Option<ParameterSpec>,
    /// Complete physical checkpoint encoding and exact companion identities.
    pub format: LinearFormatSpec,
}

/// Complete construction specification for a token embedding table.
#[derive(Debug, Clone)]
pub struct EmbeddingSpec {
    /// Vocabulary row count.
    pub vocabulary: i32,
    /// Embedding width.
    pub dimensions: i32,
    /// Stable embedding weight slot.
    pub weight: ParameterSpec,
    /// Complete physical checkpoint encoding and exact companion identities.
    pub format: LinearFormatSpec,
}

/// Architecture-owned physical encoding and exact companion parameters.
///
/// Backends consume these identities literally. They must never derive scale
/// or affine-bias names from the primary weight identity.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct LinearFormatSpec {
    format: LinearFormat,
    scale: Option<ParameterSpec>,
    affine_bias: Option<ParameterSpec>,
}

impl LinearFormatSpec {
    /// Declares a dense or checkpoint-native encoding with no companions.
    pub fn unscaled(format: LinearFormat) -> Result<Self, Error> {
        let spec = Self {
            format,
            scale: None,
            affine_bias: None,
        };
        spec.validate()?;
        Ok(spec)
    }

    /// Declares an encoding with one exact scale companion.
    pub fn scaled(format: LinearFormat, scale: ParameterSpec) -> Result<Self, Error> {
        let mut scale = scale;
        scale.linear_companion = Some(LinearCompanionRole::Scale);
        scale.linear_companion_of = None;
        let spec = Self {
            format,
            scale: Some(scale),
            affine_bias: None,
        };
        spec.validate()?;
        Ok(spec)
    }

    /// Declares an affine encoding with exact scale and bias companions.
    pub fn affine(
        format: LinearFormat,
        scale: ParameterSpec,
        affine_bias: ParameterSpec,
    ) -> Result<Self, Error> {
        let mut scale = scale;
        scale.linear_companion = Some(LinearCompanionRole::Scale);
        scale.linear_companion_of = None;
        let mut affine_bias = affine_bias;
        affine_bias.linear_companion = Some(LinearCompanionRole::AffineBias);
        affine_bias.linear_companion_of = None;
        let spec = Self {
            format,
            scale: Some(scale),
            affine_bias: Some(affine_bias),
        };
        spec.validate()?;
        Ok(spec)
    }

    /// Physical tensor encoding.
    pub const fn encoding(&self) -> LinearFormat {
        self.format
    }

    /// Exact scale companion, when stored separately.
    pub const fn scale(&self) -> Option<&ParameterSpec> {
        self.scale.as_ref()
    }

    /// Exact affine-bias companion, when stored separately.
    pub const fn affine_bias(&self) -> Option<&ParameterSpec> {
        self.affine_bias.as_ref()
    }

    /// Validates that companion cardinality matches the physical encoding.
    pub fn validate(&self) -> Result<(), Error> {
        self.format.validate().map_err(Error::backend)?;
        let expected = match self.format {
            LinearFormat::Dense | LinearFormat::GgufIQuant { .. } => (false, false),
            LinearFormat::MxFp4 | LinearFormat::E4M3BlockFp8(_) => (true, false),
            LinearFormat::Affine(_) => (true, true),
        };
        if (self.scale.is_some(), self.affine_bias.is_some()) != expected {
            return Err(Error::backend(format!(
                "linear format {:?} requires scale/bias companions {:?}, got {:?}",
                self.format,
                expected,
                (self.scale.is_some(), self.affine_bias.is_some())
            )));
        }
        if self
            .scale
            .as_ref()
            .zip(self.affine_bias.as_ref())
            .is_some_and(|(scale, bias)| scale.id == bias.id)
        {
            return Err(Error::backend(
                "linear scale and affine-bias companions require distinct identities",
            ));
        }
        if self
            .scale
            .as_ref()
            .is_some_and(|scale| scale.linear_companion != Some(LinearCompanionRole::Scale))
            || self
                .affine_bias
                .as_ref()
                .is_some_and(|bias| bias.linear_companion != Some(LinearCompanionRole::AffineBias))
        {
            return Err(Error::backend(
                "linear format companions have invalid semantic roles",
            ));
        }
        Ok(())
    }

    /// Validates companions against the primary weight identity.
    pub fn validate_for_weight(&self, weight: &ParameterSpec) -> Result<(), Error> {
        self.validate()?;
        if self
            .scale
            .as_ref()
            .into_iter()
            .chain(self.affine_bias.as_ref())
            .any(|companion| companion.id == weight.id)
        {
            return Err(Error::backend(format!(
                "linear format companion reuses primary weight identity {}",
                weight.id
            )));
        }
        Ok(())
    }
}

/// One rank's validated contiguous vocabulary ownership.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct VocabularyParallelRange {
    /// Complete logical vocabulary size.
    pub global_vocabulary: usize,
    /// Half-open row range materialized by this rank.
    pub local: std::ops::Range<usize>,
}

impl VocabularyParallelRange {
    /// Validates non-empty in-bounds ownership.
    pub fn validate(&self) -> Result<(), Error> {
        if self.global_vocabulary == 0
            || self.local.is_empty()
            || self.local.end > self.global_vocabulary
        {
            return Err(Error::backend(format!(
                "invalid vocabulary-parallel range {:?} of {}",
                self.local, self.global_vocabulary
            )));
        }
        Ok(())
    }

    /// Validates that an operator's declared global row count is exactly this
    /// ownership range's global vocabulary.
    pub fn validate_global_rows(&self, rows: i32) -> Result<(), Error> {
        self.validate()?;
        if usize::try_from(rows).ok() != Some(self.global_vocabulary) {
            return Err(Error::backend(format!(
                "vocabulary-parallel operator declares {rows} rows but ownership covers {}",
                self.global_vocabulary
            )));
        }
        Ok(())
    }

    /// Returns the exact balanced peer widths after proving this rank's local
    /// range belongs to that partition.
    ///
    /// Vocabulary-parallel architectures select balanced contiguous
    /// rows. Encoding that invariant here prevents a concrete backend from
    /// silently substituting its own peer layout during uneven gather.
    pub fn balanced_peer_widths(
        &self,
        partitions: usize,
        rank: usize,
    ) -> Result<Vec<usize>, Error> {
        self.validate()?;
        if partitions == 0 || rank >= partitions {
            return Err(Error::backend(format!(
                "invalid vocabulary partition rank {rank} of {partitions}"
            )));
        }
        let base = self.global_vocabulary / partitions;
        let remainder = self.global_vocabulary % partitions;
        let widths = (0..partitions)
            .map(|peer| base + usize::from(peer < remainder))
            .collect::<Vec<_>>();
        let start = widths[..rank].iter().sum::<usize>();
        let expected = start..start + widths[rank];
        if self.local != expected {
            return Err(Error::backend(format!(
                "vocabulary-parallel range {:?} differs from balanced rank {rank} ownership {expected:?}",
                self.local
            )));
        }
        Ok(widths)
    }
}

#[cfg(test)]
mod vocabulary_parallel_range_tests {
    use super::VocabularyParallelRange;

    #[test]
    fn balanced_peer_widths_are_neutral_and_reject_local_layout_drift() {
        let range = VocabularyParallelRange {
            global_vocabulary: 11,
            local: 4..8,
        };
        assert_eq!(range.balanced_peer_widths(3, 1).unwrap(), [4, 4, 3]);

        let drifted = VocabularyParallelRange {
            global_vocabulary: 11,
            local: 3..7,
        };
        assert!(drifted.balanced_peer_widths(3, 1).is_err());
    }
}

/// Token validation and sentinel behavior for one embedding lookup.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum EmbeddingLookupPolicy {
    /// Every token must be a non-negative row index in the embedding table.
    Strict,
    /// One negative token value produces an exact zero row instead of indexing
    /// the embedding table. Every other token remains subject to strict lookup.
    ZeroSentinel(i32),
}

impl EmbeddingLookupPolicy {
    /// Validates that the optional sentinel cannot alias an ordinary row.
    pub fn validate(self) -> Result<(), Error> {
        if let Self::ZeroSentinel(sentinel) = self {
            if sentinel >= 0 {
                return Err(Error::backend(format!(
                    "embedding zero sentinel must be negative, got {sentinel}"
                )));
            }
        }
        Ok(())
    }
}

/// One named, positive-width component of a fused projection output.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FusedProjectionSegment {
    name: String,
    width: i32,
}

impl FusedProjectionSegment {
    /// Creates a validated component declaration.
    pub fn new(name: impl Into<String>, width: i32) -> Result<Self, Error> {
        let name = name.into();
        if name.trim().is_empty() || width <= 0 {
            return Err(Error::backend(format!(
                "fused projection segments require a name and positive width, got name={name:?} width={width}"
            )));
        }
        Ok(Self { name, width })
    }

    /// Returns the stable component name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the component width on the final projection axis.
    pub const fn width(&self) -> i32 {
        self.width
    }
}

/// Validated component-major layout of one fused affine projection.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FusedProjectionLayout {
    segments: Vec<FusedProjectionSegment>,
    output_width: i32,
}

impl FusedProjectionLayout {
    /// Validates ordered unique components and checked total width.
    pub fn new(segments: impl IntoIterator<Item = FusedProjectionSegment>) -> Result<Self, Error> {
        let segments = segments.into_iter().collect::<Vec<_>>();
        if segments.is_empty() {
            return Err(Error::backend(
                "fused projection layout must contain at least one segment",
            ));
        }
        let mut names = std::collections::BTreeSet::new();
        let mut output_width = 0i32;
        for segment in &segments {
            if !names.insert(segment.name.clone()) {
                return Err(Error::backend(format!(
                    "fused projection segment {:?} is duplicated",
                    segment.name
                )));
            }
            output_width = output_width.checked_add(segment.width).ok_or_else(|| {
                Error::backend("fused projection output width overflowed signed 32-bit geometry")
            })?;
        }
        Ok(Self {
            segments,
            output_width,
        })
    }

    /// Returns component declarations in physical output order.
    pub fn segments(&self) -> &[FusedProjectionSegment] {
        &self.segments
    }

    /// Returns the checked total output width.
    pub const fn output_width(&self) -> i32 {
        self.output_width
    }

    /// Splits one fused result into component-major final-axis views.
    pub fn split<T: Tensor>(&self, output: &T, context: &T::Context) -> Result<Vec<T>, Error> {
        let actual = output
            .shape()
            .last()
            .copied()
            .ok_or_else(|| Error::backend("fused projection output has no feature axis"))?;
        if actual != self.output_width {
            return Err(Error::backend(format!(
                "fused projection emitted width {actual}, expected {}",
                self.output_width
            )));
        }
        let mut start = 0i32;
        let mut indexes = vec![Index::Full; output.shape().len()];
        self.segments
            .iter()
            .map(|segment| {
                let end = start + segment.width;
                let last = indexes.len() - 1;
                indexes[last] = Index::Range(start, end);
                let selected = output.index(&indexes, context);
                start = end;
                selected
            })
            .collect()
    }
}

/// Parameterization policy for a reusable RMS normalization operator.
///
/// Architectures select the semantic scale form while the backend retains the
/// tensor implementation. In particular, learned-offset scales are evaluated
/// as `offset + weight`; the offset is not folded into checkpoint storage.
#[derive(Debug, Clone)]
pub enum NormalizationScale {
    /// Ordinary learned multiplicative scale.
    Learned(ParameterSpec),
    /// Learned scale offset by a fixed scalar at execution time.
    LearnedOffset {
        /// Stable checkpoint slot containing the learned offset tensor.
        weight: ParameterSpec,
        /// Fixed scalar added to every learned scale value.
        offset: f32,
    },
    /// RMS normalization without a learned scale.
    Unit,
}

/// Complete construction policy for an RMS normalization operator.
#[derive(Debug, Clone)]
pub struct NormalizationConstructionSpec {
    /// Normalized feature count.
    pub dimensions: i32,
    /// Numerical stability epsilon.
    pub epsilon: f32,
    /// Learned, learned-offset, or weightless scale policy.
    pub scale: NormalizationScale,
}

impl NormalizationConstructionSpec {
    /// Creates an RMS normalization with an ordinary learned scale.
    pub fn learned(dimensions: i32, epsilon: f32, weight: ParameterSpec) -> Self {
        Self {
            dimensions,
            epsilon,
            scale: NormalizationScale::Learned(weight),
        }
    }

    /// Validates feature geometry and fixed scalar policy.
    pub fn validate(&self) -> Result<(), Error> {
        let offset = match &self.scale {
            NormalizationScale::LearnedOffset { offset, .. } => Some(*offset),
            NormalizationScale::Learned(_) | NormalizationScale::Unit => None,
        };
        if self.dimensions <= 0
            || !self.epsilon.is_finite()
            || self.epsilon <= 0.0
            || offset.is_some_and(|offset| !offset.is_finite())
        {
            return Err(Error::backend(format!(
                "invalid RMS normalization construction: dimensions={} epsilon={} offset={offset:?}",
                self.dimensions, self.epsilon
            )));
        }
        Ok(())
    }
}

/// Fully normalized rotary-position algorithm selected by an architecture.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RotaryAlgorithm {
    /// Unscaled rotary embeddings.
    Default,
    /// Uniform position interpolation by an extension factor.
    Linear {
        /// Context extension factor.
        factor: f32,
    },
    /// Llama 3 piecewise wavelength scaling.
    Llama3 {
        /// Context extension factor.
        factor: f32,
        /// Low-frequency wavelength boundary.
        low_frequency_factor: f32,
        /// High-frequency wavelength boundary.
        high_frequency_factor: f32,
        /// Context length used during training.
        original_max_positions: i32,
    },
    /// Rotary embeddings over a configurable prefix of each head.
    Proportional {
        /// Frequency scaling factor.
        factor: f32,
        /// Fraction of the head covered by rotary embeddings.
        rotary_fraction: f32,
    },
    /// YaRN frequency interpolation and attention concentration.
    Yarn {
        /// Context extension factor.
        factor: f32,
        /// Context length used during training.
        original_max_positions: i32,
        /// Fast correction rotation count.
        beta_fast: f32,
        /// Slow correction rotation count.
        beta_slow: f32,
        /// Rotary concentration coefficient.
        concentration: f32,
        /// All-dimension attention-scale coefficient.
        attention_factor: f32,
        /// Whether correction boundaries are rounded to integer frequency slots.
        truncate: bool,
    },
}

impl RotaryAlgorithm {
    /// Validates the complete scalar geometry of this normalized algorithm.
    pub fn validate(self) -> Result<(), Error> {
        let positive = |value: f32| value.is_finite() && value > 0.0;
        let valid = match self {
            Self::Default => true,
            Self::Linear { factor } => positive(factor),
            Self::Llama3 {
                factor,
                low_frequency_factor,
                high_frequency_factor,
                original_max_positions,
            } => {
                positive(factor)
                    && positive(low_frequency_factor)
                    && positive(high_frequency_factor)
                    && high_frequency_factor > low_frequency_factor
                    && original_max_positions > 0
            }
            Self::Proportional {
                factor,
                rotary_fraction,
            } => positive(factor) && positive(rotary_fraction) && rotary_fraction <= 1.0,
            Self::Yarn {
                factor,
                original_max_positions,
                beta_fast,
                beta_slow,
                concentration,
                attention_factor,
                ..
            } => {
                positive(factor)
                    && original_max_positions > 0
                    && positive(beta_fast)
                    && positive(beta_slow)
                    && beta_fast > beta_slow
                    && positive(concentration)
                    && attention_factor.is_finite()
                    && attention_factor >= 0.0
            }
        };
        if valid {
            Ok(())
        } else {
            Err(Error::backend(format!(
                "invalid normalized rotary algorithm: {self:?}"
            )))
        }
    }
}

/// Complete backend-neutral rotary-position construction specification.
#[derive(Debug, Clone, Copy)]
pub struct RotarySpec {
    /// Rotated head dimensions.
    pub dimensions: i32,
    /// Base frequency.
    pub base: f32,
    /// Whether adjacent pairs are rotated instead of split halves.
    pub traditional: bool,
    /// Fully normalized algorithm and scalar policy.
    pub algorithm: RotaryAlgorithm,
}

/// Backend-native affine projection used by shared architectures.
pub trait LinearOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Applies the projection without host materialization.
    fn forward(&mut self, input: &T, context: &T::Context) -> Result<T, Error>;
}

/// Backend-native token embedding used by shared architectures.
pub trait EmbeddingOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Looks up token embeddings.
    fn forward(&mut self, input: &T, context: &T::Context) -> Result<T, Error>;
    /// Looks up token embeddings under an explicit validation/sentinel policy.
    fn lookup(
        &mut self,
        input: &T,
        policy: EmbeddingLookupPolicy,
        context: &T::Context,
    ) -> Result<T, Error> {
        policy.validate()?;
        match policy {
            EmbeddingLookupPolicy::Strict => self.forward(input, context),
            EmbeddingLookupPolicy::ZeroSentinel(sentinel) => Err(Error::backend(format!(
                "embedding backend does not implement zero sentinel {sentinel}"
            ))),
        }
    }
    /// Projects hidden states through the transposed embedding table.
    fn as_linear(&mut self, input: &T, context: &T::Context) -> Result<T, Error>;
}

/// Backend-native normalization operator.
pub trait NormalizationOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Applies normalization.
    fn forward(&mut self, input: &T, context: &T::Context) -> Result<T, Error>;
}

/// Construction specification for a normalized low-rank projection.
#[derive(Debug, Clone)]
pub struct LowRankProjectionSpec {
    /// Optional input-to-rank projection. When omitted, the input is already
    /// represented in rank space.
    pub first: Option<LinearSpec>,
    /// Normalization applied in rank space.
    pub normalization: NormalizationConstructionSpec,
    /// Rank-to-output projection.
    pub second: LinearSpec,
}

impl LowRankProjectionSpec {
    /// Validates that both projections and normalization agree on rank width.
    pub fn validate(&self) -> Result<(), Error> {
        let rank = self.normalization.dimensions;
        if rank <= 0 {
            return Err(Error::backend(format!(
                "low-rank normalization dimensions must be positive, got {rank}"
            )));
        }
        if self.second.input != rank {
            return Err(Error::backend(format!(
                "low-rank second projection expects {} inputs but rank width is {rank}",
                self.second.input
            )));
        }
        if let Some(first) = &self.first {
            if first.output != rank {
                return Err(Error::backend(format!(
                    "low-rank first projection emits {} values but rank width is {rank}",
                    first.output
                )));
            }
        }
        Ok(())
    }
}

/// Reusable normalized low-rank projection with statically dispatched backend
/// operators.
#[derive(Debug, Clone, Parameterized)]
#[parameterized(tensor = "B::Tensor")]
pub struct LowRankProjection<B: NeuralBackend> {
    /// Optional input-to-rank projection.
    pub first: Option<B::Linear>,
    /// Rank-space normalization.
    pub normalization: B::Normalization,
    /// Rank-to-output projection.
    pub second: B::Linear,
}

impl<B: NeuralBackend> LowRankProjection<B> {
    /// Builds an unloaded low-rank projection from architecture-owned
    /// parameter identities and physical formats.
    pub fn new(
        spec: LowRankProjectionSpec,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<Self, Error> {
        spec.validate()?;
        Ok(Self {
            first: spec
                .first
                .map(|projection| B::linear(projection, context))
                .transpose()?,
            normalization: B::normalization(spec.normalization, context)?,
            second: B::linear(spec.second, context)?,
        })
    }

    /// Applies the optional first projection, rank normalization, and second
    /// projection without backend-value conversion.
    pub fn forward(
        &mut self,
        input: &B::Tensor,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<B::Tensor, Error> {
        let rank = match &mut self.first {
            Some(first) => first.forward(input, context)?,
            None => input.clone(),
        };
        let rank = self.normalization.forward(&rank, context)?;
        self.second.forward(&rank, context)
    }
}

/// Backend-native rotary-position operator.
pub trait RotaryOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Applies the architecture-selected rotary position source.
    fn forward(
        &mut self,
        input: &T,
        position: RotaryPosition<'_, T>,
        context: &T::Context,
    ) -> Result<T, Error>;

    /// Applies rotary positions only to the selected final-axis subspace and
    /// leaves every other feature unchanged.
    fn forward_subspace(
        &mut self,
        input: &T,
        subspace: RotarySubspace,
        position: RotaryPosition<'_, T>,
        context: &T::Context,
    ) -> Result<T, Error> {
        let width = *input
            .shape()
            .last()
            .ok_or_else(|| Error::backend("rotary input must have a feature axis"))?;
        let (start, dimensions) = subspace.resolve(width)?;
        if start == 0 && dimensions == width {
            return self.forward(input, position, context);
        }
        let end = start + dimensions;
        let mut indexes = vec![Index::Full; input.shape().len()];
        indexes[input.shape().len() - 1] = Index::Range(start, end);
        let selected = input.index(&indexes, context)?;
        let rotated = self.forward(&selected, position, context)?;
        let mut pieces = Vec::with_capacity(3);
        if start > 0 {
            indexes[input.shape().len() - 1] = Index::Range(0, start);
            pieces.push(input.index(&indexes, context)?);
        }
        pieces.push(rotated);
        if end < width {
            indexes[input.shape().len() - 1] = Index::Range(end, width);
            pieces.push(input.index(&indexes, context)?);
        }
        T::concatenate(&pieces, -1, context)
    }
}

/// Final-axis feature range selected for rotary position encoding.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum RotarySubspace {
    /// Rotate the complete final feature axis.
    Full,
    /// Rotate one contiguous half-open final-axis range.
    Range {
        /// First rotated feature.
        start: i32,
        /// Number of rotated features.
        dimensions: i32,
    },
}

impl RotarySubspace {
    fn resolve(self, width: i32) -> Result<(i32, i32), Error> {
        let (start, dimensions) = match self {
            Self::Full => (0, width),
            Self::Range { start, dimensions } => (start, dimensions),
        };
        if width <= 0
            || start < 0
            || dimensions <= 0
            || dimensions % 2 != 0
            || start > width - dimensions
        {
            return Err(Error::backend(format!(
                "rotary subspace start={start} dimensions={dimensions} is invalid for width {width}"
            )));
        }
        Ok((start, dimensions))
    }
}

/// Position data supplied to a backend-native rotary operator.
#[derive(Debug)]
pub enum RotaryPosition<'a, T> {
    /// Ordinary contiguous sequence positions beginning at this offset.
    Offset(i32),
    /// Caller-provided cosine and sine tensors for explicit positions.
    Embeddings {
        /// Cosine values shaped for the input sequence and rotary dimensions.
        cosine: &'a T,
        /// Sine values shaped for the input sequence and rotary dimensions.
        sine: &'a T,
    },
}

impl<T> Copy for RotaryPosition<'_, T> {}

impl<T> Clone for RotaryPosition<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

/// Architecture-selected scoring policy for top-k group selection.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum GroupScoring {
    /// Apply softmax across all group logits before selection.
    Softmax,
    /// Select the largest raw logits, then softmax only the selected entries.
    SelectedSoftmax,
    /// Apply elementwise sigmoid scores before grouped selection.
    Sigmoid,
    /// Apply the square root of softplus before selection.
    SqrtSoftplus,
}

/// Backend-neutral top-k group-selection semantics.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TopKGroupSelectionSpec {
    group_count: i32,
    top_k: i32,
    scoring: GroupScoring,
    normalize_selected: bool,
    normalization_epsilon: f32,
    coefficient_scale: f32,
    selection_partitions: i32,
    selected_groups: i32,
}

/// Construction specification for a learned top-k selector projection.
#[derive(Debug, Clone)]
pub struct TopKGroupSelectorSpec {
    /// Hidden width consumed by the selector projection.
    input_dimensions: i32,
    /// Stable selector projection parameter identity.
    weight: ParameterSpec,
    /// Optional ordinary projection bias. This contributes to selector logits
    /// before scoring, selection, and selected-score normalization.
    bias: Option<ParameterSpec>,
    /// Optional correction bias used only to choose group IDs. Gathered
    /// selection scores remain unbiased.
    correction_bias: Option<ParameterSpec>,
    /// Optional learned scaling applied after weightless RMS normalization of
    /// the selector input.
    input_transform: Option<SelectorInputTransformSpec>,
    /// Optional learned per-group multiplier gathered after selection.
    coefficient_scale: Option<ParameterSpec>,
    /// Physical encoding and exact companion identities of the selector projection.
    format: LinearFormatSpec,
    /// Architecture-selected scoring and selection semantics.
    selection: TopKGroupSelectionSpec,
}

/// Learned normalization and scale applied before a selector projection.
#[derive(Debug, Clone)]
pub struct SelectorInputTransformSpec {
    /// Weightless RMS-normalization epsilon.
    epsilon: f32,
    /// Learned feature-wise multiplier.
    scale: ParameterSpec,
    /// Whether to additionally multiply by `1 / sqrt(input_dimensions)`.
    inverse_sqrt_dimensions: bool,
}

impl SelectorInputTransformSpec {
    /// Creates a validated selector-input transformation.
    pub fn new(
        epsilon: f32,
        scale: ParameterSpec,
        inverse_sqrt_dimensions: bool,
    ) -> Result<Self, Error> {
        if !epsilon.is_finite() || epsilon < 0.0 {
            return Err(Error::backend(
                "selector input RMS epsilon must be finite and nonnegative",
            ));
        }
        Ok(Self {
            epsilon,
            scale,
            inverse_sqrt_dimensions,
        })
    }

    /// Returns the RMS epsilon.
    pub const fn epsilon(&self) -> f32 {
        self.epsilon
    }
    /// Returns the learned input scale.
    pub const fn scale(&self) -> &ParameterSpec {
        &self.scale
    }
    /// Returns whether inverse-square-root width scaling is selected.
    pub const fn inverse_sqrt_dimensions(&self) -> bool {
        self.inverse_sqrt_dimensions
    }
}

impl TopKGroupSelectorSpec {
    /// Creates a selector projection with no optional parameters.
    pub fn new(
        input_dimensions: i32,
        weight: ParameterSpec,
        format: LinearFormatSpec,
        selection: TopKGroupSelectionSpec,
    ) -> Result<Self, Error> {
        let spec = Self {
            input_dimensions,
            weight,
            bias: None,
            correction_bias: None,
            input_transform: None,
            coefficient_scale: None,
            format,
            selection,
        };
        spec.validate()?;
        Ok(spec)
    }

    /// Adds an ordinary projection bias.
    pub fn with_bias(mut self, bias: ParameterSpec) -> Result<Self, Error> {
        self.bias = Some(bias);
        self.validate()?;
        Ok(self)
    }
    /// Adds a selection-only correction bias.
    pub fn with_correction_bias(mut self, bias: ParameterSpec) -> Result<Self, Error> {
        self.correction_bias = Some(bias);
        self.validate()?;
        Ok(self)
    }
    /// Adds an input normalization transformation.
    pub fn with_input_transform(mut self, transform: SelectorInputTransformSpec) -> Self {
        self.input_transform = Some(transform);
        self
    }
    /// Adds a learned coefficient multiplier.
    pub fn with_coefficient_scale(mut self, scale: ParameterSpec) -> Self {
        self.coefficient_scale = Some(scale);
        self
    }
    /// Returns the input width.
    pub const fn input_dimensions(&self) -> i32 {
        self.input_dimensions
    }
    /// Returns the selector projection parameter.
    pub const fn weight(&self) -> &ParameterSpec {
        &self.weight
    }
    /// Returns the ordinary projection bias.
    pub const fn bias(&self) -> Option<&ParameterSpec> {
        self.bias.as_ref()
    }
    /// Returns the selection correction bias.
    pub const fn correction_bias(&self) -> Option<&ParameterSpec> {
        self.correction_bias.as_ref()
    }
    /// Returns the optional input transformation.
    pub const fn input_transform(&self) -> Option<&SelectorInputTransformSpec> {
        self.input_transform.as_ref()
    }
    /// Returns the learned coefficient multiplier.
    pub const fn coefficient_scale(&self) -> Option<&ParameterSpec> {
        self.coefficient_scale.as_ref()
    }
    /// Returns the physical projection format.
    pub const fn format(&self) -> &LinearFormatSpec {
        &self.format
    }
    /// Returns the group-selection semantics.
    pub const fn selection(&self) -> TopKGroupSelectionSpec {
        self.selection
    }

    /// Validates positive input geometry.
    pub fn validate(&self) -> Result<(), Error> {
        self.format.validate_for_weight(&self.weight)?;
        if self.input_dimensions <= 0 {
            return Err(Error::backend(format!(
                "selector input dimensions must be positive, got {}",
                self.input_dimensions
            )));
        }
        if self
            .input_transform
            .as_ref()
            .is_some_and(|transform| !transform.epsilon.is_finite() || transform.epsilon < 0.0)
        {
            return Err(Error::backend(
                "selector input RMS epsilon must be finite and nonnegative",
            ));
        }
        if self
            .bias
            .as_ref()
            .zip(self.correction_bias.as_ref())
            .is_some_and(|(bias, correction_bias)| bias.id == correction_bias.id)
        {
            return Err(Error::backend(
                "selector projection bias and correction bias require distinct parameter identities",
            ));
        }
        Ok(())
    }
}

impl TopKGroupSelectionSpec {
    /// Creates a validated top-k group-selection policy.
    pub fn new(
        group_count: i32,
        top_k: i32,
        scoring: GroupScoring,
        normalize_selected: bool,
    ) -> Result<Self, Error> {
        if group_count <= 0 {
            return Err(Error::backend(format!(
                "group count must be positive, got {group_count}"
            )));
        }
        if top_k <= 0 || top_k > group_count {
            return Err(Error::backend(format!(
                "top-k selection count must be in 1..={group_count}, got {top_k}"
            )));
        }
        Ok(Self {
            group_count,
            top_k,
            scoring,
            normalize_selected,
            normalization_epsilon: 0.0,
            coefficient_scale: 1.0,
            selection_partitions: 1,
            selected_groups: 1,
        })
    }

    /// Selects grouped selection semantics.
    pub fn with_groups(
        mut self,
        selection_partitions: i32,
        selected_groups: i32,
    ) -> Result<Self, Error> {
        if selection_partitions <= 0
            || selected_groups <= 0
            || selected_groups > selection_partitions
            || self.group_count % selection_partitions != 0
            || self.top_k > selected_groups * (self.group_count / selection_partitions)
        {
            return Err(Error::backend(format!(
                "invalid grouped selection geometry: group_count={} top_k={} partitions={selection_partitions} selected_partitions={selected_groups}",
                self.group_count, self.top_k
            )));
        }
        self.selection_partitions = selection_partitions;
        self.selected_groups = selected_groups;
        Ok(self)
    }

    /// Selects denominator epsilon and final grouped contribution scale.
    pub fn with_weight_policy(
        mut self,
        normalization_epsilon: f32,
        coefficient_scale: f32,
    ) -> Result<Self, Error> {
        if !normalization_epsilon.is_finite()
            || normalization_epsilon < 0.0
            || !coefficient_scale.is_finite()
            || coefficient_scale <= 0.0
        {
            return Err(Error::backend(
                "selection normalization epsilon must be finite and nonnegative and grouped scaling must be finite and positive",
            ));
        }
        self.normalization_epsilon = normalization_epsilon;
        self.coefficient_scale = coefficient_scale;
        Ok(self)
    }

    /// Returns the total number of selectable groups.
    pub const fn group_count(self) -> i32 {
        self.group_count
    }

    /// Returns the number of selected groups per token.
    pub const fn top_k(self) -> i32 {
        self.top_k
    }

    /// Returns the score transformation applied before selection.
    pub const fn scoring(self) -> GroupScoring {
        self.scoring
    }

    /// Returns whether selected scores are renormalized to sum to one.
    pub const fn normalize_selected(self) -> bool {
        self.normalize_selected
    }

    /// Returns the epsilon added to selected-score normalization.
    pub const fn normalization_epsilon(self) -> f32 {
        self.normalization_epsilon
    }

    /// Returns the final grouped contribution multiplier.
    pub const fn coefficient_scale(self) -> f32 {
        self.coefficient_scale
    }

    /// Returns the number of equal contiguous groups.
    pub const fn selection_partitions(self) -> i32 {
        self.selection_partitions
    }

    /// Returns the number of groups eligible for group selection.
    pub const fn selected_groups(self) -> i32 {
        self.selected_groups
    }
}

/// Backend-native result of one top-k group selection.
#[derive(Debug, Clone)]
pub struct GroupSelection<T> {
    /// Selected group IDs shaped `[..., top_k]`.
    group_indices: T,
    /// Selected scores before optional top-k renormalization.
    selected_scores: T,
    /// Final normalized or unnormalized selection weights.
    coefficients: T,
}

impl<T> GroupSelection<T> {
    /// Consumes a decision into IDs, selected scores, and effective coefficients.
    pub fn into_parts(self) -> (T, T, T) {
        (self.group_indices, self.selected_scores, self.coefficients)
    }
    /// Creates one selected group batch.
    pub fn new(group_indices: T, selected_scores: T, coefficients: T) -> Self {
        Self {
            group_indices,
            selected_scores,
            coefficients,
        }
    }
    /// Returns selected group indices.
    pub const fn group_indices(&self) -> &T {
        &self.group_indices
    }
    /// Returns selected pre-normalization scores.
    pub const fn selected_scores(&self) -> &T {
        &self.selected_scores
    }
    /// Returns final group coefficients.
    pub const fn coefficients(&self) -> &T {
        &self.coefficients
    }
}

/// Geometry for joint selected-group and always-on-group weighting.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct JointGroupSelectionSpec {
    selectable_groups: i32,
    always_on_groups: i32,
    top_k: i32,
    coefficient_scale: f32,
}

impl JointGroupSelectionSpec {
    /// Creates validated joint-selection geometry.
    pub fn new(
        selectable_groups: i32,
        always_on_groups: i32,
        top_k: i32,
        coefficient_scale: f32,
    ) -> Result<Self, Error> {
        if selectable_groups <= 0
            || always_on_groups <= 0
            || top_k <= 0
            || top_k > selectable_groups
            || !coefficient_scale.is_finite()
            || coefficient_scale <= 0.0
        {
            return Err(Error::backend(format!(
                "invalid joint group-selection geometry selectable={selectable_groups} always_on={always_on_groups} top_k={top_k} coefficient_scale={coefficient_scale}"
            )));
        }
        Ok(Self {
            selectable_groups,
            always_on_groups,
            top_k,
            coefficient_scale,
        })
    }

    /// Returns the number of selectable groups.
    pub const fn selectable_groups(self) -> i32 {
        self.selectable_groups
    }

    /// Returns the number of always-on groups.
    pub const fn always_on_groups(self) -> i32 {
        self.always_on_groups
    }

    /// Returns the selected group count per row.
    pub const fn top_k(self) -> i32 {
        self.top_k
    }

    /// Returns the fixed coefficient multiplier.
    pub const fn coefficient_scale(self) -> f32 {
        self.coefficient_scale
    }
}

/// Joint sigmoid selection request with selected groups and always-on
/// shared groups normalized in one probability distribution.
#[derive(Debug, Clone, Copy)]
pub struct JointGroupSelectionInput<'a, T> {
    /// Hidden states shaped `[..., hidden]`.
    hidden: &'a T,
    /// Projection shaped `[selectable_groups + always_on_groups, hidden]`.
    weight: &'a T,
    /// Correction bias used only for grouped top-k selection.
    correction_bias: &'a T,
    /// Learned scalar multiplier applied to all final selection weights.
    global_scale: &'a T,
    /// Joint-selection geometry.
    selection: JointGroupSelectionSpec,
}

impl<'a, T: Tensor> JointGroupSelectionInput<'a, T> {
    /// Creates a validated joint group-selection request.
    pub fn new(
        hidden: &'a T,
        weight: &'a T,
        correction_bias: &'a T,
        global_scale: &'a T,
        selection: JointGroupSelectionSpec,
    ) -> Result<Self, Error> {
        let input = Self {
            hidden,
            weight,
            correction_bias,
            global_scale,
            selection,
        };
        input.validate()?;
        Ok(input)
    }
    /// Returns hidden states.
    pub const fn hidden(&self) -> &'a T {
        self.hidden
    }
    /// Returns the selection projection.
    pub const fn weight(&self) -> &'a T {
        self.weight
    }
    /// Returns the selection-only correction bias.
    pub const fn correction_bias(&self) -> &'a T {
        self.correction_bias
    }
    /// Returns the learned global scale.
    pub const fn global_scale(&self) -> &'a T {
        self.global_scale
    }
    /// Returns the number of selectable groups.
    pub const fn selectable_groups(&self) -> i32 {
        self.selection.selectable_groups()
    }
    /// Returns the number of always-on groups.
    pub const fn always_on_groups(&self) -> i32 {
        self.selection.always_on_groups()
    }
    /// Returns the selected group count per row.
    pub const fn top_k(&self) -> i32 {
        self.selection.top_k()
    }
    /// Returns the fixed coefficient multiplier.
    pub const fn coefficient_scale(&self) -> f32 {
        self.selection.coefficient_scale()
    }
}

impl<T: Tensor> JointGroupSelectionInput<'_, T> {
    /// Validates exact projection, bias, and scalar geometry.
    pub fn validate(&self) -> Result<(), Error> {
        let hidden = self.hidden.shape();
        let weight = self.weight.shape();
        let bias = self.correction_bias.shape();
        let scale = self.global_scale.shape();
        let hidden_width = hidden.last().copied().unwrap_or(0);
        if hidden.len() < 2
            || weight
                != [
                    self.selectable_groups() + self.always_on_groups(),
                    hidden_width,
                ]
            || bias != [self.selectable_groups()]
            || scale != [1]
        {
            return Err(Error::backend(format!(
                "invalid joint group selection tensors hidden={hidden:?} weight={weight:?} bias={bias:?} scale={scale:?} selectable={} always_on={} top_k={}",
                self.selectable_groups(),
                self.always_on_groups(),
                self.top_k(),
            )));
        }
        Ok(())
    }
}

/// Backend-native result of joint grouped and shared group weighting.
#[derive(Debug, Clone)]
pub struct JointGroupSelection<T> {
    /// Selected primary group IDs shaped `[tokens, top_k]`; integer dtype is
    /// backend-defined and accepted by the corresponding group operator.
    primary_indices: T,
    /// Grouped group weights shaped `[tokens, top_k]`.
    primary_coefficients: T,
    /// Always-on shared group weights shaped `[tokens, always_on_groups]`.
    always_on_coefficients: T,
}

impl<T> JointGroupSelection<T> {
    /// Creates one joint selection result.
    pub fn new(primary_indices: T, primary_coefficients: T, always_on_coefficients: T) -> Self {
        Self {
            primary_indices,
            primary_coefficients,
            always_on_coefficients,
        }
    }
    /// Returns selected primary-group indices.
    pub const fn primary_indices(&self) -> &T {
        &self.primary_indices
    }
    /// Returns primary-group coefficients.
    pub const fn primary_coefficients(&self) -> &T {
        &self.primary_coefficients
    }
    /// Returns always-on group coefficients.
    pub const fn always_on_coefficients(&self) -> &T {
        &self.always_on_coefficients
    }
}

/// Activation applied to the gate branch of a grouped gated product.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum GatedProductActivation {
    /// `gate * sigmoid(sigmoid_multiplier * gate)`.
    Silu,
    /// Approximate Gaussian error linear unit.
    GeluApproximate,
}

/// Validated equation policy for a gated product group.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GatedProductPolicy {
    activation: GatedProductActivation,
    gate_upper_bound: Option<f32>,
    up_absolute_bound: Option<f32>,
    sigmoid_multiplier: f32,
    up_offset: f32,
}

impl GatedProductPolicy {
    /// Creates a validated gated-product equation.
    pub fn new(
        activation: GatedProductActivation,
        gate_upper_bound: Option<f32>,
        up_absolute_bound: Option<f32>,
        sigmoid_multiplier: f32,
        up_offset: f32,
    ) -> Result<Self, Error> {
        let policy = Self {
            activation,
            gate_upper_bound,
            up_absolute_bound,
            sigmoid_multiplier,
            up_offset,
        };
        policy.validate()?;
        Ok(policy)
    }

    /// Ordinary unbounded SiLU gating.
    pub const fn ordinary_silu() -> Self {
        Self {
            activation: GatedProductActivation::Silu,
            gate_upper_bound: None,
            up_absolute_bound: None,
            sigmoid_multiplier: 1.0,
            up_offset: 0.0,
        }
    }

    /// Ordinary unbounded approximate-GELU gating.
    pub const fn ordinary_gelu_approximate() -> Self {
        Self {
            activation: GatedProductActivation::GeluApproximate,
            ..Self::ordinary_silu()
        }
    }

    /// Creates ordinary SiLU gating with the same positive gate and up bound.
    pub fn bounded_silu(bound: f32) -> Result<Self, Error> {
        Self::new(
            GatedProductActivation::Silu,
            Some(bound),
            Some(bound),
            1.0,
            0.0,
        )
    }

    /// Validates finite scalars and positive bounds/multiplier.
    pub fn validate(self) -> Result<(), Error> {
        if self
            .gate_upper_bound
            .is_some_and(|bound| !bound.is_finite() || bound <= 0.0)
            || self
                .up_absolute_bound
                .is_some_and(|bound| !bound.is_finite() || bound <= 0.0)
            || !self.sigmoid_multiplier.is_finite()
            || self.sigmoid_multiplier <= 0.0
            || !self.up_offset.is_finite()
        {
            return Err(Error::backend(format!(
                "invalid gated-product policy: {self:?}"
            )));
        }
        Ok(())
    }

    /// Gate activation.
    pub const fn activation(self) -> GatedProductActivation {
        self.activation
    }

    /// Optional upper bound applied to the gate branch before activation.
    pub const fn gate_upper_bound(self) -> Option<f32> {
        self.gate_upper_bound
    }

    /// Optional symmetric absolute bound applied to the up branch.
    pub const fn up_absolute_bound(self) -> Option<f32> {
        self.up_absolute_bound
    }

    /// Multiplier inside the sigmoid for SiLU gating.
    pub const fn sigmoid_multiplier(self) -> f32 {
        self.sigmoid_multiplier
    }

    /// Offset added to the up branch after optional clipping.
    pub const fn up_offset(self) -> f32 {
        self.up_offset
    }
}

impl Default for GatedProductPolicy {
    fn default() -> Self {
        Self::ordinary_silu()
    }
}

/// Statically dispatched top-k selector.
pub trait GroupSelectionOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Executes a validated pre-dispatch control using this selector's ordinary
    /// scoring, grouping, normalization and scaling policy. Unsupported backends
    /// reject rather than silently dispatching ordinary routes.
    fn select_intervened(
        &mut self,
        _input: &T,
        _control: &routing_intervention::GroupSelectionControl,
        _context: &T::Context,
    ) -> Result<routing_intervention::IntervenedGroupSelection<T>, Error> {
        Err(Error::backend(
            "pre-dispatch routing interventions are unsupported",
        ))
    }

    /// Selects group IDs and selection weights without host materialization.
    fn select(&mut self, logits: &T, context: &T::Context) -> Result<GroupSelection<T>, Error>;

    /// Computes scores and weights for caller-selected global group IDs.
    fn select_indices(
        &mut self,
        input: &T,
        group_indices: &T,
        context: &T::Context,
    ) -> Result<GroupSelection<T>, Error>;
}

/// Parameter identities for one gated-product group or one packed group axis.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct GatedProductGroupParameters {
    /// Gating projection weight.
    gate: GroupedProjectionSpec,
    /// Up projection weight.
    up: GroupedProjectionSpec,
    /// Down projection weight.
    down: GroupedProjectionSpec,
}

impl GatedProductGroupParameters {
    /// Creates one independently addressable gated-product parameter group.
    pub fn new(
        gate: GroupedProjectionSpec,
        up: GroupedProjectionSpec,
        down: GroupedProjectionSpec,
    ) -> Self {
        Self { gate, up, down }
    }
    /// Returns the gate projection.
    pub const fn gate(&self) -> &GroupedProjectionSpec {
        &self.gate
    }
    /// Returns the up projection.
    pub const fn up(&self) -> &GroupedProjectionSpec {
        &self.up
    }
    /// Returns the down projection.
    pub const fn down(&self) -> &GroupedProjectionSpec {
        &self.down
    }
}

/// One group projection identity and optional physical encoding.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct GroupedProjectionSpec {
    /// Stable logical parameter identity.
    weight: ParameterSpec,
    /// Optional ordinary per-output projection bias.
    bias: Option<ParameterSpec>,
    /// Complete physical checkpoint encoding and exact companion identities.
    format: LinearFormatSpec,
}

impl GroupedProjectionSpec {
    /// Creates one validated grouped projection description.
    pub fn new(
        weight: ParameterSpec,
        bias: Option<ParameterSpec>,
        format: LinearFormatSpec,
    ) -> Result<Self, Error> {
        let spec = Self {
            weight,
            bias,
            format,
        };
        spec.validate()?;
        Ok(spec)
    }
    /// Returns the matrix parameter.
    pub const fn weight(&self) -> &ParameterSpec {
        &self.weight
    }
    /// Returns the optional output bias.
    pub const fn bias(&self) -> Option<&ParameterSpec> {
        self.bias.as_ref()
    }
    /// Returns the physical matrix format.
    pub const fn format(&self) -> &LinearFormatSpec {
        &self.format
    }
    fn validate(&self) -> Result<(), Error> {
        self.format.validate_for_weight(&self.weight)?;
        let parameters = self.parameters();
        for (index, parameter) in parameters.iter().enumerate() {
            if parameters[index + 1..]
                .iter()
                .any(|candidate| candidate.id == parameter.id)
            {
                return Err(Error::backend(format!(
                    "grouped projection reuses parameter identity {:?}",
                    parameter.id
                )));
            }
        }
        Ok(())
    }

    /// Returns weight, optional bias, and physical companions in binding order.
    pub fn parameters(&self) -> Vec<&ParameterSpec> {
        let mut parameters = vec![&self.weight];
        parameters.extend(self.bias.as_ref());
        parameters.extend(self.format.scale());
        parameters.extend(self.format.affine_bias());
        parameters
    }
}

/// Logical parameter layout for a gated-product bank.
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::large_enum_variant)] // Packed layout stays inline on the construction hot path.
#[non_exhaustive]
pub enum GatedProductGroupLayout {
    /// Component-major fused gate-then-up and down tensors whose leading axis
    /// indexes groups.
    Packed {
        /// Concatenated gate/up projection.
        gate_up: GroupedProjectionSpec,
        /// Down projection.
        down: GroupedProjectionSpec,
    },
    /// Independently materialized group parameter triples in group-ID order.
    Independent(Vec<GatedProductGroupParameters>),
}

/// Complete architecture-owned construction specification for grouped gated-product groups.
#[derive(Debug, Clone, PartialEq)]
pub struct GroupedGatedProductSpec {
    /// Number of groups.
    group_count: i32,
    /// Input hidden width.
    input_dimensions: i32,
    /// Per-group intermediate width.
    intermediate_dimensions: i32,
    /// Output hidden width.
    output_dimensions: i32,
    /// Exact gate activation, bounds, multiplier, and up offset.
    policy: GatedProductPolicy,
    /// Stable logical parameter identities and storage organization.
    layout: GatedProductGroupLayout,
}

impl GroupedGatedProductSpec {
    /// Creates one validated grouped gated-product mechanism request.
    pub fn new(
        group_count: i32,
        input_dimensions: i32,
        intermediate_dimensions: i32,
        output_dimensions: i32,
        policy: GatedProductPolicy,
        layout: GatedProductGroupLayout,
    ) -> Result<Self, Error> {
        let spec = Self {
            group_count,
            input_dimensions,
            intermediate_dimensions,
            output_dimensions,
            policy,
            layout,
        };
        spec.validate()?;
        Ok(spec)
    }
    /// Returns a copy with placement-resolved group geometry.
    pub fn with_group_geometry(
        mut self,
        group_count: i32,
        intermediate_dimensions: i32,
    ) -> Result<Self, Error> {
        self.group_count = group_count;
        self.intermediate_dimensions = intermediate_dimensions;
        self.validate()?;
        Ok(self)
    }
    /// Returns the number of parameter groups.
    pub const fn group_count(&self) -> i32 {
        self.group_count
    }
    /// Returns the input width.
    pub const fn input_dimensions(&self) -> i32 {
        self.input_dimensions
    }
    /// Returns the per-group intermediate width.
    pub const fn intermediate_dimensions(&self) -> i32 {
        self.intermediate_dimensions
    }
    /// Returns the output width.
    pub const fn output_dimensions(&self) -> i32 {
        self.output_dimensions
    }
    /// Returns the gated-product equation policy.
    pub const fn policy(&self) -> GatedProductPolicy {
        self.policy
    }
    /// Returns the parameter-bank layout.
    pub const fn layout(&self) -> &GatedProductGroupLayout {
        &self.layout
    }
    /// Validates positive geometry and exact independent-group cardinality.
    pub fn validate(&self) -> Result<(), Error> {
        for (name, value) in [
            ("group_count", self.group_count),
            ("input_dimensions", self.input_dimensions),
            ("intermediate_dimensions", self.intermediate_dimensions),
            ("output_dimensions", self.output_dimensions),
        ] {
            if value <= 0 {
                return Err(Error::backend(format!(
                    "gated-product group-bank {name} must be positive, got {value}"
                )));
            }
        }
        self.policy.validate()?;
        if let GatedProductGroupLayout::Independent(groups) = &self.layout {
            let expected = usize::try_from(self.group_count).map_err(Error::backend)?;
            if groups.len() != expected {
                return Err(Error::backend(format!(
                    "independent gated-product bank has {} groups, expected {expected}",
                    groups.len()
                )));
            }
        }
        let projections = match &self.layout {
            GatedProductGroupLayout::Packed { gate_up, down } => vec![gate_up, down],
            GatedProductGroupLayout::Independent(groups) => groups
                .iter()
                .flat_map(|group| [&group.gate, &group.up, &group.down])
                .collect(),
        };
        let mut identities = std::collections::BTreeSet::new();
        for projection in projections {
            projection.validate()?;
            for parameter in projection.parameters() {
                let identity = &parameter.id;
                if !identities.insert(identity) {
                    return Err(Error::backend(format!(
                        "gated-product group parameter identity {identity} is duplicated"
                    )));
                }
            }
        }
        Ok(())
    }
}

/// Rank-local grouped output split around the tensor-parallel reduction.
#[derive(Debug, Clone)]
pub struct TensorParallelGroupedOutput<T> {
    /// Rank-local projection contribution to all-sum.
    reducible: T,
    /// Replicated selection-weighted down bias added once after all-sum.
    post_reduce: Option<T>,
}

impl<T> TensorParallelGroupedOutput<T> {
    /// Creates one rank-local grouped projection output.
    pub fn new(reducible: T, post_reduce: Option<T>) -> Self {
        Self {
            reducible,
            post_reduce,
        }
    }
    /// Returns the rank-local reducible tensor.
    pub const fn reducible(&self) -> &T {
        &self.reducible
    }
    /// Returns the optional post-reduction term.
    pub const fn post_reduce(&self) -> Option<&T> {
        self.post_reduce.as_ref()
    }
    /// Consumes the output into its reduction contribution and post-reduction term.
    pub fn into_parts(self) -> (T, Option<T>) {
        (self.reducible, self.post_reduce)
    }
}

/// Statically dispatched grouped gated-product bank.
pub trait GroupedGatedProductOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Returns the architecture-owned construction specification used by this bank.
    ///
    /// Runtime providers use this metadata when they substitute cached or remote
    /// parameters for the resident bank, so every execution path retains the
    /// same geometry, encoding, bias, and activation policy.
    fn spec(&self) -> &GroupedGatedProductSpec;

    /// Executes selected groups and combines their outputs by selection weight.
    fn forward_grouped(
        &mut self,
        input: &T,
        selections: &GroupSelection<T>,
        context: &T::Context,
    ) -> Result<T, Error>;
}

/// Additive mechanism for tensor-parallel grouped gated-product partials.
pub trait TensorParallelGroupedGatedProductOperator<T: Tensor>:
    GroupedGatedProductOperator<T>
{
    /// Executes a rank-local partial and separates replicated down bias for one
    /// literal post-reduction addition.
    fn forward_grouped_tensor_parallel(
        &mut self,
        input: &T,
        selections: &GroupSelection<T>,
        partitions: usize,
        context: &T::Context,
    ) -> Result<TensorParallelGroupedOutput<T>, Error>;
}

/// Complete construction specification for packed grouped ReLU-squared groups.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct GroupedRelu2Spec {
    /// Number of groups.
    group_count: i32,
    /// Input and output hidden width.
    hidden_dimensions: i32,
    /// Per-group intermediate width.
    intermediate_dimensions: i32,
    /// Packed up-projection identity and physical format.
    up: GroupedProjectionSpec,
    /// Packed down-projection identity and physical format.
    down: GroupedProjectionSpec,
}

impl GroupedRelu2Spec {
    /// Creates one validated grouped ReLU-squared mechanism request.
    pub fn new(
        group_count: i32,
        hidden_dimensions: i32,
        intermediate_dimensions: i32,
        up: GroupedProjectionSpec,
        down: GroupedProjectionSpec,
    ) -> Result<Self, Error> {
        let spec = Self {
            group_count,
            hidden_dimensions,
            intermediate_dimensions,
            up,
            down,
        };
        spec.validate()?;
        Ok(spec)
    }
    /// Returns a copy with placement-resolved group geometry.
    pub fn with_group_count(mut self, group_count: i32) -> Result<Self, Error> {
        self.group_count = group_count;
        self.validate()?;
        Ok(self)
    }
    /// Returns the number of parameter groups.
    pub const fn group_count(&self) -> i32 {
        self.group_count
    }
    /// Returns the input and output width.
    pub const fn hidden_dimensions(&self) -> i32 {
        self.hidden_dimensions
    }
    /// Returns the per-group intermediate width.
    pub const fn intermediate_dimensions(&self) -> i32 {
        self.intermediate_dimensions
    }
    /// Returns the up projection.
    pub const fn up(&self) -> &GroupedProjectionSpec {
        &self.up
    }
    /// Returns the down projection.
    pub const fn down(&self) -> &GroupedProjectionSpec {
        &self.down
    }
    /// Validates positive geometry.
    pub fn validate(&self) -> Result<(), Error> {
        if self.group_count <= 0 || self.hidden_dimensions <= 0 || self.intermediate_dimensions <= 0
        {
            return Err(Error::backend("invalid ReLU2 group-bank geometry"));
        }
        self.up.validate()?;
        self.down.validate()?;
        let mut identities = std::collections::BTreeSet::new();
        for projection in [&self.up, &self.down] {
            for parameter in projection.parameters() {
                if !identities.insert(&parameter.id) {
                    return Err(Error::backend(format!(
                        "ReLU2 group parameter identity {} is duplicated",
                        parameter.id
                    )));
                }
            }
        }
        Ok(())
    }
}

/// Statically dispatched grouped ReLU-squared bank.
pub trait GroupedRelu2Operator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Returns the exact grouped specification used to construct this bank.
    fn spec(&self) -> &GroupedRelu2Spec;

    /// Executes selected groups and combines their outputs by selection weight.
    fn forward_grouped(
        &mut self,
        input: &T,
        selections: &GroupSelection<T>,
        context: &T::Context,
    ) -> Result<T, Error>;
}

/// Additive mechanism for tensor-parallel grouped ReLU-squared partials.
pub trait TensorParallelGroupedRelu2Operator<T: Tensor>: GroupedRelu2Operator<T> {
    /// Executes a rank-local partial and separates replicated down bias for one
    /// literal post-reduction addition.
    fn forward_grouped_tensor_parallel(
        &mut self,
        input: &T,
        selections: &GroupSelection<T>,
        partitions: usize,
        context: &T::Context,
    ) -> Result<TensorParallelGroupedOutput<T>, Error>;
}

/// Neural backend extension for grouped computation.
pub trait GroupedNeuralBackend: NeuralBackend {
    /// Concrete top-k selector.
    type Selector: GroupSelectionOperator<Self::Tensor>;
    /// Concrete packed or independently materialized gated-product bank.
    type GatedProductGroups: GroupedGatedProductOperator<Self::Tensor>;
    /// Concrete packed or independently materialized ReLU-squared bank.
    type Relu2Groups: GroupedRelu2Operator<Self::Tensor>;

    /// Applies one packed block-diagonal projection independently across an
    /// explicit group axis.
    fn grouped_linear(
        linear: &mut Self::Linear,
        input: &Self::Tensor,
        groups: i32,
        output_per_group: i32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;

    /// Builds a selector with architecture-selected top-k semantics.
    fn top_k_group_selector(
        spec: TopKGroupSelectorSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Selector, Error>;

    /// Builds a grouped gated-product bank.
    fn grouped_gated_product(
        spec: GroupedGatedProductSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::GatedProductGroups, Error>;

    /// Builds a grouped ReLU-squared bank.
    fn grouped_relu2(
        spec: GroupedRelu2Spec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Relu2Groups, Error>;

    /// Selects primary groups and jointly normalizes always-on group coefficients.
    fn joint_group_selection(
        input: JointGroupSelectionInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<JointGroupSelection<Self::Tensor>, Error>;
}

/// Grouped backend whose selected realization provides every required
/// tensor-parallel grouped partial operation.
pub trait TensorParallelGroupedNeuralBackend: GroupedNeuralBackend {
    /// Executes one rank-local gated-product grouped partial.
    fn gated_product_groups_tensor_parallel(
        groups: &mut Self::GatedProductGroups,
        input: &Self::Tensor,
        selections: &GroupSelection<Self::Tensor>,
        partitions: usize,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<TensorParallelGroupedOutput<Self::Tensor>, Error>;

    /// Executes one rank-local ReLU-squared grouped partial.
    fn relu2_groups_tensor_parallel(
        groups: &mut Self::Relu2Groups,
        input: &Self::Tensor,
        selections: &GroupSelection<Self::Tensor>,
        partitions: usize,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<TensorParallelGroupedOutput<Self::Tensor>, Error>;
}

impl<B> TensorParallelGroupedNeuralBackend for B
where
    B: GroupedNeuralBackend,
    B::GatedProductGroups: TensorParallelGroupedGatedProductOperator<B::Tensor>,
    B::Relu2Groups: TensorParallelGroupedRelu2Operator<B::Tensor>,
{
    fn gated_product_groups_tensor_parallel(
        groups: &mut Self::GatedProductGroups,
        input: &Self::Tensor,
        selections: &GroupSelection<Self::Tensor>,
        partitions: usize,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<TensorParallelGroupedOutput<Self::Tensor>, Error> {
        groups.forward_grouped_tensor_parallel(input, selections, partitions, context)
    }

    fn relu2_groups_tensor_parallel(
        groups: &mut Self::Relu2Groups,
        input: &Self::Tensor,
        selections: &GroupSelection<Self::Tensor>,
        partitions: usize,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<TensorParallelGroupedOutput<Self::Tensor>, Error> {
        groups.forward_grouped_tensor_parallel(input, selections, partitions, context)
    }
}

/// Complete construction specification for one multi-stream residual mix.
#[derive(Debug, Clone)]
pub struct HyperConnectionSpec {
    /// Number of parallel residual streams.
    pub streams: i32,
    /// Hidden width of each stream.
    pub hidden_size: i32,
    /// Sinkhorn row/column normalization passes.
    pub sinkhorn_iterations: usize,
    /// Positive numerical epsilon used by Sinkhorn normalization.
    pub epsilon: f32,
    /// Projection producing pre, post, and stream-mixing logits.
    pub function: ParameterSpec,
    /// Additive base for the mixing logits.
    pub base: ParameterSpec,
    /// Learned scales for pre, post, and matrix logits.
    pub scale: ParameterSpec,
}

impl HyperConnectionSpec {
    /// Validates geometry and numerical policy without inspecting parameters.
    pub fn validate(&self) -> Result<(), Error> {
        if self.streams <= 0 || self.hidden_size <= 0 {
            return Err(Error::backend(
                "hyper-connection streams and hidden size must be positive",
            ));
        }
        if self.sinkhorn_iterations == 0 {
            return Err(Error::backend(
                "hyper-connection Sinkhorn iteration count must be positive",
            ));
        }
        if !self.epsilon.is_finite() || self.epsilon <= 0.0 {
            return Err(Error::backend(
                "hyper-connection epsilon must be finite and positive",
            ));
        }
        Ok(())
    }
}

/// Complete construction specification for the final stream collapse.
#[derive(Debug, Clone)]
pub struct HyperHeadSpec {
    /// Number of parallel residual streams.
    pub streams: i32,
    /// Hidden width of each stream.
    pub hidden_size: i32,
    /// RMS preparation epsilon.
    pub norm_epsilon: f32,
    /// Positive offset added to collapse coefficients.
    pub epsilon: f32,
    /// Projection producing per-stream collapse logits.
    pub function: ParameterSpec,
    /// Additive base for collapse logits.
    pub base: ParameterSpec,
    /// Learned collapse-logit scale.
    pub scale: ParameterSpec,
}

impl HyperHeadSpec {
    /// Validates geometry and numerical policy without inspecting parameters.
    pub fn validate(&self) -> Result<(), Error> {
        if self.streams <= 0 || self.hidden_size <= 0 {
            return Err(Error::backend(
                "hyper-head streams and hidden size must be positive",
            ));
        }
        if !self.norm_epsilon.is_finite()
            || self.norm_epsilon <= 0.0
            || !self.epsilon.is_finite()
            || self.epsilon <= 0.0
        {
            return Err(Error::backend(
                "hyper-head epsilons must be finite and positive",
            ));
        }
        Ok(())
    }
}

/// Coefficients and collapsed value produced before one residual sublayer.
#[derive(Debug, Clone)]
pub struct HyperConnectionState<T> {
    /// Residual streams reduced to one sublayer input.
    pub collapsed: T,
    /// Coefficients used for the pre-sublayer reduction.
    pub pre: T,
    /// Coefficients used to inject the sublayer result into each stream.
    pub post: T,
    /// Doubly-stochastic stream-mixing matrix.
    pub combination: T,
}

/// Backend-native operator for one hyper-connected residual cycle.
pub trait HyperConnectionOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Performs FP32 RMS preparation, predicts mixing coefficients, applies
    /// Sinkhorn normalization, and collapses streams for a sublayer.
    fn collapse(
        &mut self,
        residual: &T,
        norm_epsilon: f32,
        context: &T::Context,
    ) -> Result<HyperConnectionState<T>, Error>;

    /// Injects a sublayer result and mixes the previous residual streams.
    fn expand(
        &mut self,
        sublayer: &T,
        residual: &T,
        state: &HyperConnectionState<T>,
        context: &T::Context,
    ) -> Result<T, Error>;
}

/// Backend-native operator for the final learned stream collapse.
pub trait HyperHeadOperator<T: Tensor>: Clone + Debug + Parameterized<T> {
    /// Collapses `[batch, tokens, streams, hidden]` into one hidden state.
    fn forward(&mut self, residual: &T, context: &T::Context) -> Result<T, Error>;
}

/// Neural backend extension for hyper-connected residual architectures.
pub trait HyperNeuralBackend: NeuralBackend {
    /// Concrete multi-stream residual operator.
    type HyperConnection: HyperConnectionOperator<Self::Tensor>;
    /// Concrete final stream-collapse operator.
    type HyperHead: HyperHeadOperator<Self::Tensor>;

    /// Builds one unloaded hyper-connection operator.
    fn hyper_connection(
        spec: HyperConnectionSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::HyperConnection, Error>;

    /// Builds one unloaded final hyper-head operator.
    fn hyper_head(
        spec: HyperHeadSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::HyperHead, Error>;
}

/// Neutral, statically dispatched multi-stream residual layer.
#[derive(Debug, Clone, Parameterized)]
#[parameterized(tensor = "B::Tensor")]
pub struct HyperConnection<B: HyperNeuralBackend> {
    operator: B::HyperConnection,
}

impl<B: HyperNeuralBackend> HyperConnection<B> {
    /// Builds the backend operator from architecture-owned parameter slots.
    pub fn new(
        spec: HyperConnectionSpec,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<Self, Error> {
        spec.validate()?;
        Ok(Self {
            operator: B::hyper_connection(spec, context)?,
        })
    }

    /// Collapses residual streams for one sublayer.
    pub fn collapse(
        &mut self,
        residual: &B::Tensor,
        norm_epsilon: f32,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<HyperConnectionState<B::Tensor>, Error> {
        self.operator.collapse(residual, norm_epsilon, context)
    }

    /// Expands a sublayer result back into residual streams.
    pub fn expand(
        &mut self,
        sublayer: &B::Tensor,
        residual: &B::Tensor,
        state: &HyperConnectionState<B::Tensor>,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<B::Tensor, Error> {
        self.operator.expand(sublayer, residual, state, context)
    }
}

/// Neutral, statically dispatched final stream-collapse layer.
#[derive(Debug, Parameterized)]
#[parameterized(tensor = "B::Tensor")]
pub struct HyperHead<B: HyperNeuralBackend> {
    operator: B::HyperHead,
}

impl<B: HyperNeuralBackend> Clone for HyperHead<B> {
    fn clone(&self) -> Self {
        Self {
            operator: self.operator.clone(),
        }
    }
}

impl<B: HyperNeuralBackend> HyperHead<B> {
    /// Builds the backend operator from architecture-owned parameter slots.
    pub fn new(
        spec: HyperHeadSpec,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<Self, Error> {
        spec.validate()?;
        Ok(Self {
            operator: B::hyper_head(spec, context)?,
        })
    }

    /// Collapses all residual streams to one hidden state.
    pub fn forward(
        &mut self,
        residual: &B::Tensor,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<B::Tensor, Error> {
        self.operator.forward(residual, context)
    }
}

/// One backend-native scaled-dot-product attention request.
///
/// Projected queries, keys, and values remain owned backend tensors so cached,
/// uncached, paged, and sliding implementations can consume the same request
/// without cloning or host materialization. Masks and learned per-query-head
/// sink logits are borrowed architecture state.
#[derive(Debug)]
pub struct AttentionRequest<'a, T> {
    /// Queries shaped `[batch, query_heads, query_tokens, head_dimensions]`.
    pub queries: T,
    /// Keys shaped `[batch, key_value_heads, key_tokens, head_dimensions]`.
    pub keys: T,
    /// Values shaped `[batch, key_value_heads, key_tokens, value_dimensions]`.
    pub values: T,
    /// Positive finite score scale.
    pub scale: f32,
    /// Optional additive or boolean attention mask.
    pub mask: Option<&'a T>,
    /// Optional learned sink logit for every query head.
    pub sinks: Option<&'a T>,
}

impl<T: Tensor> AttentionRequest<'_, T> {
    /// Validates common grouped-query and sink geometry without inspecting values.
    pub fn validate(&self) -> Result<(), Error> {
        let queries = self.queries.shape();
        let keys = self.keys.shape();
        let values = self.values.shape();
        if queries.len() != 4
            || keys.len() != 4
            || values.len() != 4
            || queries[0] != keys[0]
            || keys[..3] != values[..3]
            || queries[3] != keys[3]
            || queries[1] <= 0
            || keys[1] <= 0
            || queries[1] % keys[1] != 0
            || queries[2] <= 0
            || keys[2] <= 0
            || values[3] <= 0
            || !self.scale.is_finite()
            || self.scale <= 0.0
        {
            return Err(Error::backend(format!(
                "invalid attention request geometry queries={queries:?} keys={keys:?} values={values:?} scale={}",
                self.scale
            )));
        }
        if let Some(sinks) = self.sinks {
            if sinks.shape() != [queries[1]] {
                return Err(Error::backend(format!(
                    "attention sinks require shape [{}], got {:?}",
                    queries[1],
                    sinks.shape()
                )));
            }
        }
        Ok(())
    }
}

/// Backend-native key/value cache operations required by attention.
pub trait AttentionCache<T: Tensor> {
    /// Current absolute sequence offset.
    fn offset(&self) -> i32;
    /// Maximum retained history for a sliding cache.
    fn max_size(&self) -> Option<i32>;
    /// Appends projected keys and values and returns the tensors used by attention.
    fn update_for_attention(
        &mut self,
        keys: T,
        values: T,
        context: &T::Context,
    ) -> Result<(T, T), Error>;
    /// Runs cache-aware attention, including paged or quantized kernels where applicable.
    fn attention(
        &mut self,
        request: AttentionRequest<'_, T>,
        context: &T::Context,
    ) -> Result<T, Error>;
}

/// Attention cache with a fixed set of bounded causal-convolution histories.
///
/// Slot identity is architecture policy; storage, persistence, and device
/// realization remain runtime/backend concerns.
pub trait AuxiliaryConvolutionState<T: Tensor>: AttentionCache<T> {
    /// Borrows one bounded convolution-history slot.
    fn convolution_state(&mut self, slot: u32) -> Result<&mut Option<T>, Error>;
}

/// Semantic latent and rotary components retained by compressed attention.
#[derive(Debug, Clone)]
pub struct CompressedAttentionState<T> {
    /// Head-independent latent key/value representation.
    pub latent: T,
    /// Rotary-key representation aligned to the same token range.
    pub rotary: T,
}

/// Result of appending compressed state.
#[derive(Debug, Clone)]
pub enum CompressedAttentionView<T> {
    /// Complete resident state used directly by prefill or decode attention.
    Resident(CompressedAttentionState<T>),
    /// Paged state; the appended components are retained for diagnostics while
    /// attention scans semantic blocks through the cache operator.
    Paged {
        /// Components appended by this update.
        appended: CompressedAttentionState<T>,
    },
}

impl<T> CompressedAttentionView<T> {
    /// Returns the resident state when paging is not active.
    pub const fn resident(&self) -> Option<&CompressedAttentionState<T>> {
        match self {
            Self::Resident(state) => Some(state),
            Self::Paged { .. } => None,
        }
    }

    /// Returns components suitable for non-materializing observation.
    pub const fn observable(&self) -> &CompressedAttentionState<T> {
        match self {
            Self::Resident(state) | Self::Paged { appended: state } => state,
        }
    }

    /// Returns whether block-addressable paging is active.
    pub const fn is_paged(&self) -> bool {
        matches!(self, Self::Paged { .. })
    }
}

/// One absolute token range supplied to blockwise compressed attention.
#[derive(Debug, Clone)]
pub struct CompressedAttentionBlock<T> {
    /// Inclusive absolute token start.
    pub start: i64,
    /// Exclusive absolute token end.
    pub end: i64,
    /// Latent and rotary components for this range.
    pub state: CompressedAttentionState<T>,
}

/// Aggregate observations from one paged blockwise attention scan.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub struct CompressedAttentionScan {
    /// Number of scanned sealed and tail blocks.
    pub blocks: u64,
    /// Number of persistent compressed bytes scanned.
    pub bytes: u64,
    /// Maximum caller-reported transient reconstruction bytes.
    pub reconstruction_scratch_bytes: u64,
}

/// Fixed request metadata for an online blockwise attention recurrence.
#[derive(Debug, Clone, Copy)]
pub struct BlockwiseAttentionSpec<'a, T> {
    /// Queries shaped `[batch, heads, query_tokens, dimensions]`.
    pub queries: &'a T,
    /// Query/key score multiplier.
    pub scale: f32,
    /// Optional complete-context mask sliced by the backend for each block.
    pub mask: Option<&'a T>,
    /// Absolute position of the first query.
    pub query_start: i64,
    /// Absolute exclusive end of the complete visible context.
    pub context_end: i64,
    /// Optional causal sliding-window width.
    pub sliding_window: Option<i32>,
    /// Number of prefix tokens visible outside a sliding window.
    pub prefix_tokens: i64,
    /// Optional learned per-head sink logits.
    pub sinks: Option<&'a T>,
}

/// Typed backend fusion for exact online softmax across ordered attention
/// blocks. Persistent caches remain compressed; only one reconstructed block
/// is live at a time.
pub trait BlockwiseAttentionBackend: NeuralBackend {
    /// Backend-native running maximum, normalization, and value accumulator.
    type BlockwiseAccumulator;

    /// Starts an empty online attention recurrence.
    fn begin_blockwise_attention(
        spec: BlockwiseAttentionSpec<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::BlockwiseAccumulator, Error>;

    /// Incorporates one absolute key/value block and reports transient bytes.
    fn accumulate_blockwise_attention(
        accumulator: &mut Self::BlockwiseAccumulator,
        start: i64,
        end: i64,
        keys: Self::Tensor,
        values: Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<u64, Error>;

    /// Finishes the online recurrence.
    fn finish_blockwise_attention(
        accumulator: Self::BlockwiseAccumulator,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
}

/// Backend-owned compressed-attention state over semantic components.
///
/// Checkpoints are cheap backend snapshots used by speculative fork/rollback.
/// `finalize` seals mutable state before runtime prompt-cache persistence.
pub trait CompressedAttentionCache<T: Tensor>: Debug {
    /// Backend snapshot preserving paging and residency identity.
    type Checkpoint: Clone + Debug;

    /// Current absolute token frontier.
    fn offset(&self) -> i32;
    /// Whether state is block-addressable rather than fully resident.
    fn is_paged(&self) -> bool;
    /// Appends aligned latent and rotary components.
    fn append(
        &mut self,
        state: CompressedAttentionState<T>,
        context: &T::Context,
    ) -> Result<CompressedAttentionView<T>, Error>;
    /// Visits all paged blocks in absolute order without host tensor
    /// materialization. The callback reports its transient scratch usage.
    fn visit_blocks<F>(
        &mut self,
        query_tokens: i32,
        context: &T::Context,
        visitor: F,
    ) -> Result<CompressedAttentionScan, Error>
    where
        F: FnMut(CompressedAttentionBlock<T>) -> Result<u64, Error>;
    /// Captures a cheap speculative checkpoint.
    fn checkpoint(&self) -> Self::Checkpoint;
    /// Restores a previous checkpoint, removing any later paged state.
    fn restore(&mut self, checkpoint: &Self::Checkpoint, context: &T::Context)
        -> Result<(), Error>;
    /// Seals mutable tails before prompt-cache snapshot persistence.
    fn finalize(&mut self) -> Result<(), Error>;
    /// Clears all resident or paged state.
    fn clear(&mut self) -> Result<(), Error>;
}

/// Complete source windows emitted by an append-only gated-pooling stream.
#[derive(Debug, Clone)]
pub struct PoolingWindows<T> {
    /// Source values shaped `[batch, complete_source_tokens, width]`.
    pub values: T,
    /// Gate logits aligned to `values`.
    pub gates: T,
    /// Absolute source-token position of the first returned value.
    pub base_position: i32,
}

/// Previous overlap carried between adjacent gated-pooling windows.
#[derive(Debug, Clone)]
pub struct PoolingOverlap<T> {
    /// Previous-window source values, when a complete predecessor exists.
    pub values: Option<T>,
    /// Previous-window gate logits aligned to `values`.
    pub gates: Option<T>,
}

/// Backend-owned local-key and compressed-pooling state used by architectures
/// that mix bounded local attention with append-only pooled history.
///
/// Stream ordinals are architecture-owned. Implementations preserve pending,
/// pooled, and overlap components through checkpoint, rollback, prompt-cache,
/// resident, and paged realizations without exposing storage classes here.
pub trait PoolingAttentionCache<T: Tensor>: Debug {
    /// Backend snapshot preserving all local and pooling state.
    type Checkpoint: Clone + Debug;

    /// Current absolute source-token frontier.
    fn offset(&self) -> i32;
    /// Returns the configured source-token ratio for one pooling stream.
    fn pooling_ratio(&self, stream: u32) -> Option<i32>;
    /// Appends local keys and returns the bounded history used by attention,
    /// shaped `[batch, local_tokens, dimensions]`.
    fn append_local(&mut self, keys: T, context: &T::Context) -> Result<T, Error>;
    /// Builds causal eligibility for the currently retained local history.
    fn local_mask(&self, query_tokens: i32, offset: i32, context: &T::Context) -> Result<T, Error>;
    /// Accumulates source values and gates, retaining any incomplete suffix.
    fn accumulate_pooling_windows(
        &mut self,
        stream: u32,
        values: T,
        gates: T,
        absolute_offset: i32,
        context: &T::Context,
    ) -> Result<PoolingWindows<T>, Error>;
    /// Replaces overlap carried by one stream and returns its previous pair.
    fn replace_pooling_overlap(
        &mut self,
        stream: u32,
        values: T,
        gates: T,
    ) -> Result<PoolingOverlap<T>, Error>;
    /// Appends newly pooled values and returns the complete pooled history.
    fn append_pooled(&mut self, stream: u32, values: T, context: &T::Context) -> Result<T, Error>;
    /// Builds causal eligibility for one stream's complete pooled history.
    fn pooling_mask(
        &self,
        stream: u32,
        query_tokens: i32,
        offset: i32,
        context: &T::Context,
    ) -> Result<Option<T>, Error>;
    /// Captures a cheap speculative checkpoint.
    fn checkpoint(&self) -> Self::Checkpoint;
    /// Restores a previous checkpoint.
    fn restore(&mut self, checkpoint: &Self::Checkpoint, context: &T::Context)
        -> Result<(), Error>;
    /// Seals mutable local and pooled tails before persistence.
    fn finalize(&mut self) -> Result<(), Error>;
    /// Clears all local and pooling state.
    fn clear(&mut self) -> Result<(), Error>;
}

/// Explicit optional operations a backend promises to execute.
///
/// These capabilities cover explicitly admitted methods on [`NeuralBackend`]
/// and every optional [`Tensor`] method whose default implementation fails
/// closed. Architectures validate their required set while constructing
/// modules, before parameters are loaded or a forward pass can begin.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub struct NeuralOperatorCapabilities(u64);

impl NeuralOperatorCapabilities {
    /// No optional forward operators.
    pub const NONE: Self = Self(0);
    /// Tanh-approximated GELU.
    pub const GELU_APPROXIMATE: Self = Self(1 << 0);
    /// Logistic sigmoid.
    pub const SIGMOID: Self = Self(1 << 1);
    /// Softplus.
    pub const SOFTPLUS: Self = Self(1 << 2);
    /// Natural exponential.
    pub const EXP: Self = Self(1 << 3);
    /// Gated grouped RMS normalization.
    pub const GATED_GROUP_RMS_NORM: Self = Self(1 << 4);
    /// L2 normalization.
    pub const L2_NORMALIZE: Self = Self(1 << 5);
    /// SiLU-gated grouped RMS normalization.
    pub const SILU_GATED_GROUP_RMS_NORM: Self = Self(1 << 6);
    /// Segmented attention.
    pub const SEGMENTED_ATTENTION: Self = Self(1 << 7);
    /// Gated-delta recurrent scan.
    pub const GATED_DELTA_SCAN: Self = Self(1 << 8);
    /// Selective state-space scan.
    pub const SELECTIVE_STATE_SPACE_SCAN: Self = Self(1 << 9);
    /// Indexed sparse attention.
    pub const INDEXED_ATTENTION: Self = Self(1 << 10);
    /// Dense pooled attention.
    pub const POOLED_ATTENTION: Self = Self(1 << 11);
    /// Pooled-position selection.
    pub const POOLED_POSITION_SELECTION: Self = Self(1 << 12);
    /// Pooled-mask gathering.
    pub const POOLED_MASK_GATHER: Self = Self(1 << 13);
    /// Attention with learned sink logits.
    pub const ATTENTION_SINKS: Self = Self(1 << 14);
    /// Learned relative-profile attention.
    pub const RELATIVE_ATTENTION: Self = Self(1 << 15);
    /// Joint grouped/shared group selection.
    pub const JOINT_GROUP_SELECTION: Self = Self(1 << 16);
    /// Weightless RMS normalization.
    pub const RMS_NORM_WITHOUT_WEIGHT: Self = Self(1 << 17);
    /// Grouped block-diagonal linear projection.
    pub const GROUPED_LINEAR: Self = Self(1 << 18);
    /// Tensor-parallel sum reduction.
    pub const SUM_PARALLEL: Self = Self(1 << 19);
    /// Unloaded signed 32-bit integer parameter allocation.
    pub const UNLOADED_I32: Self = Self(1 << 20);
    /// Signed 32-bit integer tensor construction from host data.
    pub const FROM_I32_SLICE: Self = Self(1 << 21);
    /// Floating-point host materialization.
    pub const TO_F32_VEC: Self = Self(1 << 22);
    /// Signed 32-bit integer host materialization.
    pub const TO_I32_VEC: Self = Self(1 << 23);
    /// Floating-point filled tensor construction.
    pub const FULL_F32: Self = Self(1 << 24);
    /// Signed 32-bit integer filled tensor construction.
    pub const FULL_I32: Self = Self(1 << 25);
    /// Elementwise hyperbolic tangent.
    pub const TANH: Self = Self(1 << 26);
    /// Elementwise clamp with tensor bounds.
    pub const CLIP: Self = Self(1 << 27);
    /// Axis-wise softmax.
    pub const SOFTMAX_AXIS: Self = Self(1 << 28);
    /// Tensor broadcasting.
    pub const BROADCAST_TO: Self = Self(1 << 29);
    /// Dtype-preserving zero allocation.
    pub const ZEROS_LIKE: Self = Self(1 << 30);
    /// Signed integer scalar comparison.
    pub const EQUAL_I32: Self = Self(1 << 31);
    /// Elementwise logical disjunction.
    pub const LOGICAL_OR: Self = Self(1 << 32);
    /// Conditional tensor selection.
    pub const WHERE_CONDITION: Self = Self(1 << 33);
    /// Masked tensor scatter.
    pub const MASKED_SCATTER: Self = Self(1 << 34);
    /// Rotary positions with caller-supplied frequencies.
    pub const ROPE_WITH_FREQUENCIES: Self = Self(1 << 35);
    /// Two-dimensional convolution.
    pub const CONV2D: Self = Self(1 << 36);
    /// Multi-axis rotary embedding construction.
    pub const MULTI_AXIS_ROTARY_EMBEDDINGS: Self = Self(1 << 37);
    /// Masked vocabulary output projection.
    pub const MASKED_OUTPUT_PROJECTION: Self = Self(1 << 38);
    /// Every currently declared optional operation.
    pub const ALL: Self = Self((1 << 39) - 1);

    /// Returns the union of two capability sets.
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Returns whether this set contains every required capability.
    pub const fn contains(self, required: Self) -> bool {
        self.0 & required.0 == required.0
    }

    /// Returns stable names for every required capability absent from this set.
    pub fn missing_capability_names(self, required: Self) -> Vec<&'static str> {
        const NAMES: &[(NeuralOperatorCapabilities, &str)] = &[
            (
                NeuralOperatorCapabilities::GELU_APPROXIMATE,
                "gelu_approximate",
            ),
            (NeuralOperatorCapabilities::SIGMOID, "sigmoid"),
            (NeuralOperatorCapabilities::SOFTPLUS, "softplus"),
            (NeuralOperatorCapabilities::EXP, "exp"),
            (
                NeuralOperatorCapabilities::GATED_GROUP_RMS_NORM,
                "gated_group_rms_norm",
            ),
            (NeuralOperatorCapabilities::L2_NORMALIZE, "l2_normalize"),
            (
                NeuralOperatorCapabilities::SILU_GATED_GROUP_RMS_NORM,
                "silu_gated_group_rms_norm",
            ),
            (
                NeuralOperatorCapabilities::SEGMENTED_ATTENTION,
                "segmented_attention",
            ),
            (
                NeuralOperatorCapabilities::GATED_DELTA_SCAN,
                "gated_delta_scan",
            ),
            (
                NeuralOperatorCapabilities::SELECTIVE_STATE_SPACE_SCAN,
                "selective_state_space_scan",
            ),
            (
                NeuralOperatorCapabilities::INDEXED_ATTENTION,
                "indexed_attention",
            ),
            (
                NeuralOperatorCapabilities::POOLED_ATTENTION,
                "pooled_attention",
            ),
            (
                NeuralOperatorCapabilities::POOLED_POSITION_SELECTION,
                "select_pooled_positions",
            ),
            (
                NeuralOperatorCapabilities::POOLED_MASK_GATHER,
                "gather_pooled_mask",
            ),
            (
                NeuralOperatorCapabilities::ATTENTION_SINKS,
                "attention_sinks",
            ),
            (
                NeuralOperatorCapabilities::RELATIVE_ATTENTION,
                "relative_attention",
            ),
            (
                NeuralOperatorCapabilities::JOINT_GROUP_SELECTION,
                "joint_group_selection",
            ),
            (
                NeuralOperatorCapabilities::RMS_NORM_WITHOUT_WEIGHT,
                "rms_norm_without_weight",
            ),
            (NeuralOperatorCapabilities::GROUPED_LINEAR, "grouped_linear"),
            (NeuralOperatorCapabilities::SUM_PARALLEL, "sum_parallel"),
            (NeuralOperatorCapabilities::UNLOADED_I32, "unloaded_i32"),
            (NeuralOperatorCapabilities::FROM_I32_SLICE, "from_i32_slice"),
            (NeuralOperatorCapabilities::TO_F32_VEC, "to_f32_vec"),
            (NeuralOperatorCapabilities::TO_I32_VEC, "to_i32_vec"),
            (NeuralOperatorCapabilities::FULL_F32, "full_f32"),
            (NeuralOperatorCapabilities::FULL_I32, "full_i32"),
            (NeuralOperatorCapabilities::TANH, "tanh"),
            (NeuralOperatorCapabilities::CLIP, "clip"),
            (NeuralOperatorCapabilities::SOFTMAX_AXIS, "softmax_axis"),
            (NeuralOperatorCapabilities::BROADCAST_TO, "broadcast_to"),
            (NeuralOperatorCapabilities::ZEROS_LIKE, "zeros_like"),
            (NeuralOperatorCapabilities::EQUAL_I32, "equal_i32"),
            (NeuralOperatorCapabilities::LOGICAL_OR, "logical_or"),
            (
                NeuralOperatorCapabilities::WHERE_CONDITION,
                "where_condition",
            ),
            (NeuralOperatorCapabilities::MASKED_SCATTER, "masked_scatter"),
            (
                NeuralOperatorCapabilities::ROPE_WITH_FREQUENCIES,
                "rope_with_frequencies",
            ),
            (NeuralOperatorCapabilities::CONV2D, "conv2d"),
            (
                NeuralOperatorCapabilities::MULTI_AXIS_ROTARY_EMBEDDINGS,
                "multi_axis_rotary_embeddings",
            ),
            (
                NeuralOperatorCapabilities::MASKED_OUTPUT_PROJECTION,
                "masked_output_projection",
            ),
        ];
        NAMES
            .iter()
            .filter_map(|(capability, name)| {
                (required.contains(*capability) && !self.contains(*capability)).then_some(*name)
            })
            .collect()
    }
}

#[cfg(test)]
mod neural_operator_capability_tests {
    use super::NeuralOperatorCapabilities as C;

    #[test]
    fn all_includes_every_fail_closed_tensor_operation() {
        for (capability, name) in [
            (C::UNLOADED_I32, "unloaded_i32"),
            (C::FROM_I32_SLICE, "from_i32_slice"),
            (C::TO_F32_VEC, "to_f32_vec"),
            (C::TO_I32_VEC, "to_i32_vec"),
            (C::FULL_F32, "full_f32"),
            (C::FULL_I32, "full_i32"),
            (C::TANH, "tanh"),
            (C::CLIP, "clip"),
            (C::SOFTMAX_AXIS, "softmax_axis"),
            (C::BROADCAST_TO, "broadcast_to"),
            (C::ZEROS_LIKE, "zeros_like"),
            (C::EQUAL_I32, "equal_i32"),
            (C::LOGICAL_OR, "logical_or"),
            (C::WHERE_CONDITION, "where_condition"),
            (C::MASKED_SCATTER, "masked_scatter"),
            (C::ROPE_WITH_FREQUENCIES, "rope_with_frequencies"),
            (C::CONV2D, "conv2d"),
            (
                C::MULTI_AXIS_ROTARY_EMBEDDINGS,
                "multi_axis_rotary_embeddings",
            ),
            (C::MASKED_OUTPUT_PROJECTION, "masked_output_projection"),
        ] {
            assert!(C::ALL.contains(capability));
            assert_eq!(C::NONE.missing_capability_names(capability), [name]);
        }
    }
}

/// General neural-operator family selected by a shared architecture.
///
/// Associated concrete types make calls statically dispatched. Implementations
/// retain ownership of tensor storage, fusion, quantization, and collectives.
pub trait NeuralBackend: Sized + 'static {
    /// Optional forward operators explicitly supported by this backend.
    const OPERATOR_CAPABILITIES: NeuralOperatorCapabilities = NeuralOperatorCapabilities::NONE;

    /// Backend tensor handle.
    type Tensor: Tensor;
    /// Native affine projection, including packed quantized variants.
    type Linear: LinearOperator<Self::Tensor>;
    /// Native embedding table.
    type Embedding: EmbeddingOperator<Self::Tensor>;
    /// Native normalization operator.
    type Normalization: NormalizationOperator<Self::Tensor>;
    /// Native rotary-position operator.
    type Rotary: RotaryOperator<Self::Tensor>;
    /// Backend collective context used by tensor-parallel execution.
    type ParallelContext: ?Sized;

    /// Rejects an architecture before module construction when an optional
    /// forward operator is unavailable.
    fn require_operator_capabilities(
        architecture: &'static str,
        required: NeuralOperatorCapabilities,
    ) -> Result<(), Error> {
        let available = Self::OPERATOR_CAPABILITIES;
        if available.contains(required) {
            return Ok(());
        }
        Err(Error::backend(format!(
            "{architecture} requires unsupported backend operators: {}",
            available.missing_capability_names(required).join(", ")
        )))
    }

    /// Builds one affine projection.
    fn linear(
        spec: LinearSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Linear, Error>;
    /// Builds one token embedding table.
    fn embedding(
        spec: EmbeddingSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Embedding, Error>;
    /// Builds an RMS normalization with an explicit scale policy.
    fn normalization(
        spec: NormalizationConstructionSpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Normalization, Error>;
    /// Builds the model's rotary-position operator.
    fn rotary(
        spec: RotarySpec,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Rotary, Error>;
    /// Applies SiLU using a backend-native implementation.
    fn silu(
        input: Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Applies the tanh-approximated GELU used by some encoder MLPs.
    fn gelu_approximate(
        input: Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "approximate GELU is not implemented by this backend",
        ))
    }
    /// Applies the logistic sigmoid elementwise.
    fn sigmoid(
        input: Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend("sigmoid is not implemented by this backend"))
    }
    /// Applies softplus elementwise.
    fn softplus(
        input: Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "softplus is not implemented by this backend",
        ))
    }
    /// Applies the natural exponential elementwise.
    fn exp(
        input: Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "exponential is not implemented by this backend",
        ))
    }
    /// Applies SiLU gating followed by grouped RMS normalization and scale.
    /// Input and gate shapes must match; positive groups must divide the final
    /// feature axis, and epsilon must be finite and strictly positive.
    fn gated_group_rms_norm(
        input: &Self::Tensor,
        gate: &Self::Tensor,
        weight: &Self::Tensor,
        groups: i32,
        epsilon: f32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, gate, weight, groups, epsilon, context);
        Err(Error::backend(
            "gated grouped RMS normalization is not implemented by this backend",
        ))
    }
    /// Applies `input / sqrt(sum(input * input) + epsilon)` over the final axis.
    /// Epsilon must be finite and strictly positive; it is additive, not a clamp.
    fn l2_normalize(
        input: &Self::Tensor,
        epsilon: f32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, epsilon, context);
        Err(Error::backend(
            "L2 normalization is not implemented by this backend",
        ))
    }
    /// Applies grouped RMS normalization to `input`, multiplies by a learned
    /// scale, and then modulates the result by `silu(gate)`.
    /// Input and gate shapes must match; positive groups must divide the final
    /// feature axis, and epsilon must be finite and strictly positive.
    fn silu_gated_group_rms_norm(
        input: &Self::Tensor,
        gate: &Self::Tensor,
        weight: &Self::Tensor,
        groups: i32,
        epsilon: f32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, gate, weight, groups, epsilon, context);
        Err(Error::backend(
            "SiLU-gated grouped RMS normalization is not implemented by this backend",
        ))
    }
    /// Repeats a validated head axis using backend-native reshape and
    /// broadcast operations.
    fn expand_heads(
        input: &Self::Tensor,
        expansion: HeadExpansion,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        expansion.validate(input)?;
        if expansion.source_heads == expansion.target_heads {
            return Ok(input.clone());
        }
        let mut expanded_shape = input.shape().to_vec();
        expanded_shape.insert(expansion.axis + 1, 1);
        let expanded = input.reshape(&expanded_shape, context)?;
        expanded_shape[expansion.axis + 1] = expansion.repeats();
        let expanded = expanded.broadcast_to(&expanded_shape, context)?;
        expanded_shape[expansion.axis] = expansion.target_heads;
        expanded_shape.remove(expansion.axis + 1);
        expanded.reshape(&expanded_shape, context)
    }
    /// Runs unmasked attention independently over contiguous validated
    /// segments without exposing backend slicing to architecture code.
    fn segmented_attention(
        input: SegmentedAttentionInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        input.validate()?;
        let _ = context;
        Err(Error::backend(
            "segmented attention is not implemented by this backend",
        ))
    }
    /// Adds a residual branch, optionally retaining the accumulator in FP32.
    fn add_residual(
        residual: &Self::Tensor,
        branch: &Self::Tensor,
        fp32: bool,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = fp32;
        residual.add(branch, context)
    }
    /// Executes a gated-delta recurrent scan over projected head-major values.
    ///
    /// Inputs are `[batch, sequence, heads, dimensions]` except `beta`, which
    /// is `[batch, sequence, heads]`. The optional initial and returned state
    /// are `[batch, heads, dimensions, dimensions]` in FP32 semantic storage.
    fn gated_delta_scan(
        input: GatedDeltaScanInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<GatedDeltaScanOutput<Self::Tensor>, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "gated-delta scan is not implemented by this backend",
        ))
    }
    /// Executes a grouped selective state-space recurrence in FP32 state.
    fn selective_state_space_scan(
        input: SelectiveStateSpaceScanInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<SelectiveStateSpaceScanOutput<Self::Tensor>, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "selective state-space scan is not implemented by this backend",
        ))
    }
    /// Runs sparse attention over bounded local state and caller-selected
    /// compressed positions, optionally sharing softmax normalization with
    /// learned attention sinks.
    fn indexed_attention(
        input: IndexedAttentionInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "indexed attention is not implemented by this backend",
        ))
    }
    /// Runs dense shared-softmax attention over local and pooled history.
    fn pooled_attention(
        input: PooledAttentionInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "pooled attention is not implemented by this backend",
        ))
    }
    /// Selects pooled positions for indexed attention.
    fn select_pooled_positions(
        input: PooledPositionInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "pooled-position selection is not implemented by this backend",
        ))
    }
    /// Gathers one full pooled-eligibility mask at selected positions.
    fn gather_pooled_mask(
        mask: &Self::Tensor,
        selected_positions: &Self::Tensor,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (mask, selected_positions, context);
        Err(Error::backend(
            "pooled-mask gathering is not implemented by this backend",
        ))
    }
    /// Runs dense attention with optional learned per-head sink logits.
    fn attention_with_sinks(
        request: AttentionRequest<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        request.validate()?;
        if request.sinks.is_some() {
            return Err(Error::backend(
                "attention sinks are not implemented by this backend",
            ));
        }
        Self::attention(
            request.queries,
            request.keys,
            request.values,
            request.scale,
            request.mask,
            context,
        )
    }
    /// Runs causal sliding-window prefill attention with optional learned sinks.
    fn sliding_window_attention_with_sinks(
        request: AttentionRequest<'_, Self::Tensor>,
        window: i32,
        position_offset: i32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        request.validate()?;
        if request.sinks.is_some() {
            return Err(Error::backend(
                "sliding-window attention sinks are not implemented by this backend",
            ));
        }
        Self::sliding_window_attention(
            request.queries,
            request.keys,
            request.values,
            request.scale,
            window,
            position_offset,
            context,
        )
    }
    /// Runs causal attention with caller-projected learned relative profiles.
    fn relative_attention(
        input: RelativeAttentionInput<'_, Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "relative-profile attention is not implemented by this backend",
        ))
    }
    /// Applies RMS normalization without a learned scale.
    /// The final feature axis must be nonempty, with finite, positive epsilon.
    fn rms_norm_without_weight(
        input: &Self::Tensor,
        epsilon: f32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        let _ = (input, epsilon, context);
        Err(Error::backend(
            "weightless RMS normalization is not implemented by this backend",
        ))
    }
    /// Applies RMS normalization with a caller-owned learned scale.
    /// The final feature axis must be nonempty, with finite, positive epsilon.
    ///
    /// The default keeps the operation portable by composing weightless
    /// normalization and multiplication. Backends may override it with a
    /// fused kernel when their tensor runtime provides one.
    fn rms_norm_with_weight(
        input: &Self::Tensor,
        weight: &Self::Tensor,
        epsilon: f32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error> {
        Self::rms_norm_without_weight(input, epsilon, context)?.multiply(weight, context)
    }
    /// Applies a validated gated-product equation.
    fn gated_product(
        gate: Self::Tensor,
        up: Self::Tensor,
        policy: GatedProductPolicy,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Runs un-cached scaled dot-product attention.
    fn attention(
        queries: Self::Tensor,
        keys: Self::Tensor,
        values: Self::Tensor,
        scale: f32,
        mask: Option<&Self::Tensor>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Runs causal sliding-window prefill attention without a square mask.
    #[allow(clippy::too_many_arguments)]
    fn sliding_window_attention(
        queries: Self::Tensor,
        keys: Self::Tensor,
        values: Self::Tensor,
        scale: f32,
        window: i32,
        position_offset: i32,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Builds the backend-native boolean causal mask used for a prefill.
    /// `window` is the inclusive maximum backward distance, not a token count:
    /// zero admits only the current position and one also admits its predecessor.
    ///
    /// The returned value remains a lazy/backend-owned tensor. Calling this
    /// method must not synchronize or materialize mask contents on the host.
    fn causal_mask(
        sequence: i32,
        offset: i32,
        window: Option<i32>,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Applies a row-parallel projection and its collective reduction.
    fn row_parallel_linear(
        linear: &mut Self::Linear,
        input: &Self::Tensor,
        parallel: &Self::ParallelContext,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Number of participants in a tensor-parallel collective context.
    fn parallel_size(_parallel: &Self::ParallelContext) -> usize {
        1
    }
}

/// Additive mechanisms required only by distributed vocabulary and reduction paths.
///
/// Ordinary replicated backends implement [`NeuralBackend`] without this trait.
/// Every operation here is required, so an admitted distributed architecture cannot
/// encounter an inherited forward-time “unsupported” implementation.
pub trait DistributedNeuralBackend: NeuralBackend {
    /// Builds one rank-local vocabulary embedding under validated ownership.
    fn vocabulary_parallel_embedding(
        spec: EmbeddingSpec,
        range: VocabularyParallelRange,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Embedding, Error>;
    /// Builds one rank-local vocabulary output projection.
    fn vocabulary_parallel_linear(
        spec: LinearSpec,
        range: VocabularyParallelRange,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Linear, Error>;
    /// Looks up global token IDs and sums this rank's local contribution.
    fn vocabulary_parallel_lookup(
        embedding: &mut Self::Embedding,
        input: &Self::Tensor,
        policy: EmbeddingLookupPolicy,
        parallel: &Self::ParallelContext,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Projects to local vocabulary rows and gathers complete logits.
    fn vocabulary_parallel_project(
        linear: &mut Self::Linear,
        input: &Self::Tensor,
        parallel: &Self::ParallelContext,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Projects through a rank-local vocabulary embedding and gathers complete logits.
    fn vocabulary_parallel_embedding_project(
        embedding: &mut Self::Embedding,
        input: &Self::Tensor,
        parallel: &Self::ParallelContext,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
    /// Sums a rank-local tensor contribution across the tensor-parallel group.
    fn sum_parallel(
        value: Self::Tensor,
        parallel: &Self::ParallelContext,
        context: &<Self::Tensor as Tensor>::Context,
    ) -> Result<Self::Tensor, Error>;
}

/// Projected inputs to one gated-delta recurrent scan.
#[derive(Debug, Clone, Copy)]
pub struct GatedDeltaScanInput<'a, T> {
    /// Normalized queries `[batch, sequence, heads, dimensions]`.
    pub query: &'a T,
    /// Normalized keys `[batch, sequence, heads, dimensions]`.
    pub key: &'a T,
    /// Values `[batch, sequence, heads, dimensions]`.
    pub value: &'a T,
    /// Log transition decay, scalar- or vector-valued per head.
    pub log_decay: &'a T,
    /// Update strength `[batch, sequence, heads]`.
    pub beta: &'a T,
    /// Optional FP32 recurrent matrix.
    pub initial_state: Option<&'a T>,
}

/// Final state and per-token output of a gated-delta scan.
#[derive(Debug, Clone)]
pub struct GatedDeltaScanOutput<T> {
    /// FP32 recurrent state after the final token.
    pub state: T,
    /// Recurrent output `[batch, sequence, heads, dimensions]`.
    pub output: T,
}

/// Projected inputs to one Mamba-style selective state-space scan.
#[derive(Debug, Clone, Copy)]
pub struct SelectiveStateSpaceScanInput<'a, T> {
    /// Values `[batch, sequence, heads, head_dimensions]`.
    pub values: &'a T,
    /// Expanded input state vectors `[batch, sequence, heads, state_dimensions]`.
    pub input_state: &'a T,
    /// Expanded output state vectors `[batch, sequence, heads, state_dimensions]`.
    pub output_state: &'a T,
    /// Unnormalized timesteps `[batch, sequence, heads]`.
    pub time_step: &'a T,
    /// Per-head timestep bias `[heads]`.
    pub time_step_bias: &'a T,
    /// Per-head logarithmic transition magnitude `[heads]`.
    pub transition_log: &'a T,
    /// Per-head direct skip coefficient `[heads]`.
    pub skip: &'a T,
    /// Optional FP32 state `[batch, heads, head_dimensions, state_dimensions]`.
    pub initial_state: Option<&'a T>,
    /// Lower bound applied after softplus timestep discretization.
    pub time_step_floor: f32,
    /// Maximum number of prefill tokens processed per backend chunk.
    pub chunk_size: usize,
}

/// Final state and per-token output of a selective state-space scan.
#[derive(Debug, Clone)]
pub struct SelectiveStateSpaceScanOutput<T> {
    /// FP32 recurrent state after the final token.
    pub state: T,
    /// Scan output `[batch, sequence, heads, head_dimensions]`.
    pub output: T,
}

/// Deterministic host reference for the selective state-space recurrence.
#[allow(clippy::too_many_arguments)]
pub fn reference_selective_state_space_scan(
    batch: usize,
    sequence: usize,
    heads: usize,
    head_dimensions: usize,
    state_dimensions: usize,
    values: &[f32],
    input_state: &[f32],
    output_state: &[f32],
    time_step: &[f32],
    time_step_bias: &[f32],
    transition_log: &[f32],
    skip: &[f32],
    time_step_floor: f32,
    initial_state: Option<&[f32]>,
) -> Result<(Vec<f32>, Vec<f32>), Error> {
    let groups = batch * sequence * heads;
    let values_len = groups * head_dimensions;
    let vectors_len = groups * state_dimensions;
    let state_len = batch * heads * head_dimensions * state_dimensions;
    if values.len() != values_len
        || input_state.len() != vectors_len
        || output_state.len() != vectors_len
        || time_step.len() != groups
        || time_step_bias.len() != heads
        || transition_log.len() != heads
        || skip.len() != heads
        || initial_state.is_some_and(|state| state.len() != state_len)
        || !time_step_floor.is_finite()
        || time_step_floor < 0.0
    {
        return Err(Error::backend(
            "invalid selective state-space reference geometry",
        ));
    }
    let mut state = initial_state.map_or_else(|| vec![0.0; state_len], <[f32]>::to_vec);
    let mut output = vec![0.0; values_len];
    for batch_index in 0..batch {
        for token in 0..sequence {
            for head in 0..heads {
                let group = (batch_index * sequence + token) * heads + head;
                let dt =
                    ((time_step[group] + time_step_bias[head]).exp().ln_1p()).max(time_step_floor);
                let transition = (-transition_log[head].exp() * dt).exp();
                let vector_base = group * state_dimensions;
                for dimension in 0..head_dimensions {
                    let value_index = group * head_dimensions + dimension;
                    let state_base =
                        (batch_index * heads + head) * head_dimensions * state_dimensions
                            + dimension * state_dimensions;
                    let value = values[value_index];
                    let mut projected = 0.0f32;
                    for state_dimension in 0..state_dimensions {
                        let state_index = state_base + state_dimension;
                        state[state_index] = state[state_index] * transition
                            + dt * input_state[vector_base + state_dimension] * value;
                        projected +=
                            state[state_index] * output_state[vector_base + state_dimension];
                    }
                    output[value_index] = projected + value * skip[head];
                }
            }
        }
    }
    Ok((state, output))
}

/// Deterministic host reference for the gated-delta recurrence.
///
/// Query, key, and value use flattened `[batch, sequence, heads, dimensions]`
/// storage. Decay is either `[batch, sequence, heads]` or the same vector
/// shape as query/key. Returned state is `[batch, heads, key_dim, value_dim]`.
#[allow(clippy::too_many_arguments)]
pub fn reference_gated_delta_scan(
    batch: usize,
    sequence: usize,
    heads: usize,
    key_dim: usize,
    value_dim: usize,
    query: &[f32],
    key: &[f32],
    value: &[f32],
    log_decay: &[f32],
    vector_decay: bool,
    beta: &[f32],
    initial_state: Option<&[f32]>,
) -> Result<(Vec<f32>, Vec<f32>), Error> {
    let key_values = batch * sequence * heads * key_dim;
    let values = batch * sequence * heads * value_dim;
    let groups = batch * sequence * heads;
    let state_values = batch * heads * key_dim * value_dim;
    if query.len() != key_values
        || key.len() != key_values
        || value.len() != values
        || beta.len() != groups
        || log_decay.len() != if vector_decay { key_values } else { groups }
        || initial_state.is_some_and(|state| state.len() != state_values)
    {
        return Err(Error::backend("invalid gated-delta reference geometry"));
    }
    let mut state = initial_state.map_or_else(|| vec![0.0; state_values], <[f32]>::to_vec);
    let mut output = vec![0.0; values];
    for batch_index in 0..batch {
        for token in 0..sequence {
            for head in 0..heads {
                let group = (batch_index * sequence + token) * heads + head;
                let state_group = (batch_index * heads + head) * key_dim * value_dim;
                for value_index in 0..value_dim {
                    let mut memory = 0.0f32;
                    for key_index in 0..key_dim {
                        let vector_index = group * key_dim + key_index;
                        let decay = if vector_decay {
                            log_decay[vector_index]
                        } else {
                            log_decay[group]
                        }
                        .exp();
                        let state_index = state_group + key_index * value_dim + value_index;
                        state[state_index] *= decay;
                        memory += state[state_index] * key[vector_index];
                    }
                    let value_index_flat = group * value_dim + value_index;
                    let delta = (value[value_index_flat] - memory) * beta[group];
                    let mut accumulated = 0.0f32;
                    for key_index in 0..key_dim {
                        let vector_index = group * key_dim + key_index;
                        let state_index = state_group + key_index * value_dim + value_index;
                        state[state_index] += key[vector_index] * delta;
                        accumulated += state[state_index] * query[vector_index];
                    }
                    output[value_index_flat] = accumulated;
                }
            }
        }
    }
    Ok((state, output))
}

#[cfg(test)]
mod gated_delta_reference_tests {
    use super::reference_gated_delta_scan;

    #[test]
    fn chunked_continuation_matches_one_scan() {
        let query = [0.5, -0.25, 0.1, 0.2, -0.4, 0.8];
        let key = [0.3, 0.4, -0.2, 0.7, 0.6, -0.1];
        let value = [1.0, -0.5, 0.25, 0.75, -0.3, 0.9];
        let decay = [-0.2, -0.1, -0.4, -0.3, -0.5, -0.25];
        let beta = [0.8, 0.6, 0.4];
        let (expected_state, expected) = reference_gated_delta_scan(
            1, 3, 1, 2, 2, &query, &key, &value, &decay, true, &beta, None,
        )
        .unwrap();
        let (state, mut actual) = reference_gated_delta_scan(
            1,
            2,
            1,
            2,
            2,
            &query[..4],
            &key[..4],
            &value[..4],
            &decay[..4],
            true,
            &beta[..2],
            None,
        )
        .unwrap();
        let (actual_state, tail) = reference_gated_delta_scan(
            1,
            1,
            1,
            2,
            2,
            &query[4..],
            &key[4..],
            &value[4..],
            &decay[4..],
            true,
            &beta[2..],
            Some(&state),
        )
        .unwrap();
        actual.extend(tail);
        assert!(expected
            .iter()
            .zip(actual)
            .all(|(left, right)| (left - right).abs() < 1e-6));
        assert!(expected_state
            .iter()
            .zip(actual_state)
            .all(|(left, right)| (left - right).abs() < 1e-6));
    }
}

#[cfg(test)]
mod selective_state_space_reference_tests {
    use super::reference_selective_state_space_scan;

    #[test]
    fn continuation_matches_one_scan() {
        let values = [0.2, -0.4, 0.8, 0.5, -0.3, 0.7];
        let input_state = [0.1, 0.3, -0.2, 0.4, 0.6, -0.5];
        let output_state = [0.7, -0.1, 0.2, 0.5, -0.4, 0.9];
        let time_step = [-0.3, 0.1, -0.2];
        let bias = [0.05];
        let transition = [-0.4];
        let skip = [0.25];
        let (expected_state, expected) = reference_selective_state_space_scan(
            1,
            3,
            1,
            2,
            2,
            &values,
            &input_state,
            &output_state,
            &time_step,
            &bias,
            &transition,
            &skip,
            0.001,
            None,
        )
        .unwrap();
        let (state, mut actual) = reference_selective_state_space_scan(
            1,
            2,
            1,
            2,
            2,
            &values[..4],
            &input_state[..4],
            &output_state[..4],
            &time_step[..2],
            &bias,
            &transition,
            &skip,
            0.001,
            None,
        )
        .unwrap();
        let (actual_state, tail) = reference_selective_state_space_scan(
            1,
            1,
            1,
            2,
            2,
            &values[4..],
            &input_state[4..],
            &output_state[4..],
            &time_step[2..],
            &bias,
            &transition,
            &skip,
            0.001,
            Some(&state),
        )
        .unwrap();
        actual.extend(tail);
        assert!(expected
            .iter()
            .zip(actual)
            .all(|(left, right)| (left - right).abs() < 1e-6));
        assert!(expected_state
            .iter()
            .zip(actual_state)
            .all(|(left, right)| (left - right).abs() < 1e-6));
    }
}

/// Opaque tensor handle and the neural operations required by shared Eredu
/// architectures.
///
/// Implementations must preserve backend-native execution semantics. None of
/// these operations imply host materialization or synchronization.
pub trait Tensor: Clone + Debug + Sized + 'static {
    /// Backend execution context, such as a stream or command queue.
    type Context: ?Sized;

    /// Logical tensor shape maintained without materializing tensor values.
    fn shape(&self) -> &[i32];

    /// Returns one logical dimension.
    fn dim(&self, axis: usize) -> i32 {
        self.shape()[axis]
    }

    /// Allocates an unloaded floating-point parameter tensor.
    fn unloaded_f32(shape: &[i32], context: &Self::Context) -> Result<Self, Error>;
    /// Allocates an unloaded signed 32-bit integer parameter tensor.
    fn unloaded_i32(shape: &[i32], context: &Self::Context) -> Result<Self, Error> {
        let _ = (shape, context);
        Err(Error::backend(
            "I32 parameter allocation is not implemented by this backend",
        ))
    }
    /// Creates a floating-point tensor from host initialization data.
    fn from_f32_slice(
        values: &[f32],
        shape: &[i32],
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Creates a signed 32-bit integer tensor from host initialization data.
    fn from_i32_slice(
        values: &[i32],
        shape: &[i32],
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (values, shape, context);
        Err(Error::backend(
            "I32 tensor construction is not implemented by this backend",
        ))
    }
    /// Explicitly materializes floating-point tensor values on the host.
    fn to_f32_vec(&self, context: &Self::Context) -> Result<Vec<f32>, Error> {
        let _ = context;
        Err(Error::backend(
            "F32 host materialization is not implemented by this backend",
        ))
    }
    /// Explicitly materializes signed 32-bit integer tensor values on the host.
    fn to_i32_vec(&self, context: &Self::Context) -> Result<Vec<i32>, Error> {
        let _ = context;
        Err(Error::backend(
            "I32 host materialization is not implemented by this backend",
        ))
    }
    /// Creates a floating-point tensor filled with one scalar.
    fn full_f32(value: f32, shape: &[i32], context: &Self::Context) -> Result<Self, Error> {
        let _ = (value, shape, context);
        Err(Error::backend(
            "filled tensor construction is not implemented by this backend",
        ))
    }
    /// Creates a signed 32-bit integer tensor filled with one scalar.
    fn full_i32(value: i32, shape: &[i32], context: &Self::Context) -> Result<Self, Error> {
        let _ = (value, shape, context);
        Err(Error::backend(
            "filled I32 tensor construction is not implemented by this backend",
        ))
    }
    /// Elementwise addition.
    fn add(&self, rhs: &Self, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise subtraction.
    fn subtract(&self, rhs: &Self, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise multiplication.
    fn multiply(&self, rhs: &Self, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise multiplication by a floating-point scalar.
    fn multiply_scalar(&self, rhs: f32, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise division.
    fn divide(&self, rhs: &Self, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise square.
    fn square(&self, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise hyperbolic tangent.
    fn tanh(&self, context: &Self::Context) -> Result<Self, Error> {
        let _ = context;
        Err(Error::backend(
            "tanh is not implemented by this tensor backend",
        ))
    }
    /// Elementwise maximum with a scalar.
    fn maximum_scalar(&self, rhs: f32, context: &Self::Context) -> Result<Self, Error>;
    /// Elementwise maximum with one signed integer while preserving an
    /// integral input representation.
    fn maximum_i32(&self, rhs: i32, context: &Self::Context) -> Result<Self, Error> {
        self.maximum_scalar(rhs as f32, context)
    }
    /// Elementwise clamp using backend tensor bounds that may be scalar or broadcastable.
    fn clip(&self, minimum: &Self, maximum: &Self, context: &Self::Context) -> Result<Self, Error> {
        let _ = (minimum, maximum, context);
        Err(Error::backend(
            "clip is not implemented by this tensor backend",
        ))
    }

    /// Softmax over one axis.
    fn softmax_axis(
        &self,
        axis: i32,
        precise: bool,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (axis, precise, context);
        Err(Error::backend(
            "softmax is not implemented by this tensor backend",
        ))
    }

    /// Reshapes without changing logical element order.
    fn reshape(&self, shape: &[i32], context: &Self::Context) -> Result<Self, Error>;
    /// Broadcasts to a compatible target shape.
    fn broadcast_to(&self, shape: &[i32], context: &Self::Context) -> Result<Self, Error> {
        let _ = (shape, context);
        Err(Error::backend(
            "broadcasting is not implemented by this tensor backend",
        ))
    }
    /// Permutes axes.
    fn transpose_axes(&self, axes: &[i32], context: &Self::Context) -> Result<Self, Error>;
    /// Swaps two axes.
    fn swap_axes(&self, left: i32, right: i32, context: &Self::Context) -> Result<Self, Error>;
    /// Reverses the axes of a rank-two tensor.
    fn transpose(&self, context: &Self::Context) -> Result<Self, Error>;
    /// Inserts one unit dimension.
    fn expand_dims(&self, axis: i32, context: &Self::Context) -> Result<Self, Error>;
    /// Removes unit dimensions.
    fn squeeze_axes(&self, axes: &[i32], context: &Self::Context) -> Result<Self, Error>;
    /// Creates a tensor view using backend-neutral axis indexes.
    fn index(&self, indexes: &[Index], context: &Self::Context) -> Result<Self, Error>;
    /// Takes rows along one axis using a backend index tensor.
    fn take_axis(&self, indexes: &Self, axis: i32, context: &Self::Context) -> Result<Self, Error>;
    /// Creates a zero tensor with the same shape and physical dtype.
    fn zeros_like(&self, context: &Self::Context) -> Result<Self, Error> {
        let _ = context;
        Err(Error::backend(
            "dtype-preserving zero allocation is not implemented by this tensor backend",
        ))
    }
    /// Compares every element with one signed integer scalar.
    fn equal_i32(&self, value: i32, context: &Self::Context) -> Result<Self, Error> {
        let _ = (value, context);
        Err(Error::backend(
            "integer scalar comparison is not implemented by this tensor backend",
        ))
    }
    /// Elementwise logical disjunction over two boolean tensors.
    fn logical_or(&self, rhs: &Self, context: &Self::Context) -> Result<Self, Error> {
        let _ = (rhs, context);
        Err(Error::backend(
            "logical disjunction is not implemented by this tensor backend",
        ))
    }
    /// Selects elements from two broadcast-compatible tensors using a boolean condition.
    fn where_condition(
        condition: &Self,
        when_true: &Self,
        when_false: &Self,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (condition, when_true, when_false, context);
        Err(Error::backend(
            "conditional selection is not implemented by this tensor backend",
        ))
    }
    /// Scatters source rows into the true entries of a boolean mask.
    fn masked_scatter(
        &self,
        mask: &Self,
        source: &Self,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (mask, source, context);
        Err(Error::backend(
            "masked scatter is not implemented by this tensor backend",
        ))
    }

    /// Applies rotary positions using caller-supplied reciprocal frequencies.
    fn rope_with_frequencies(
        &self,
        dimensions: i32,
        traditional: bool,
        offset: i32,
        frequencies: &Self,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (dimensions, traditional, offset, frequencies, context);
        Err(Error::backend(
            "explicit-frequency rotary positions are not implemented by this tensor backend",
        ))
    }

    /// Concatenates tensors along an axis.
    fn concatenate(values: &[Self], axis: i32, context: &Self::Context) -> Result<Self, Error>;
    /// Stacks tensors along a new axis.
    fn stack(values: &[Self], axis: i32, context: &Self::Context) -> Result<Self, Error>;
    /// Matrix multiplication.
    fn matmul(lhs: &Self, rhs: &Self, context: &Self::Context) -> Result<Self, Error>;
    /// Reduction sum.
    fn sum_axis(
        value: &Self,
        axis: i32,
        keep_dims: bool,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Reduction mean.
    fn mean_axis(
        value: &Self,
        axis: i32,
        keep_dims: bool,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let width = value
            .shape()
            .get(if axis < 0 {
                usize::try_from(value.shape().len() as i32 + axis).unwrap_or(usize::MAX)
            } else {
                usize::try_from(axis).unwrap_or(usize::MAX)
            })
            .copied()
            .ok_or_else(|| Error::backend(format!("mean axis {axis} is out of range")))?;
        Self::sum_axis(value, axis, keep_dims, context)?
            .multiply_scalar(1.0 / width as f32, context)
    }
    /// Reduction argmin.
    fn argmin_axis(
        value: &Self,
        axis: i32,
        keep_dims: bool,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Pads a tensor.
    fn pad(
        value: &Self,
        widths: &[(i32, i32)],
        mode: PadMode,
        context: &Self::Context,
    ) -> Result<Self, Error>;

    /// One-dimensional convolution.
    #[allow(clippy::too_many_arguments)]
    fn conv1d(
        input: &Self,
        weight: &Self,
        stride: i32,
        padding: i32,
        dilation: i32,
        groups: i32,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Two-dimensional convolution over canonical NHWC inputs and OHWI weights.
    #[allow(clippy::too_many_arguments)]
    fn conv2d(
        input: &Self,
        weight: &Self,
        stride: (i32, i32),
        padding: (i32, i32),
        dilation: (i32, i32),
        groups: i32,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (input, weight, stride, padding, dilation, groups, context);
        Err(Error::backend(
            "two-dimensional convolution is not implemented by this backend",
        ))
    }
    /// One-dimensional transposed convolution.
    #[allow(clippy::too_many_arguments)]
    fn conv_transpose1d(
        input: &Self,
        weight: &Self,
        stride: i32,
        padding: i32,
        dilation: i32,
        output_padding: i32,
        groups: i32,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Affine linear projection. Backends may use fused or quantized paths.
    fn linear(
        input: &Self,
        weight: &Self,
        bias: Option<&Self>,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Layer normalization.
    fn layer_norm(
        input: &Self,
        weight: Option<&Self>,
        bias: Option<&Self>,
        epsilon: f32,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Gaussian error linear unit.
    fn gelu(input: &Self, context: &Self::Context) -> Result<Self, Error>;
    /// Exponential linear unit.
    fn elu(input: &Self, alpha: f32, context: &Self::Context) -> Result<Self, Error>;
    /// Rotary positional encoding.
    #[allow(clippy::too_many_arguments)]
    fn rope(
        input: &Self,
        dimensions: i32,
        traditional: bool,
        base: f32,
        scale: f32,
        offset: i32,
        context: &Self::Context,
    ) -> Result<Self, Error>;
    /// Builds cosine and sine tensors for explicit multi-axis positions.
    fn multi_axis_rotary_embeddings(
        position_ids: &Self,
        spec: &multimodal::MultiAxisRotarySpec,
        context: &Self::Context,
    ) -> Result<(Self, Self), Error> {
        let _ = (position_ids, spec, context);
        Err(Error::backend(
            "multi-axis rotary embeddings are not implemented by this backend",
        ))
    }
    /// Projects selected output rows and scatters them into vocabulary order.
    fn masked_output_projection(
        input: multimodal::MaskedOutputProjectionInput<'_, Self>,
        context: &Self::Context,
    ) -> Result<Self, Error> {
        let _ = (input, context);
        Err(Error::backend(
            "masked output projection is not implemented by this backend",
        ))
    }
    /// Scaled dot-product attention. Backends retain control over fusion.
    fn scaled_dot_product_attention(
        queries: &Self,
        keys: &Self,
        values: &Self,
        scale: f32,
        mask: AttentionMask<'_, Self>,
        context: &Self::Context,
    ) -> Result<Self, Error>;
}

/// One trainable parameter owned by a generic architecture module.
#[derive(Debug, Clone)]
pub struct Parameter<T> {
    spec: ParameterSpec,
    trainable: bool,
    value: T,
}

impl<T> Parameter<T> {
    /// Wraps a backend tensor as an authoritative parameter slot.
    pub fn new(spec: ParameterSpec, value: T) -> Self {
        let trainable = spec.trainable;
        Self {
            spec,
            trainable,
            value,
        }
    }
    /// Borrows the backend tensor.
    pub const fn as_ref(&self) -> &T {
        &self.value
    }
    /// Replaces the backend tensor.
    pub fn replace(&mut self, value: T) {
        self.value = value;
    }
}

impl<T: Tensor> Parameter<T> {
    /// Creates an unloaded floating-point parameter.
    pub fn unloaded(
        spec: ParameterSpec,
        shape: &[i32],
        context: &T::Context,
    ) -> Result<Self, Error> {
        Ok(Self::new(spec, T::unloaded_f32(shape, context)?))
    }

    /// Creates an unloaded signed 32-bit integer parameter.
    pub fn unloaded_i32(
        spec: ParameterSpec,
        shape: &[i32],
        context: &T::Context,
    ) -> Result<Self, Error> {
        Ok(Self::new(spec, T::unloaded_i32(shape, context)?))
    }
}

impl<T: 'static> Parameterized<T> for Parameter<T> {
    fn visit_parameters<'a, V>(&'a self, visitor: &mut V)
    where
        V: ParameterVisitor<'a, T>,
    {
        visitor.visit(
            ParameterMetadata::from_spec(&self.spec, self.trainable),
            &self.value,
        );
    }

    fn visit_parameters_mut<'a, V>(&'a mut self, visitor: &mut V)
    where
        V: ParameterVisitorMut<'a, T>,
    {
        visitor.visit_mut(
            ParameterMetadata::from_spec(&self.spec, self.trainable),
            &mut self.value,
        );
    }

    fn set_trainable(&mut self, trainable: bool) {
        self.trainable = trainable;
    }
}

impl<T: 'static, M: Parameterized<T>> Parameterized<T> for Vec<M> {
    fn visit_parameters<'a, V>(&'a self, visitor: &mut V)
    where
        V: ParameterVisitor<'a, T>,
    {
        for module in self {
            module.visit_parameters(visitor);
        }
    }

    fn visit_parameters_mut<'a, V>(&'a mut self, visitor: &mut V)
    where
        V: ParameterVisitorMut<'a, T>,
    {
        for module in self {
            module.visit_parameters_mut(visitor);
        }
    }

    fn set_trainable(&mut self, trainable: bool) {
        for module in self {
            module.set_trainable(trainable);
        }
    }
}

impl<T: 'static, M: Parameterized<T>> Parameterized<T> for Option<M> {
    fn visit_parameters<'a, V>(&'a self, visitor: &mut V)
    where
        V: ParameterVisitor<'a, T>,
    {
        if let Some(module) = self {
            module.visit_parameters(visitor);
        }
    }

    fn visit_parameters_mut<'a, V>(&'a mut self, visitor: &mut V)
    where
        V: ParameterVisitorMut<'a, T>,
    {
        if let Some(module) = self {
            module.visit_parameters_mut(visitor);
        }
    }

    fn set_trainable(&mut self, trainable: bool) {
        if let Some(module) = self {
            module.set_trainable(trainable);
        }
    }
}

/// Post-convolution activation selected by architecture policy.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConvolutionActivation {
    /// Preserve the affine convolution output.
    Identity,
    /// Apply the sigmoid linear unit.
    Silu,
}

/// Geometry and parameter identity for a causal depthwise convolution.
#[derive(Debug, Clone)]
pub struct CausalDepthwiseConvolutionSpec {
    /// Number of independent channels.
    pub channels: i32,
    /// Causal kernel width, including the current token.
    pub kernel_size: i32,
    /// Checkpoint-facing kernel stored as `[channels, 1, kernel]`.
    pub weight: ParameterSpec,
    /// Optional per-channel affine bias.
    pub bias: Option<ParameterSpec>,
    /// Activation applied after convolution and bias.
    pub activation: ConvolutionActivation,
}

impl CausalDepthwiseConvolutionSpec {
    /// Validates positive geometry before allocating backend parameters.
    pub fn validate(&self) -> Result<(), Error> {
        if self.channels <= 0 {
            return Err(Error::backend(format!(
                "causal depthwise convolution channels must be positive, got {}",
                self.channels
            )));
        }
        if self.kernel_size <= 0 {
            return Err(Error::backend(format!(
                "causal depthwise convolution kernel size must be positive, got {}",
                self.kernel_size
            )));
        }
        Ok(())
    }
}

/// Output and exact bounded history produced by one causal convolution call.
#[derive(Debug, Clone)]
pub struct CausalDepthwiseConvolutionOutput<T> {
    /// Activated convolution output shaped like the input.
    pub output: T,
    /// Last `kernel_size - 1` inputs, or `None` for a width-one kernel.
    pub history: Option<T>,
}

/// Backend-neutral causal depthwise convolution.
///
/// The layer owns only parameters and equations. Callers keep the returned
/// bounded history in their runtime state realization.
#[derive(Debug, Clone, Parameterized)]
#[parameterized(tensor = "B::Tensor")]
pub struct CausalDepthwiseConvolution<B: NeuralBackend> {
    /// Checkpoint-layout kernel shaped `[channels, 1, kernel]`.
    pub weight: Parameter<B::Tensor>,
    /// Optional per-channel bias.
    pub bias: Option<Parameter<B::Tensor>>,
    #[parameter(skip)]
    channels: i32,
    #[parameter(skip)]
    kernel_size: i32,
    #[parameter(skip)]
    activation: ConvolutionActivation,
}

impl<B: NeuralBackend> CausalDepthwiseConvolution<B> {
    /// Creates unloaded convolution parameters.
    pub fn new(
        spec: CausalDepthwiseConvolutionSpec,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<Self, Error> {
        spec.validate()?;
        Ok(Self {
            weight: Parameter::unloaded(
                spec.weight,
                &[spec.channels, 1, spec.kernel_size],
                context,
            )?,
            bias: spec
                .bias
                .map(|bias| Parameter::unloaded(bias, &[spec.channels], context))
                .transpose()?,
            channels: spec.channels,
            kernel_size: spec.kernel_size,
            activation: spec.activation,
        })
    }

    /// Returns the exact retained causal-history length.
    pub const fn history_len(&self) -> i32 {
        self.kernel_size - 1
    }

    /// Applies the convolution and returns the replacement bounded history.
    pub fn forward(
        &self,
        input: &B::Tensor,
        history: Option<&B::Tensor>,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<CausalDepthwiseConvolutionOutput<B::Tensor>, Error> {
        let shape = input.shape();
        if shape.len() != 3 || shape[0] <= 0 || shape[1] <= 0 || shape[2] != self.channels {
            return Err(Error::backend(format!(
                "causal depthwise convolution expects [batch, sequence, {}], got {shape:?}",
                self.channels
            )));
        }
        let history_len = self.history_len();
        let padded = if history_len == 0 {
            if history.is_some() {
                return Err(Error::backend(
                    "width-one causal convolution does not accept history",
                ));
            }
            input.clone()
        } else if let Some(history) = history {
            let expected = [shape[0], history_len, self.channels];
            if history.shape() != expected {
                return Err(Error::backend(format!(
                    "causal depthwise convolution history must have shape {expected:?}, got {:?}",
                    history.shape()
                )));
            }
            B::Tensor::concatenate(&[history.clone(), input.clone()], 1, context)?
        } else {
            B::Tensor::pad(
                input,
                &[(0, 0), (history_len, 0), (0, 0)],
                PadMode::Constant,
                context,
            )?
        };
        let execution_weight = self.weight.as_ref().swap_axes(1, 2, context)?;
        let mut output =
            B::Tensor::conv1d(&padded, &execution_weight, 1, 0, 1, self.channels, context)?;
        if output.shape() != shape {
            return Err(Error::backend(format!(
                "causal depthwise convolution backend returned shape {:?}, expected {shape:?}",
                output.shape()
            )));
        }
        if let Some(bias) = &self.bias {
            let bias = bias
                .as_ref()
                .reshape(&[1, 1, self.channels], context)?
                .broadcast_to(shape, context)?;
            output = output.add(&bias, context)?;
        }
        if self.activation == ConvolutionActivation::Silu {
            output = B::silu(output, context)?;
        }
        let history = (history_len > 0)
            .then(|| {
                padded.index(
                    &[
                        Index::Full,
                        Index::Range(shape[1], shape[1] + history_len),
                        Index::Full,
                    ],
                    context,
                )
            })
            .transpose()?;
        Ok(CausalDepthwiseConvolutionOutput { output, history })
    }
}

/// Construction policy for a gated causal short convolution.
#[derive(Debug, Clone)]
pub struct GatedShortConvolutionSpec {
    /// Hidden width accepted by the fused input projection.
    pub input_dimensions: i32,
    /// Rank-local convolution channel count.
    pub channels: i32,
    /// Hidden width returned by the output projection.
    pub output_dimensions: i32,
    /// Fused B/C/x projection with output width `3 * channels`.
    pub input_projection: LinearSpec,
    /// Projection from convolution channels to the output width.
    pub output_projection: LinearSpec,
    /// Shared causal depthwise convolution parameters.
    pub convolution: CausalDepthwiseConvolutionSpec,
}

impl GatedShortConvolutionSpec {
    /// Validates the fused segment and convolution geometry.
    pub fn validate(&self) -> Result<(), Error> {
        self.convolution.validate()?;
        let fused = self
            .channels
            .checked_mul(3)
            .ok_or_else(|| Error::backend("gated short-convolution width overflowed"))?;
        if self.input_dimensions <= 0
            || self.channels <= 0
            || self.output_dimensions <= 0
            || self.convolution.channels != self.channels
            || self.input_projection.input != self.input_dimensions
            || self.input_projection.output != fused
            || self.output_projection.input != self.channels
            || self.output_projection.output != self.output_dimensions
        {
            return Err(Error::backend(format!(
                "invalid gated short-convolution geometry input={} channels={} output={} fused_projection={}x{} output_projection={}x{} convolution_channels={}",
                self.input_dimensions,
                self.channels,
                self.output_dimensions,
                self.input_projection.input,
                self.input_projection.output,
                self.output_projection.input,
                self.output_projection.output,
                self.convolution.channels,
            )));
        }
        Ok(())
    }
}

/// Output and replacement bounded state from a gated short convolution.
#[derive(Debug, Clone)]
pub struct GatedShortConvolutionOutput<T> {
    /// Projected hidden states.
    pub output: T,
    /// Last causal input values retained by the depthwise convolution.
    pub history: Option<T>,
}

/// Fused gated short-convolution layer shared by hybrid decoders.
#[derive(Debug, Clone, Parameterized)]
#[parameterized(tensor = "B::Tensor")]
pub struct GatedShortConvolution<B: NeuralBackend> {
    /// Fused B/C/x input projection.
    pub input_projection: B::Linear,
    /// Shared causal depthwise convolution.
    pub convolution: CausalDepthwiseConvolution<B>,
    /// Output projection.
    pub output_projection: B::Linear,
    #[parameter(skip)]
    channels: i32,
}

impl<B: NeuralBackend> GatedShortConvolution<B> {
    /// Builds one unloaded gated short convolution.
    pub fn new(
        spec: GatedShortConvolutionSpec,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<Self, Error> {
        spec.validate()?;
        Ok(Self {
            input_projection: B::linear(spec.input_projection, context)?,
            convolution: CausalDepthwiseConvolution::new(spec.convolution, context)?,
            output_projection: B::linear(spec.output_projection, context)?,
            channels: spec.channels,
        })
    }

    fn hidden(
        &mut self,
        input: &B::Tensor,
        history: Option<&B::Tensor>,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<(B::Tensor, Option<B::Tensor>), Error> {
        let projected = self.input_projection.forward(input, context)?;
        let rank = projected.shape().len();
        if rank == 0 || projected.shape()[rank - 1] != 3 * self.channels {
            return Err(Error::backend(format!(
                "gated short-convolution projection returned shape {:?}, expected final width {}",
                projected.shape(),
                3 * self.channels
            )));
        }
        let mut segment = vec![Index::Full; rank];
        segment[rank - 1] = Index::Range(0, self.channels);
        let b = projected.index(&segment, context)?;
        segment[rank - 1] = Index::Range(self.channels, 2 * self.channels);
        let c = projected.index(&segment, context)?;
        segment[rank - 1] = Index::Range(2 * self.channels, 3 * self.channels);
        let x = projected.index(&segment, context)?;
        let convolution = self
            .convolution
            .forward(&b.multiply(&x, context)?, history, context)?;
        Ok((
            c.multiply(&convolution.output, context)?,
            convolution.history,
        ))
    }

    /// Executes the replicated layer and returns replacement bounded state.
    pub fn forward(
        &mut self,
        input: &B::Tensor,
        history: Option<&B::Tensor>,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<GatedShortConvolutionOutput<B::Tensor>, Error> {
        let (hidden, history) = self.hidden(input, history, context)?;
        Ok(GatedShortConvolutionOutput {
            output: self.output_projection.forward(&hidden, context)?,
            history,
        })
    }

    /// Executes the same layer with a row-parallel output projection.
    pub fn forward_parallel(
        &mut self,
        input: &B::Tensor,
        history: Option<&B::Tensor>,
        parallel: &B::ParallelContext,
        context: &<B::Tensor as Tensor>::Context,
    ) -> Result<GatedShortConvolutionOutput<B::Tensor>, Error> {
        let (hidden, history) = self.hidden(input, history, context)?;
        Ok(GatedShortConvolutionOutput {
            output: B::row_parallel_linear(
                &mut self.output_projection,
                &hidden,
                parallel,
                context,
            )?,
            history,
        })
    }
}

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

    fn dense_format() -> LinearFormatSpec {
        LinearFormatSpec::unscaled(LinearFormat::Dense).unwrap()
    }

    fn parameters(prefix: &str) -> GatedProductGroupParameters {
        let projection = |name| {
            GroupedProjectionSpec::new(
                ParameterSpec::trainable(name).unwrap(),
                None,
                dense_format(),
            )
            .unwrap()
        };
        GatedProductGroupParameters::new(
            projection(format!("{prefix}.gate.weight")),
            projection(format!("{prefix}.up.weight")),
            projection(format!("{prefix}.down.weight")),
        )
    }

    #[test]
    fn top_k_selection_policy_rejects_invalid_counts() {
        assert!(TopKGroupSelectionSpec::new(8, 2, GroupScoring::Softmax, true).is_ok());
        assert!(TopKGroupSelectionSpec::new(0, 1, GroupScoring::Softmax, false).is_err());
        assert!(TopKGroupSelectionSpec::new(8, 9, GroupScoring::Softmax, false).is_err());
    }

    #[test]
    fn gated_product_policy_rejects_malformed_scalars() {
        assert!(
            GatedProductPolicy::new(GatedProductActivation::Silu, Some(0.0), None, 1.0, 0.0,)
                .is_err()
        );
        assert!(GatedProductPolicy::new(
            GatedProductActivation::Silu,
            None,
            Some(f32::NAN),
            1.0,
            0.0,
        )
        .is_err());
        assert!(
            GatedProductPolicy::new(GatedProductActivation::Silu, None, None, 0.0, 0.0,).is_err()
        );
        assert!(GatedProductPolicy::new(
            GatedProductActivation::Silu,
            None,
            None,
            1.0,
            f32::INFINITY,
        )
        .is_err());
    }

    #[test]
    fn selector_projection_and_correction_biases_require_distinct_identities() {
        let shared_bias = ParameterSpec::trainable("selector.bias").unwrap();
        let spec = TopKGroupSelectorSpec::new(
            4,
            ParameterSpec::trainable("selector.weight").unwrap(),
            dense_format(),
            TopKGroupSelectionSpec::new(2, 1, GroupScoring::SelectedSoftmax, false).unwrap(),
        )
        .unwrap()
        .with_bias(shared_bias.clone())
        .unwrap();

        assert!(spec.with_correction_bias(shared_bias).is_err());
    }

    #[test]
    fn independent_group_layout_requires_exact_cardinality() {
        assert!(GroupedGatedProductSpec::new(
            2,
            16,
            8,
            16,
            eredu_nn::GatedProductPolicy::ordinary_silu(),
            GatedProductGroupLayout::Independent(vec![parameters("e0"), parameters("e1")]),
        )
        .is_ok());
        assert!(GroupedGatedProductSpec::new(
            2,
            16,
            8,
            16,
            eredu_nn::GatedProductPolicy::ordinary_silu(),
            GatedProductGroupLayout::Independent(vec![parameters("e0")]),
        )
        .is_err());
    }

    #[test]
    fn gated_product_bank_rejects_reused_projection_bias_identity() {
        let shared = ParameterSpec::trainable("groups.gate_up").unwrap();
        let gate_up = GroupedProjectionSpec::new(shared.clone(), Some(shared), dense_format());
        assert!(gate_up.is_err());
    }

    #[test]
    fn quantized_group_projection_requires_explicit_companion_identities() {
        let format =
            LinearFormat::Affine(eredu_checkpoint::AffineQuantization::new(32, 4).unwrap());
        let projection = |format| {
            GroupedProjectionSpec::new(
                ParameterSpec::trainable("arbitrary.group.matrix").unwrap(),
                None,
                format,
            )
        };
        assert!(LinearFormatSpec::unscaled(format).is_err());
        assert!(projection(
            LinearFormatSpec::affine(
                format,
                ParameterSpec::trainable("unrelated.scale.identity").unwrap(),
                ParameterSpec::trainable("unrelated.affine.identity").unwrap(),
            )
            .unwrap()
        )
        .is_ok());
    }
}

/// Generic affine projection.
#[derive(Debug, Clone)]
pub struct Linear<T> {
    /// Projection weights shaped `[output, input]`.
    pub weight: Parameter<T>,
    /// Optional output bias.
    pub bias: Option<Parameter<T>>,
}

impl<T: Tensor> Linear<T> {
    /// Creates unloaded projection parameters.
    pub fn unloaded(spec: LinearSpec, context: &T::Context) -> Result<Self, Error> {
        Ok(Self {
            weight: Parameter::unloaded(spec.weight, &[spec.output, spec.input], context)?,
            bias: spec
                .bias
                .map(|bias| Parameter::unloaded(bias, &[spec.output], context))
                .transpose()?,
        })
    }

    /// Applies the projection without materializing backend tensors.
    pub fn forward(&self, input: &T, context: &T::Context) -> Result<T, Error> {
        T::linear(
            input,
            self.weight.as_ref(),
            self.bias.as_ref().map(Parameter::as_ref),
            context,
        )
    }
}

impl<T: 'static> Parameterized<T> for Linear<T> {
    fn visit_parameters<'a, V>(&'a self, visitor: &mut V)
    where
        V: ParameterVisitor<'a, T>,
    {
        self.weight.visit_parameters(visitor);
        if let Some(bias) = &self.bias {
            bias.visit_parameters(visitor);
        }
    }

    fn visit_parameters_mut<'a, V>(&'a mut self, visitor: &mut V)
    where
        V: ParameterVisitorMut<'a, T>,
    {
        self.weight.visit_parameters_mut(visitor);
        if let Some(bias) = &mut self.bias {
            bias.visit_parameters_mut(visitor);
        }
    }

    fn set_trainable(&mut self, trainable: bool) {
        self.weight.set_trainable(trainable);
        if let Some(bias) = &mut self.bias {
            bias.set_trainable(trainable);
        }
    }
}

/// Generic affine layer normalization.
#[derive(Debug, Clone)]
pub struct LayerNorm<T> {
    /// Numerical stability epsilon.
    pub epsilon: f32,
    /// Optional trainable scale.
    pub weight: Option<Parameter<T>>,
    /// Optional trainable bias.
    pub bias: Option<Parameter<T>>,
}

impl<T: Tensor> LayerNorm<T> {
    /// Creates an unloaded affine layer normalization.
    pub fn unloaded(
        dimensions: i32,
        epsilon: f32,
        weight: Option<ParameterSpec>,
        bias: Option<ParameterSpec>,
        context: &T::Context,
    ) -> Result<Self, Error> {
        Ok(Self {
            epsilon,
            weight: weight
                .map(|weight| Parameter::unloaded(weight, &[dimensions], context))
                .transpose()?,
            bias: bias
                .map(|bias| Parameter::unloaded(bias, &[dimensions], context))
                .transpose()?,
        })
    }

    /// Applies layer normalization through the selected backend.
    pub fn forward(&self, input: &T, context: &T::Context) -> Result<T, Error> {
        T::layer_norm(
            input,
            self.weight.as_ref().map(Parameter::as_ref),
            self.bias.as_ref().map(Parameter::as_ref),
            self.epsilon,
            context,
        )
    }
}

impl<T: 'static> Parameterized<T> for LayerNorm<T> {
    fn visit_parameters<'a, V>(&'a self, visitor: &mut V)
    where
        V: ParameterVisitor<'a, T>,
    {
        if let Some(weight) = &self.weight {
            weight.visit_parameters(visitor);
        }
        if let Some(bias) = &self.bias {
            bias.visit_parameters(visitor);
        }
    }

    fn visit_parameters_mut<'a, V>(&'a mut self, visitor: &mut V)
    where
        V: ParameterVisitorMut<'a, T>,
    {
        if let Some(weight) = &mut self.weight {
            weight.visit_parameters_mut(visitor);
        }
        if let Some(bias) = &mut self.bias {
            bias.visit_parameters_mut(visitor);
        }
    }

    fn set_trainable(&mut self, trainable: bool) {
        if let Some(weight) = &mut self.weight {
            weight.set_trainable(trainable);
        }
        if let Some(bias) = &mut self.bias {
            bias.set_trainable(trainable);
        }
    }
}

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

    #[derive(Parameterized)]
    #[parameterized(tensor = "i32")]
    struct DerivedModule {
        first: Parameter<i32>,
        second: Option<Parameter<i32>>,
        #[parameter(skip)]
        label: &'static str,
    }

    #[derive(Parameterized)]
    #[parameterized(tensor = "i32")]
    enum DerivedChoice {
        Present(Parameter<i32>),
        Empty,
    }

    fn parameter(id: &str, value: i32) -> Parameter<i32> {
        Parameter::new(ParameterSpec::trainable(id).unwrap(), value)
    }

    #[test]
    fn derive_recurses_through_structs_options_and_enums() {
        let mut module = DerivedModule {
            first: parameter("first.weight", 1),
            second: Some(parameter("second.weight", 2)),
            label: "not a parameter",
        };
        assert_eq!(module.label, "not a parameter");
        let metadata = validate_parameter_topology::<i32, _>(&module).unwrap();
        assert_eq!(
            metadata
                .iter()
                .map(|entry| entry.id.as_str())
                .collect::<Vec<_>>(),
            ["first.weight", "second.weight"]
        );

        module.set_trainable(false);
        assert!(validate_parameter_topology::<i32, _>(&module)
            .unwrap()
            .iter()
            .all(|entry| !entry.trainable));

        let choice = DerivedChoice::Present(parameter("choice.weight", 3));
        assert_eq!(
            validate_parameter_topology::<i32, _>(&choice).unwrap()[0]
                .id
                .as_str(),
            "choice.weight"
        );
        assert!(validate_parameter_topology::<i32, _>(&DerivedChoice::Empty)
            .unwrap()
            .is_empty());
    }

    #[test]
    fn validation_rejects_duplicates_and_invalid_aliases() {
        let duplicate = vec![parameter("same.weight", 1), parameter("same.weight", 2)];
        assert!(matches!(
            validate_parameter_topology::<i32, _>(&duplicate),
            Err(ParameterTopologyError::DuplicateId(id)) if id.as_str() == "same.weight"
        ));

        let alias = Parameter::new(
            ParameterSpec {
                id: ParameterId::new("alias.weight").unwrap(),
                trainable: true,
                alias_of: Some(ParameterId::new("missing.weight").unwrap()),
                group: None,
                linear_companion: None,
                linear_companion_of: None,
            },
            1,
        );
        assert!(matches!(
            validate_parameter_topology::<i32, _>(&alias),
            Err(ParameterTopologyError::MissingAliasDestination { .. })
        ));
    }
}

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

    #[test]
    fn component_major_layout_is_checked_and_stable() {
        let layout = FusedProjectionLayout::new([
            FusedProjectionSegment::new("query", 8).unwrap(),
            FusedProjectionSegment::new("key", 4).unwrap(),
            FusedProjectionSegment::new("value", 4).unwrap(),
        ])
        .unwrap();
        assert_eq!(layout.output_width(), 16);
        assert_eq!(
            layout
                .segments()
                .iter()
                .map(|segment| (segment.name(), segment.width()))
                .collect::<Vec<_>>(),
            [("query", 8), ("key", 4), ("value", 4)]
        );
        assert!(FusedProjectionLayout::new(Vec::new()).is_err());
        assert!(FusedProjectionLayout::new([
            FusedProjectionSegment::new("same", 1).unwrap(),
            FusedProjectionSegment::new("same", 1).unwrap(),
        ])
        .is_err());
        assert!(FusedProjectionSegment::new("", 1).is_err());
        assert!(FusedProjectionSegment::new("bad", 0).is_err());
    }

    #[test]
    fn zero_sentinel_cannot_alias_an_embedding_row() {
        EmbeddingLookupPolicy::Strict.validate().unwrap();
        EmbeddingLookupPolicy::ZeroSentinel(-1).validate().unwrap();
        assert!(EmbeddingLookupPolicy::ZeroSentinel(0).validate().is_err());
    }

    #[test]
    fn vocabulary_parallel_ownership_requires_exact_global_rows() {
        let range = VocabularyParallelRange {
            global_vocabulary: 5,
            local: 0..3,
        };
        range.validate_global_rows(5).unwrap();
        assert!(range.validate_global_rows(4).is_err());
        assert!(range.validate_global_rows(-1).is_err());
    }
}

/// Generic rotary positional encoding configuration.
#[derive(Debug, Clone, Copy)]
pub struct Rope {
    dimensions: i32,
    traditional: bool,
    base: f32,
    scale: f32,
}

impl Rope {
    /// Creates a rotary positional encoding.
    pub const fn new(dimensions: i32, traditional: bool, base: f32, scale: f32) -> Self {
        Self {
            dimensions,
            traditional,
            base,
            scale,
        }
    }

    /// Applies rotary positional encoding through the selected backend.
    pub fn forward<T: Tensor>(
        &self,
        input: &T,
        offset: i32,
        context: &T::Context,
    ) -> Result<T, Error> {
        T::rope(
            input,
            self.dimensions,
            self.traditional,
            self.base,
            self.scale,
            offset,
            context,
        )
    }
}