rlx-cpu 0.2.13

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

use super::*;
use rlx_ir::*;

/// The im2col+BLAS forward conv must match the reference scalar loop
/// (up to float reassociation) across a range of shapes — strided,
/// dilated, padded, grouped, and multi-batch. Guards the default
/// `RLX_FAST_CONV` fast path (disable with `=0` for the scalar oracle).
#[test]
fn conv2d_im2col_matches_naive() {
    // (n, c_in, h, w, c_out, kh, kw, sh, sw, ph, pw, dh, dw, groups)
    let cases = [
        (1, 1, 28, 28, 8, 3, 3, 1, 1, 0, 0, 1, 1, 1), // TinyConv layer 1
        (4, 8, 13, 13, 16, 3, 3, 1, 1, 0, 0, 1, 1, 1), // TinyConv layer 2, batched
        (2, 3, 16, 16, 6, 3, 3, 2, 2, 1, 1, 1, 1, 1), // stride 2, pad 1
        (1, 4, 12, 12, 4, 3, 3, 1, 1, 2, 2, 2, 2, 1), // dilation 2
        (3, 8, 10, 10, 8, 3, 3, 1, 1, 1, 1, 1, 1, 2), // groups = 2
        (1, 2, 7, 7, 5, 1, 1, 1, 1, 0, 0, 1, 1, 1),   // 1x1
    ];
    for (idx, &(n, c_in, h, w, c_out, kh, kw, sh, sw, ph, pw, dh, dw, groups)) in
        cases.iter().enumerate()
    {
        let c_in_per_g = c_in / groups;
        let h_out = (h + 2 * ph - dh * (kh - 1) - 1) / sh + 1;
        let w_out = (w + 2 * pw - dw * (kw - 1) - 1) / sw + 1;
        // Deterministic pseudo-random inputs (no rng dep in tests).
        let mut s: u32 = 0x9e37_79b9 ^ (idx as u32 + 1);
        let mut rand = || {
            s ^= s << 13;
            s ^= s >> 17;
            s ^= s << 5;
            (s as f32 / u32::MAX as f32) - 0.5
        };
        let inp: Vec<f32> = (0..n * c_in * h * w).map(|_| rand()).collect();
        let wt: Vec<f32> = (0..c_out * c_in_per_g * kh * kw).map(|_| rand()).collect();
        let mut out_ref = vec![0f32; n * c_out * h_out * w_out];
        let mut out_fast = vec![0f32; n * c_out * h_out * w_out];

        conv2d_forward_naive(
            &inp,
            &wt,
            &mut out_ref,
            n,
            c_in,
            h,
            w,
            c_out,
            h_out,
            w_out,
            kh,
            kw,
            sh,
            sw,
            ph,
            pw,
            dh,
            dw,
            groups,
        );
        conv2d_forward_im2col(
            &inp,
            &wt,
            &mut out_fast,
            n,
            c_in,
            h,
            w,
            c_out,
            h_out,
            w_out,
            kh,
            kw,
            sh,
            sw,
            ph,
            pw,
            dh,
            dw,
            groups,
        );

        let max_abs = out_ref
            .iter()
            .zip(&out_fast)
            .map(|(a, b)| (a - b).abs())
            .fold(0f32, f32::max);
        assert!(
            max_abs < 1e-3,
            "case {idx}: im2col vs naive max abs diff {max_abs}"
        );
    }
}

/// Direct forward conv (stride-1, no-pad) must match the reference scalar
/// conv exactly-ish across channel/batch/group shapes.
#[test]
fn conv2d_direct_matches_naive() {
    // (n, c_in, h, w, c_out, kh, kw, groups)
    let cases = [
        (1, 1, 28, 28, 8, 3, 3, 1),  // TinyConv L1
        (4, 8, 13, 13, 16, 3, 3, 1), // TinyConv L2, batched
        (2, 6, 10, 10, 9, 3, 3, 3),  // groups=3
        (1, 4, 9, 9, 4, 5, 5, 1),    // 5×5 kernel
        (3, 2, 7, 7, 2, 1, 1, 1),    // 1×1
    ];
    for (idx, &(n, c_in, h, w, c_out, kh, kw, groups)) in cases.iter().enumerate() {
        let h_out = h - kh + 1;
        let w_out = w - kw + 1;
        let c_in_per_g = c_in / groups;
        let mut s: u32 = 0xfeed_1234 ^ (idx as u32 + 1);
        let mut rand = || {
            s ^= s << 13;
            s ^= s >> 17;
            s ^= s << 5;
            (s as f32 / u32::MAX as f32) - 0.5
        };
        let inp: Vec<f32> = (0..n * c_in * h * w).map(|_| rand()).collect();
        let wt: Vec<f32> = (0..c_out * c_in_per_g * kh * kw).map(|_| rand()).collect();
        let mut r = vec![0f32; n * c_out * h_out * w_out];
        let mut d = vec![0f32; n * c_out * h_out * w_out];
        conv2d_forward_naive(
            &inp, &wt, &mut r, n, c_in, h, w, c_out, h_out, w_out, kh, kw, 1, 1, 0, 0, 1, 1, groups,
        );
        conv2d_forward_direct(
            &inp, &wt, &mut d, n, c_in, h, w, c_out, h_out, w_out, kh, kw, groups,
        );
        let mx = r
            .iter()
            .zip(&d)
            .map(|(a, b)| (a - b).abs())
            .fold(0f32, f32::max);
        assert!(mx < 1e-4, "case {idx}: direct vs naive max abs diff {mx}");
    }
}

/// Winograd F(2,3) forward conv must match the reference scalar conv (up to
/// the transform's float reassociation) for 3×3 stride-1 valid convs,
/// including odd output dims (boundary tiles) and multiple channels/batches.
#[test]
fn conv2d_winograd_matches_naive() {
    // (n, c_in, h, w, c_out)  — all 3×3 stride1 valid; covers even (26) and
    // odd (11) output dims and the TinyConv channel shapes.
    let cases = [
        (1, 1, 28, 28, 8),  // TinyConv layer 1: out 26×26 (even)
        (4, 8, 13, 13, 16), // TinyConv layer 2: out 11×11 (odd) — boundary tiles
        (2, 3, 9, 9, 5),    // out 7×7 (odd)
        (1, 4, 8, 8, 4),    // out 6×6 (even)
    ];
    for (idx, &(n, c_in, h, w, c_out)) in cases.iter().enumerate() {
        let h_out = h - 2;
        let w_out = w - 2;
        let mut s: u32 = 0x1234_5678 ^ (idx as u32 + 1);
        let mut rand = || {
            s ^= s << 13;
            s ^= s >> 17;
            s ^= s << 5;
            (s as f32 / u32::MAX as f32) - 0.5
        };
        let inp: Vec<f32> = (0..n * c_in * h * w).map(|_| rand()).collect();
        let wt: Vec<f32> = (0..c_out * c_in * 9).map(|_| rand()).collect();
        let mut out_ref = vec![0f32; n * c_out * h_out * w_out];
        let mut out_win = vec![0f32; n * c_out * h_out * w_out];
        conv2d_forward_naive(
            &inp,
            &wt,
            &mut out_ref,
            n,
            c_in,
            h,
            w,
            c_out,
            h_out,
            w_out,
            3,
            3,
            1,
            1,
            0,
            0,
            1,
            1,
            1,
        );
        conv2d_forward_winograd(&inp, &wt, &mut out_win, n, c_in, h, w, c_out, h_out, w_out);
        let max_abs = out_ref
            .iter()
            .zip(&out_win)
            .map(|(a, b)| (a - b).abs())
            .fold(0f32, f32::max);
        assert!(
            max_abs < 1e-3,
            "case {idx}: winograd vs naive max abs diff {max_abs}"
        );
    }
}

/// Plan #45: when a Narrow's only consumer is a Rope, the thunk
/// fusion pass collapses them — the Narrow becomes Nop, and the
/// Rope reads from the parent buffer with its row stride. This
/// test runs the unfused path (batch*seq > FusedAttnBlock
/// threshold) and asserts the rewrite happened.
#[test]
fn narrow_rope_fuses_in_unfused_path() {
    let f = DType::F32;
    let mut g = Graph::new("nr_fuse");
    // Force batch*seq > 64 so FusedAttnBlock doesn't pre-empt us.
    let qkv = g.input("qkv", Shape::new(&[16, 8, 192], f)); // 16*8=128 > 64
    let cos = g.input("cos", Shape::new(&[16], f));
    let sin = g.input("sin", Shape::new(&[16], f));
    // Last-axis narrow: Q = qkv[..., 0..64]
    let q = g.narrow_(qkv, 2, 0, 64);
    let q_rope = g.rope(q, cos, sin, 16);
    g.set_outputs(vec![q_rope]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let mut narrow_count = 0;
    let mut rope_with_stride: Option<u32> = None;
    for t in &sched.thunks {
        match t {
            Thunk::Narrow { .. } => narrow_count += 1,
            Thunk::Rope { src_row_stride, .. } => rope_with_stride = Some(*src_row_stride),
            _ => {}
        }
    }
    // After fusion the Narrow is gone; only the Rope remains, and
    // it now walks with the parent QKV's row stride (3 * 64 = 192).
    assert_eq!(
        narrow_count, 0,
        "Narrow→Rope fusion should leave zero Narrow thunks; saw {narrow_count}"
    );
    assert_eq!(
        rope_with_stride,
        Some(192),
        "Rope's src_row_stride should be 192 (parent qkv axis), saw {rope_with_stride:?}"
    );
}

/// Plan #15: SSM selective scan matches a naive Python-style
/// Python-style sequential reference.
#[test]
fn ssm_selective_scan_matches_reference() {
    use rlx_ir::Philox4x32;
    let bch = 1usize;
    let s = 4usize;
    let h = 3usize;
    let n = 2usize;

    let mut rng = Philox4x32::new(13);
    let mut x = vec![0f32; bch * s * h];
    rng.fill_normal(&mut x);
    let mut delta = vec![0f32; bch * s * h];
    // Keep Δ small so exp(Δ·A) doesn't blow up.
    for v in delta.iter_mut() {
        *v = (rng.next_f32() - 0.5) * 0.1;
    }
    let mut a = vec![0f32; h * n];
    for v in a.iter_mut() {
        *v = -(rng.next_f32() * 0.5 + 0.1);
    } // negative for stability
    let mut b = vec![0f32; bch * s * n];
    rng.fill_normal(&mut b);
    let mut c = vec![0f32; bch * s * n];
    rng.fill_normal(&mut c);

    // Reference scan.
    let mut expected = vec![0f32; bch * s * h];
    for bi in 0..bch {
        let mut state = vec![0f32; h * n];
        for si in 0..s {
            for ci in 0..h {
                let d = delta[bi * s * h + si * h + ci];
                let xv = x[bi * s * h + si * h + ci];
                let mut acc = 0f32;
                for ni in 0..n {
                    let da = (d * a[ci * n + ni]).exp();
                    state[ci * n + ni] =
                        da * state[ci * n + ni] + d * b[bi * s * n + si * n + ni] * xv;
                    acc += c[bi * s * n + si * n + ni] * state[ci * n + ni];
                }
                expected[bi * s * h + si * h + ci] = acc;
            }
        }
    }

    // RLX path.
    let f = DType::F32;
    let mut g = Graph::new("ssm");
    let xn = g.input("x", Shape::new(&[bch, s, h], f));
    let dn = g.input("delta", Shape::new(&[bch, s, h], f));
    let an = g.param("a", Shape::new(&[h, n], f));
    let bn = g.param("b", Shape::new(&[bch, s, n], f));
    let cn = g.param("c", Shape::new(&[bch, s, n], f));
    let yn = g.selective_scan(xn, dn, an, bn, cn, n, Shape::new(&[bch, s, h], f));
    g.set_outputs(vec![yn]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let xn_off = arena.byte_offset(xn);
    let dn_off = arena.byte_offset(dn);
    let an_off = arena.byte_offset(an);
    let bn_off = arena.byte_offset(bn);
    let cn_off = arena.byte_offset(cn);
    let yn_off = arena.byte_offset(yn);
    let buf = arena.raw_buf_mut();
    unsafe {
        let copy = |dst: *mut f32, data: &[f32]| {
            for (i, &v) in data.iter().enumerate() {
                *dst.add(i) = v;
            }
        };
        copy(buf.as_mut_ptr().add(xn_off) as *mut f32, &x);
        copy(buf.as_mut_ptr().add(dn_off) as *mut f32, &delta);
        copy(buf.as_mut_ptr().add(an_off) as *mut f32, &a);
        copy(buf.as_mut_ptr().add(bn_off) as *mut f32, &b);
        copy(buf.as_mut_ptr().add(cn_off) as *mut f32, &c);
    }
    execute_thunks(&sched, arena.raw_buf_mut());

    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(yn_off) as *const f32;
        (0..bch * s * h).map(|i| *p.add(i)).collect()
    };

    for (i, (e, a)) in expected.iter().zip(&actual).enumerate() {
        assert!(
            (e - a).abs() < 1e-3,
            "mismatch at {i}: expected {e}, got {a}"
        );
    }
}

/// Plan #26: 1×1 conv lowers to per-batch sgemm and matches the
/// scalar 7-loop reference.
#[test]
fn conv_1x1_fast_path_matches_scalar() {
    use rlx_ir::Philox4x32;
    // [N=2, C_in=4, H=3, W=3]
    let n = 2usize;
    let c_in = 4usize;
    let h = 3usize;
    let w = 3usize;
    let c_out = 5usize;
    let mut rng = Philox4x32::new(31);
    let mut x = vec![0f32; n * c_in * h * w];
    rng.fill_normal(&mut x);
    let mut weight = vec![0f32; c_out * c_in];
    rng.fill_normal(&mut weight);

    // Reference: scalar 1×1 conv = per-batch matmul
    // out[ni, co, hi, wi] = sum_ci weight[co, ci] * x[ni, ci, hi, wi]
    let mut expected = vec![0f32; n * c_out * h * w];
    for ni in 0..n {
        for co in 0..c_out {
            for hi in 0..h {
                for wi in 0..w {
                    let mut acc = 0f32;
                    for ci in 0..c_in {
                        acc += weight[co * c_in + ci] * x[((ni * c_in) + ci) * h * w + hi * w + wi];
                    }
                    expected[((ni * c_out) + co) * h * w + hi * w + wi] = acc;
                }
            }
        }
    }

    // RLX path: build a graph with Op::Conv (kernel=[1,1], stride=[1,1], etc).
    let f = DType::F32;
    let mut g = Graph::new("conv1x1");
    let xn = g.input("x", Shape::new(&[n, c_in, h, w], f));
    let wn = g.param("w", Shape::new(&[c_out, c_in, 1, 1], f));
    // Manually add Op::Conv since there's no `g.conv()` helper.
    let cn = g.add_node(
        rlx_ir::Op::Conv {
            kernel_size: vec![1, 1],
            stride: vec![1, 1],
            padding: vec![0, 0],
            dilation: vec![1, 1],
            groups: 1,
        },
        vec![xn, wn],
        Shape::new(&[n, c_out, h, w], f),
    );
    g.set_outputs(vec![cn]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    // Verify the fast path was selected.
    let saw_fast = sched
        .thunks
        .iter()
        .any(|t| matches!(t, Thunk::Conv2D1x1 { .. }));
    let saw_slow = sched
        .thunks
        .iter()
        .any(|t| matches!(t, Thunk::Conv2D { .. }));
    assert!(saw_fast, "1×1 conv should emit Conv2D1x1");
    assert!(!saw_slow, "1×1 conv must not fall through to scalar Conv2D");

    let xn_off = arena.byte_offset(xn);
    let wn_off = arena.byte_offset(wn);
    let cn_off = arena.byte_offset(cn);
    let buf = arena.raw_buf_mut();
    unsafe {
        let xp = buf.as_mut_ptr().add(xn_off) as *mut f32;
        for (i, &v) in x.iter().enumerate() {
            *xp.add(i) = v;
        }
        let wp = buf.as_mut_ptr().add(wn_off) as *mut f32;
        for (i, &v) in weight.iter().enumerate() {
            *wp.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());

    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(cn_off) as *const f32;
        (0..(n * c_out * h * w)).map(|i| *p.add(i)).collect()
    };

    for (i, (e, a)) in expected.iter().zip(&actual).enumerate() {
        assert!(
            (e - a).abs() < 1e-3,
            "mismatch at {i}: expected {e}, got {a}"
        );
    }
}

/// Plan #5: fused dequant matmul matches the dequant-then-matmul
/// reference (i.e. `(scale * (q - z)) @ x` materialized).
#[test]
fn dequant_matmul_int8_sym_matches_reference() {
    use rlx_ir::Philox4x32;
    use rlx_ir::quant::QuantScheme;

    let m = 3usize;
    let k = 8usize;
    let n = 4usize;
    let block_size = 4usize; // 2 blocks per column
    let blocks_per_col = k / block_size;

    // Random inputs: x f32, w_q i8, scales f32. Symmetric → no zp.
    let mut rng = Philox4x32::new(99);
    let mut x = vec![0f32; m * k];
    rng.fill_normal(&mut x);
    let w_q: Vec<i8> = (0..(k * n))
        .map(|i| ((i as i32 * 13 + 7) % 127 - 63) as i8)
        .collect();
    let scales: Vec<f32> = (0..(blocks_per_col * n))
        .map(|i| 0.01 + 0.001 * i as f32)
        .collect();

    // Reference: build f32 weights from (q * scale) per block.
    let mut w_f32 = vec![0f32; k * n];
    for p in 0..k {
        let block = p / block_size;
        for j in 0..n {
            let s = scales[block * n + j];
            w_f32[p * n + j] = w_q[p * n + j] as f32 * s;
        }
    }
    let mut expected = vec![0f32; m * n];
    for i in 0..m {
        for j in 0..n {
            let mut acc = 0f32;
            for p in 0..k {
                acc += x[i * k + p] * w_f32[p * n + j];
            }
            expected[i * n + j] = acc;
        }
    }

    // RLX path.
    let f = DType::F32;
    let mut g = Graph::new("dq");
    let xn = g.input("x", Shape::new(&[m, k], f));
    let wn = g.param("w", Shape::new(&[k, n], DType::I8));
    let sn = g.param("scale", Shape::new(&[blocks_per_col, n], f));
    let zn = g.param("zp", Shape::new(&[blocks_per_col, n], f)); // unused (sym)
    let dq = g.dequant_matmul(
        xn,
        wn,
        sn,
        zn,
        QuantScheme::Int8Block {
            block_size: block_size as u32,
        },
        Shape::new(&[m, n], f),
    );
    g.set_outputs(vec![dq]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let xn_off = arena.byte_offset(xn);
    let wn_off = arena.byte_offset(wn);
    let sn_off = arena.byte_offset(sn);
    let zn_off = arena.byte_offset(zn);
    let dq_off = arena.byte_offset(dq);
    let buf = arena.raw_buf_mut();
    unsafe {
        // Seed f32 inputs.
        let xp = buf.as_mut_ptr().add(xn_off) as *mut f32;
        for (i, &v) in x.iter().enumerate() {
            *xp.add(i) = v;
        }
        let sp = buf.as_mut_ptr().add(sn_off) as *mut f32;
        for (i, &v) in scales.iter().enumerate() {
            *sp.add(i) = v;
        }
        let zp = buf.as_mut_ptr().add(zn_off) as *mut f32;
        for i in 0..(blocks_per_col * n) {
            *zp.add(i) = 0.0;
        }
        // Seed i8 weights byte-by-byte.
        let wp = buf.as_mut_ptr().add(wn_off) as *mut i8;
        for (i, &v) in w_q.iter().enumerate() {
            *wp.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());

    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(dq_off) as *const f32;
        (0..m * n).map(|i| *p.add(i)).collect()
    };

    for (i, (e, a)) in expected.iter().zip(&actual).enumerate() {
        assert!(
            (e - a).abs() < 1e-3,
            "mismatch at {i}: expected {e}, got {a}"
        );
    }
}

/// Plan #9: LoRA matmul matches the unfused 3-matmul reference.
#[test]
fn lora_matmul_matches_unfused_reference() {
    use rlx_ir::Philox4x32;

    let m = 4usize;
    let k = 8usize;
    let n = 6usize;
    let r = 2usize;
    let scale = 0.5f32;

    // Random inputs (deterministic via Philox).
    let mut rng = Philox4x32::new(42);
    let mut x = vec![0f32; m * k];
    rng.fill_normal(&mut x);
    let mut w = vec![0f32; k * n];
    rng.fill_normal(&mut w);
    let mut a = vec![0f32; k * r];
    rng.fill_normal(&mut a);
    let mut b = vec![0f32; r * n];
    rng.fill_normal(&mut b);

    // Reference: out = x·W + scale * x·A·B. Naive triple-loop.
    let naive = |a_buf: &[f32], b_buf: &[f32], rows: usize, inner: usize, cols: usize| {
        let mut o = vec![0f32; rows * cols];
        for i in 0..rows {
            for j in 0..cols {
                let mut acc = 0f32;
                for p in 0..inner {
                    acc += a_buf[i * inner + p] * b_buf[p * cols + j];
                }
                o[i * cols + j] = acc;
            }
        }
        o
    };
    let xw = naive(&x, &w, m, k, n);
    let xa = naive(&x, &a, m, k, r);
    let xab = naive(&xa, &b, m, r, n);
    let mut expected = xw;
    for i in 0..(m * n) {
        expected[i] += scale * xab[i];
    }

    // RLX path: build a graph with one LoraMatMul.
    let f = DType::F32;
    let mut g = Graph::new("lora");
    let xn = g.input("x", Shape::new(&[m, k], f));
    let wn = g.param("w", Shape::new(&[k, n], f));
    let an = g.param("a", Shape::new(&[k, r], f));
    let bn = g.param("b", Shape::new(&[r, n], f));
    let lm = g.lora_matmul(xn, wn, an, bn, scale, Shape::new(&[m, n], f));
    g.set_outputs(vec![lm]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let xn_off = arena.byte_offset(xn);
    let wn_off = arena.byte_offset(wn);
    let an_off = arena.byte_offset(an);
    let bn_off = arena.byte_offset(bn);
    let lm_off = arena.byte_offset(lm);
    let buf = arena.raw_buf_mut();
    unsafe {
        let copy = |dst: *mut f32, data: &[f32]| {
            for (i, &v) in data.iter().enumerate() {
                *dst.add(i) = v;
            }
        };
        copy(buf.as_mut_ptr().add(xn_off) as *mut f32, &x);
        copy(buf.as_mut_ptr().add(wn_off) as *mut f32, &w);
        copy(buf.as_mut_ptr().add(an_off) as *mut f32, &a);
        copy(buf.as_mut_ptr().add(bn_off) as *mut f32, &b);
    }
    execute_thunks(&sched, arena.raw_buf_mut());

    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(lm_off) as *const f32;
        (0..m * n).map(|i| *p.add(i)).collect()
    };

    for (i, (e, a)) in expected.iter().zip(&actual).enumerate() {
        assert!(
            (e - a).abs() < 1e-3,
            "mismatch at {i}: expected {e}, got {a}"
        );
    }
}

/// Plan #42: fused sampling kernel determinism + greedy fallback.
#[test]
fn sample_temperature_zero_is_argmax() {
    // Very low temperature → distribution collapses on argmax.
    // Same seed → same output bit-for-bit.
    let f = DType::F32;
    let mut g = Graph::new("samp");
    let logits = g.input("logits", Shape::new(&[1, 8], f));
    let s = g.sample(logits, 0, 1.0, 1e-3, 42, Shape::new(&[1], f));
    g.set_outputs(vec![s]);
    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let logits_off = arena.byte_offset(logits);
    let s_off = arena.byte_offset(s);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(logits_off) as *mut f32;
        // argmax = index 5 (value 9.0).
        let inputs = [0.1f32, 0.2, 0.3, 0.4, 0.5, 9.0, 0.7, 0.8];
        for (i, &v) in inputs.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());

    let token = unsafe {
        let p = arena.raw_buf().as_ptr().add(s_off) as *const f32;
        *p as usize
    };
    assert_eq!(token, 5, "low-temp sampling should pick the argmax");
}

#[test]
fn sample_top_k_one_is_deterministic() {
    // top_k=1 forces only the argmax to have nonzero probability.
    let f = DType::F32;
    let mut g = Graph::new("samp_k1");
    let logits = g.input("logits", Shape::new(&[1, 4], f));
    let s = g.sample(logits, 1, 1.0, 1.0, 7, Shape::new(&[1], f));
    g.set_outputs(vec![s]);
    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let logits_off = arena.byte_offset(logits);
    let s_off = arena.byte_offset(s);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(logits_off) as *mut f32;
        let inputs = [0.1f32, 5.0, 0.3, 0.4]; // argmax = 1
        for (i, &v) in inputs.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let token = unsafe {
        let p = arena.raw_buf().as_ptr().add(s_off) as *const f32;
        *p as usize
    };
    assert_eq!(token, 1);
}

/// Plan #44: cumsum primitive parity vs. naive scan.
#[test]
fn cumsum_inclusive_matches_naive() {
    let f = DType::F32;
    let mut g = Graph::new("cumsum");
    let x = g.input("x", Shape::new(&[2, 4], f));
    let cs = g.cumsum(x, -1, false, Shape::new(&[2, 4], f));
    g.set_outputs(vec![cs]);
    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    // Cache offsets up-front so we can drop the immutable borrow.
    let x_off = arena.byte_offset(x);
    let out_off = arena.byte_offset(cs);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(x_off) as *mut f32;
        let inputs = [1.0f32, 2.0, 3.0, 4.0, 10.0, 20.0, 30.0, 40.0];
        for (i, &v) in inputs.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());

    let out: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..8).map(|i| *p.add(i)).collect()
    };
    assert_eq!(out, vec![1.0, 3.0, 6.0, 10.0, 10.0, 30.0, 60.0, 100.0]);
}

/// Plan #46 deep: Narrow×3 → Attention fusion. The three QKV
/// narrows that BERT/Nomic emit on the unfused (batch*seq > 64)
/// path collapse into a single strided-Attention thunk.
#[test]
fn narrow_attention_fuses_in_unfused_path() {
    let f = DType::F32;
    let mut g = Graph::new("nattn_fuse");
    // batch*seq = 8*16 = 128 > 64 so FusedAttnBlock skips.
    let qkv = g.input("qkv", Shape::new(&[8, 16, 192], f)); // 3*64 = 192
    let mask = g.input("mask", Shape::new(&[8, 16], f));
    let q = g.narrow_(qkv, 2, 0, 64);
    let k = g.narrow_(qkv, 2, 64, 64);
    let v = g.narrow_(qkv, 2, 128, 64);
    let attn = g.attention(q, k, v, mask, 4, 16, Shape::new(&[8, 16, 64], f));
    g.set_outputs(vec![attn]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let mut narrow_count = 0;
    let mut attn_strides: Option<(u32, u32, u32)> = None;
    for t in &sched.thunks {
        match t {
            Thunk::Narrow { .. } => narrow_count += 1,
            Thunk::Attention {
                q_row_stride,
                k_row_stride,
                v_row_stride,
                ..
            } => attn_strides = Some((*q_row_stride, *k_row_stride, *v_row_stride)),
            _ => {}
        }
    }
    // After fusion the 3 narrows are gone; Attention now walks the
    // QKV with parent row stride = 192 (3 × 64) on all three inputs.
    assert_eq!(
        narrow_count, 0,
        "Narrow×3→Attention fusion should eliminate all 3 narrows; saw {narrow_count}"
    );
    assert_eq!(
        attn_strides,
        Some((192, 192, 192)),
        "Attention should walk Q/K/V with parent row stride 192"
    );
}

/// Regression: when the QKV→Narrow×3→RoPE×2→Attention→OutProj chain
/// collapses into a single `FusedAttnBlock` (small batch·seq), the fused
/// kernel must honor a **causal** mask. It previously applied only the
/// per-key padding mask and dropped `mask_kind`, so a later token leaked
/// into earlier positions (decoder attention attended to the future).
#[test]
fn fused_attn_block_respects_causal_mask() {
    let f = DType::F32;
    let (s, d, nh, dh) = (5usize, 8usize, 2usize, 4usize);
    let half = dh / 2;

    let mut g = Graph::new("fused_causal");
    let hidden = g.input("hidden", Shape::new(&[s, d], f));
    let wqkv = g.input("wqkv", Shape::new(&[d, 3 * d], f));
    let wo = g.input("wo", Shape::new(&[d, d], f));
    let cos = g.input("cos", Shape::new(&[s, half], f));
    let sin = g.input("sin", Shape::new(&[s, half], f));
    let qkv = g.matmul(hidden, wqkv, Shape::new(&[s, 3 * d], f));
    let q = g.narrow_(qkv, 1, 0, d);
    let k = g.narrow_(qkv, 1, d, d);
    let v = g.narrow_(qkv, 1, 2 * d, d);
    let q3 = g.reshape(q, vec![1, s as i64, d as i64], Shape::new(&[1, s, d], f));
    let k3 = g.reshape(k, vec![1, s as i64, d as i64], Shape::new(&[1, s, d], f));
    let v3 = g.reshape(v, vec![1, s as i64, d as i64], Shape::new(&[1, s, d], f));
    let qr = g.rope(q3, cos, sin, dh);
    let kr = g.rope(k3, cos, sin, dh);
    let attn = g.attention_kind(
        qr,
        kr,
        v3,
        nh,
        dh,
        rlx_ir::op::MaskKind::Causal,
        Shape::new(&[1, s, d], f),
    );
    let a2 = g.reshape(attn, vec![s as i64, d as i64], Shape::new(&[s, d], f));
    let out = g.matmul(a2, wo, Shape::new(&[s, d], f));
    g.set_outputs(vec![out]);

    // The fusion must actually fire AND carry the causal kind.
    let plan = rlx_opt::memory::plan_memory(&g);
    let arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    assert!(
        sched.thunks.iter().any(|t| matches!(
            t,
            Thunk::FusedAttnBlock {
                mask_kind: rlx_ir::op::MaskKind::Causal,
                ..
            }
        )),
        "expected a FusedAttnBlock carrying MaskKind::Causal"
    );

    let wqkv_d: Vec<f32> = (0..d * 3 * d)
        .map(|i| ((i % 7) as f32 - 3.0) * 0.05)
        .collect();
    let wo_d: Vec<f32> = (0..d * d).map(|i| ((i % 5) as f32 - 2.0) * 0.05).collect();
    let mut cos_d = vec![0f32; s * half];
    let mut sin_d = vec![0f32; s * half];
    for p in 0..s {
        for i in 0..half {
            let fr = 1.0f32 / 10000f32.powf(2.0 * i as f32 / dh as f32);
            cos_d[p * half + i] = (p as f32 * fr).cos();
            sin_d[p * half + i] = (p as f32 * fr).sin();
        }
    }
    let base_h: Vec<f32> = (0..s * d).map(|i| ((i % 11) as f32 - 5.0) * 0.1).collect();
    let run = |hin: &[f32]| {
        run_graph(
            &g,
            &[
                (hidden, hin),
                (wqkv, &wqkv_d),
                (wo, &wo_d),
                (cos, &cos_d),
                (sin, &sin_d),
            ],
            out,
            s * d,
        )
    };
    let a = run(&base_h);
    // Perturb only the LAST position's hidden row.
    let mut changed = base_h.clone();
    for j in 0..d {
        changed[4 * d + j] += 1.0;
    }
    let b = run(&changed);
    for pos in 0..4 {
        for j in 0..d {
            let i = pos * d + j;
            assert!(
                (a[i] - b[i]).abs() < 1e-5,
                "causal leak at pos {pos}: {} vs {}",
                a[i],
                b[i]
            );
        }
    }
    let last: f32 = (0..d).map(|j| (a[4 * d + j] - b[4 * d + j]).abs()).sum();
    assert!(last > 1e-4, "last position must react to its own token");
}

// ── Backward / training op parity tests ────────────────────
//
// Strategy: build a graph that contains exactly the backward op
// under test (plus its inputs as graph Inputs), execute, and
// compare against a hand-rolled scalar reference. For
// Conv2dBackwardInput we additionally check against the numerical
// gradient of the forward Conv2D — that's the gold-standard test
// that validates the math, not just consistency between two
// implementations of the same formula.

fn run_graph(g: &Graph, inputs: &[(NodeId, &[f32])], out_id: NodeId, out_len: usize) -> Vec<f32> {
    let plan = rlx_opt::memory::plan_memory(g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(g, &arena);
    for &(id, data) in inputs {
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(off) as *mut f32;
            for (i, &v) in data.iter().enumerate() {
                *p.add(i) = v;
            }
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let off = arena.byte_offset(out_id);
    unsafe {
        let p = arena.raw_buf().as_ptr().add(off) as *const f32;
        (0..out_len).map(|i| *p.add(i)).collect()
    }
}

#[test]
fn relu_backward_matches_mask() {
    let f = DType::F32;
    let len = 7usize;
    let x: Vec<f32> = vec![-2.0, -0.1, 0.0, 0.1, 1.0, 3.0, -5.0];
    let dy: Vec<f32> = vec![0.5, 1.5, 2.5, -0.7, 4.0, -1.0, 9.0];

    let mut g = Graph::new("relu_bw");
    let xn = g.input("x", Shape::new(&[len], f));
    let dyn_ = g.input("dy", Shape::new(&[len], f));
    let dx = g.relu_backward(xn, dyn_);
    g.set_outputs(vec![dx]);

    let actual = run_graph(&g, &[(xn, &x), (dyn_, &dy)], dx, len);
    // Reference: gradient is dy where x>0 strictly, else 0.
    // (zero is not "positive" — the forward applied max(0, x), and at
    // x=0 the subgradient could be anything in [0, dy]; we pick 0.)
    let expected: Vec<f32> = x
        .iter()
        .zip(&dy)
        .map(|(&xi, &dyi)| if xi > 0.0 { dyi } else { 0.0 })
        .collect();
    for (a, e) in actual.iter().zip(&expected) {
        assert!((a - e).abs() < 1e-6, "relu_bw mismatch: {a} vs {e}");
    }
}

#[test]
fn maxpool2d_backward_routes_to_argmax() {
    let f = DType::F32;
    // [N=1, C=1, H=4, W=4] → 2x2 max-pool stride 2 → [1,1,2,2].
    let x: Vec<f32> = vec![
        1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
    ];
    // Argmax of each 2x2 window:
    //   (0,0)→6 (idx 5), (0,1)→8 (idx 7),
    //   (1,0)→14(idx 13),(1,1)→16(idx 15).
    let dy: Vec<f32> = vec![0.5, 1.0, 2.0, 4.0];

    let mut g = Graph::new("maxpool_bw");
    let xn = g.input("x", Shape::new(&[1, 1, 4, 4], f));
    let dyn_ = g.input("dy", Shape::new(&[1, 1, 2, 2], f));
    let dx = g.maxpool2d_backward(xn, dyn_, vec![2, 2], vec![2, 2], vec![0, 0]);
    g.set_outputs(vec![dx]);

    let actual = run_graph(&g, &[(xn, &x), (dyn_, &dy)], dx, 16);
    let mut expected = vec![0f32; 16];
    expected[5] = 0.5;
    expected[7] = 1.0;
    expected[13] = 2.0;
    expected[15] = 4.0;
    for (i, (a, e)) in actual.iter().zip(&expected).enumerate() {
        assert!((a - e).abs() < 1e-6, "maxpool_bw[{i}] mismatch: {a} vs {e}");
    }
}

#[test]
fn conv2d_backward_input_matches_numerical_gradient() {
    use rlx_ir::Philox4x32;
    // Small enough to numerically differentiate exhaustively but
    // big enough to exercise stride/padding edge cases.
    let n = 1usize;
    let c_in = 2usize;
    let h = 4usize;
    let w = 4usize;
    let c_out = 3usize;
    let kh = 3usize;
    let kw = 3usize;
    let ph = 1usize;
    let pw = 1usize;
    let sh = 1usize;
    let sw = 1usize;
    // Output dims with padding=1, stride=1: same as input.
    let h_out = (h + 2 * ph - kh) / sh + 1;
    let w_out = (w + 2 * pw - kw) / sw + 1;
    assert_eq!(h_out, 4);
    assert_eq!(w_out, 4);

    let mut rng = Philox4x32::new(7);
    let mut x = vec![0f32; n * c_in * h * w];
    rng.fill_normal(&mut x);
    let mut wt = vec![0f32; c_out * c_in * kh * kw];
    rng.fill_normal(&mut wt);
    let mut dy = vec![0f32; n * c_out * h_out * w_out];
    rng.fill_normal(&mut dy);

    // Analytical: Conv2dBackwardInput on (dy, w).
    let f = DType::F32;
    let mut g = Graph::new("conv_bwi");
    let dy_in = g.input("dy", Shape::new(&[n, c_out, h_out, w_out], f));
    let w_in = g.input("w", Shape::new(&[c_out, c_in, kh, kw], f));
    let dx = g.conv2d_backward_input(
        dy_in,
        w_in,
        Shape::new(&[n, c_in, h, w], f),
        vec![kh, kw],
        vec![sh, sw],
        vec![ph, pw],
        vec![1, 1],
        1,
    );
    g.set_outputs(vec![dx]);
    let analytical = run_graph(&g, &[(dy_in, &dy), (w_in, &wt)], dx, n * c_in * h * w);

    // Numerical: for each x[i], finite-difference forward conv twice.
    // Forward: y[j] = sum over filter window of w * x ; dot(dy, y) is
    // the scalar we differentiate. Then dx[i] = ∂(dot(dy, y))/∂x[i].
    let forward = |x: &[f32]| -> Vec<f32> {
        let mut out = vec![0f32; n * c_out * h_out * w_out];
        for ni in 0..n {
            for co in 0..c_out {
                for ho in 0..h_out {
                    for wo in 0..w_out {
                        let mut acc = 0f32;
                        for ci in 0..c_in {
                            for ki in 0..kh {
                                for kj in 0..kw {
                                    let hi = ho * sh + ki;
                                    let wi = wo * sw + kj;
                                    if hi < ph || wi < pw {
                                        continue;
                                    }
                                    let hi = hi - ph;
                                    let wi = wi - pw;
                                    if hi >= h || wi >= w {
                                        continue;
                                    }
                                    let xv = x[((ni * c_in) + ci) * h * w + hi * w + wi];
                                    let wv = wt[((co * c_in) + ci) * kh * kw + ki * kw + kj];
                                    acc += xv * wv;
                                }
                            }
                        }
                        out[((ni * c_out) + co) * h_out * w_out + ho * w_out + wo] = acc;
                    }
                }
            }
        }
        out
    };
    let dot = |a: &[f32], b: &[f32]| -> f32 { a.iter().zip(b).map(|(&u, &v)| u * v).sum() };
    let eps = 1e-3f32;
    let mut numerical = vec![0f32; x.len()];
    for i in 0..x.len() {
        let saved = x[i];
        x[i] = saved + eps;
        let plus = dot(&forward(&x), &dy);
        x[i] = saved - eps;
        let minus = dot(&forward(&x), &dy);
        x[i] = saved;
        numerical[i] = (plus - minus) / (2.0 * eps);
    }
    for (i, (a, n)) in analytical.iter().zip(&numerical).enumerate() {
        // f32 + eps=1e-3 numerical grad → ~1e-3 absolute is realistic.
        assert!(
            (a - n).abs() < 5e-3,
            "conv_bw_input[{i}]: analytical {a} vs numerical {n}"
        );
    }
}

#[test]
fn conv2d_backward_weight_matches_numerical_gradient() {
    use rlx_ir::Philox4x32;
    let n = 2usize;
    let c_in = 2usize;
    let h = 4usize;
    let w = 4usize;
    let c_out = 2usize;
    let kh = 3usize;
    let kw = 3usize;
    let ph = 0usize;
    let pw = 0usize;
    let sh = 1usize;
    let sw = 1usize;
    let h_out = (h + 2 * ph - kh) / sh + 1;
    let w_out = (w + 2 * pw - kw) / sw + 1;

    let mut rng = Philox4x32::new(11);
    let mut x = vec![0f32; n * c_in * h * w];
    rng.fill_normal(&mut x);
    let mut wt = vec![0f32; c_out * c_in * kh * kw];
    rng.fill_normal(&mut wt);
    let mut dy = vec![0f32; n * c_out * h_out * w_out];
    rng.fill_normal(&mut dy);

    let f = DType::F32;
    let mut g = Graph::new("conv_bww");
    let xn = g.input("x", Shape::new(&[n, c_in, h, w], f));
    let dyn_ = g.input("dy", Shape::new(&[n, c_out, h_out, w_out], f));
    let dwn = g.conv2d_backward_weight(
        xn,
        dyn_,
        Shape::new(&[c_out, c_in, kh, kw], f),
        vec![kh, kw],
        vec![sh, sw],
        vec![ph, pw],
        vec![1, 1],
        1,
    );
    g.set_outputs(vec![dwn]);
    let analytical = run_graph(&g, &[(xn, &x), (dyn_, &dy)], dwn, c_out * c_in * kh * kw);

    let forward = |wt: &[f32]| -> Vec<f32> {
        let mut out = vec![0f32; n * c_out * h_out * w_out];
        for ni in 0..n {
            for co in 0..c_out {
                for ho in 0..h_out {
                    for wo in 0..w_out {
                        let mut acc = 0f32;
                        for ci in 0..c_in {
                            for ki in 0..kh {
                                for kj in 0..kw {
                                    let hi = ho + ki;
                                    let wi = wo + kj;
                                    let xv = x[((ni * c_in) + ci) * h * w + hi * w + wi];
                                    let wv = wt[((co * c_in) + ci) * kh * kw + ki * kw + kj];
                                    acc += xv * wv;
                                }
                            }
                        }
                        out[((ni * c_out) + co) * h_out * w_out + ho * w_out + wo] = acc;
                    }
                }
            }
        }
        out
    };
    let dot = |a: &[f32], b: &[f32]| -> f32 { a.iter().zip(b).map(|(&u, &v)| u * v).sum() };
    let eps = 1e-3f32;
    let mut numerical = vec![0f32; wt.len()];
    for i in 0..wt.len() {
        let saved = wt[i];
        wt[i] = saved + eps;
        let plus = dot(&forward(&wt), &dy);
        wt[i] = saved - eps;
        let minus = dot(&forward(&wt), &dy);
        wt[i] = saved;
        numerical[i] = (plus - minus) / (2.0 * eps);
    }
    for (i, (a, n)) in analytical.iter().zip(&numerical).enumerate() {
        assert!(
            (a - n).abs() < 5e-3,
            "conv_bw_weight[{i}]: analytical {a} vs numerical {n}"
        );
    }
}

#[test]
fn softmax_cross_entropy_matches_reference() {
    let f = DType::F32;
    let logits: Vec<f32> = vec![
        1.0, 2.0, 3.0, // row 0: max=3 (idx 2)
        -1.0, 0.0, 4.0, // row 1: max=4 (idx 2)
        5.0, 5.0, 5.0, // row 2: uniform
    ];
    let labels: Vec<f32> = vec![2.0, 0.0, 1.0];

    let mut g = Graph::new("sce");
    let lg = g.input("logits", Shape::new(&[3, 3], f));
    let lb = g.input("labels", Shape::new(&[3], f));
    let loss = g.softmax_cross_entropy_with_logits(lg, lb);
    g.set_outputs(vec![loss]);
    let actual = run_graph(&g, &[(lg, &logits), (lb, &labels)], loss, 3);

    // Reference per-row: -log(softmax(row)[label]).
    let mut expected = vec![0f32; 3];
    for ni in 0..3 {
        let row = &logits[ni * 3..(ni + 1) * 3];
        let m = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
        let sum: f32 = row.iter().map(|&v| (v - m).exp()).sum();
        let lse = m + sum.ln();
        let label_idx = labels[ni] as usize;
        expected[ni] = lse - row[label_idx];
    }
    for (i, (a, e)) in actual.iter().zip(&expected).enumerate() {
        assert!((a - e).abs() < 1e-5, "sce loss[{i}]: {a} vs {e}");
    }
}

#[test]
fn softmax_cross_entropy_backward_matches_numerical_gradient() {
    use rlx_ir::Philox4x32;
    let n = 4usize;
    let c = 5usize;
    let mut rng = Philox4x32::new(23);
    let mut logits = vec![0f32; n * c];
    rng.fill_normal(&mut logits);
    let labels: Vec<f32> = (0..n).map(|i| (i % c) as f32).collect();
    let mut d_loss = vec![0f32; n];
    rng.fill_normal(&mut d_loss);

    let f = DType::F32;
    let mut g = Graph::new("sce_bw");
    let lg = g.input("logits", Shape::new(&[n, c], f));
    let lb = g.input("labels", Shape::new(&[n], f));
    let dl = g.input("d_loss", Shape::new(&[n], f));
    let dlogits = g.softmax_cross_entropy_backward(lg, lb, dl);
    g.set_outputs(vec![dlogits]);
    let analytical = run_graph(
        &g,
        &[(lg, &logits), (lb, &labels), (dl, &d_loss)],
        dlogits,
        n * c,
    );

    // Numerical: differentiate dot(d_loss, sce_loss(logits)) w.r.t. each logit.
    let sce_loss = |logits: &[f32]| -> Vec<f32> {
        let mut out = vec![0f32; n];
        for ni in 0..n {
            let row = &logits[ni * c..(ni + 1) * c];
            let m = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
            let sum: f32 = row.iter().map(|&v| (v - m).exp()).sum();
            out[ni] = (m + sum.ln()) - row[labels[ni] as usize];
        }
        out
    };
    let dot = |a: &[f32], b: &[f32]| a.iter().zip(b).map(|(&u, &v)| u * v).sum::<f32>();
    let eps = 1e-3f32;
    let mut numerical = vec![0f32; logits.len()];
    for i in 0..logits.len() {
        let saved = logits[i];
        logits[i] = saved + eps;
        let plus = dot(&sce_loss(&logits), &d_loss);
        logits[i] = saved - eps;
        let minus = dot(&sce_loss(&logits), &d_loss);
        logits[i] = saved;
        numerical[i] = (plus - minus) / (2.0 * eps);
    }
    for (i, (a, num)) in analytical.iter().zip(&numerical).enumerate() {
        assert!(
            (a - num).abs() < 5e-3,
            "sce_bw[{i}]: analytical {a} vs numerical {num}"
        );
    }
}

// ── End-to-end autodiff parity tests ──────────────────────
//
// Build a forward graph, run `grad_with_loss` to produce a graph
// that emits [loss, gradients...], execute it through rlx-cpu,
// and compare each gradient to a finite-difference estimate
// produced by re-running the forward graph with each parameter
// entry perturbed. f32 + ε=1e-3 puts the tolerance floor around
// 5e-3 absolute error.

/// Initialize Op::Constant slots in the arena with their literal
/// data. Mirrors the loop in rlx_runtime::backend (which serves
/// the same role for production runs).
fn fill_constants_into_arena(graph: &Graph, arena: &mut crate::arena::Arena) {
    for node in graph.nodes() {
        if let Op::Constant { data } = &node.op
            && arena.has_buffer(node.id)
            && !data.is_empty()
        {
            let buf = arena.slice_mut(node.id);
            let n_floats = data.len() / 4;
            let n = buf.len().min(n_floats);
            for i in 0..n {
                let bytes = [
                    data[i * 4],
                    data[i * 4 + 1],
                    data[i * 4 + 2],
                    data[i * 4 + 3],
                ];
                buf[i] = f32::from_le_bytes(bytes);
            }
        }
    }
}

/// Compile + arena-prep helper for these tests. Returns the
/// schedule and a populated arena. `seed_inputs` writes f32 input
/// data into the arena slot for each (NodeId, &[f32]) pair.
fn prepare(
    graph: &Graph,
    seed_inputs: &[(NodeId, &[f32])],
) -> (ThunkSchedule, crate::arena::Arena) {
    let plan = rlx_opt::memory::plan_memory(graph);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(graph, &arena);
    fill_constants_into_arena(graph, &mut arena);
    for &(id, data) in seed_inputs {
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(off) as *mut f32;
            for (i, &v) in data.iter().enumerate() {
                *p.add(i) = v;
            }
        }
    }
    (sched, arena)
}

fn read_arena(arena: &crate::arena::Arena, id: NodeId, len: usize) -> Vec<f32> {
    let off = arena.byte_offset(id);
    unsafe {
        let p = arena.raw_buf().as_ptr().add(off) as *const f32;
        (0..len).map(|i| *p.add(i)).collect()
    }
}

fn write_arena(arena: &mut crate::arena::Arena, id: NodeId, data: &[f32]) {
    let off = arena.byte_offset(id);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(off) as *mut f32;
        for (i, &v) in data.iter().enumerate() {
            *p.add(i) = v;
        }
    }
}

/// f64 sibling of `prepare`. Writes f64 input data into the arena.
fn prepare_f64(
    graph: &Graph,
    seed_inputs: &[(NodeId, &[f64])],
) -> (ThunkSchedule, crate::arena::Arena) {
    let plan = rlx_opt::memory::plan_memory(graph);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(graph, &arena);
    fill_constants_into_arena(graph, &mut arena);
    for &(id, data) in seed_inputs {
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(off) as *mut f64;
            for (i, &v) in data.iter().enumerate() {
                *p.add(i) = v;
            }
        }
    }
    (sched, arena)
}

fn read_arena_f64(arena: &crate::arena::Arena, id: NodeId, len: usize) -> Vec<f64> {
    let off = arena.byte_offset(id);
    unsafe {
        let p = arena.raw_buf().as_ptr().add(off) as *const f64;
        (0..len).map(|i| *p.add(i)).collect()
    }
}

/// End-to-end f64 DenseSolve through the full compile + execute
/// path. Validates: IR shape inference, memory planner f64 sizing,
/// arena f64 accessors, Thunk::DenseSolveF64 lowering, executor
/// dispatch, Accelerate dgesv FFI.
///
/// System:
///   A = [[2, 1],
///        [1, 3]]   b = [5, 10]
///   ⇒  x = [1, 3]   (verified by hand)
#[test]
fn dense_solve_f64_end_to_end() {
    let mut g = Graph::new("solve_e2e");
    let a = g.input("A", Shape::new(&[2, 2], DType::F64));
    let b = g.input("b", Shape::new(&[2], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[2], DType::F64));
    g.set_outputs(vec![x]);

    let a_data = [2.0, 1.0, 1.0, 3.0_f64];
    let b_data = [5.0, 10.0_f64];
    let (sched, mut arena) = prepare_f64(&g, &[(a, &a_data), (b, &b_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());

    let got = read_arena_f64(&arena, x, 2);
    let want = [1.0, 3.0_f64];
    for i in 0..2 {
        assert!(
            (got[i] - want[i]).abs() < 1e-12,
            "x[{i}] = {} (expected {})",
            got[i],
            want[i]
        );
    }
}

/// Scaled-up f64 DenseSolve — tridiagonal Laplacian-shape (typical
/// MNA structure for a passive RC mesh in Circulax). Validates
/// that the solve scales beyond the trivial 2×2 and that the
/// row-major ↔ col-major dance in `dgesv` is correct for the
/// general case.
#[test]
fn dense_solve_f64_5x5_laplacian() {
    let n = 5usize;
    let mut g = Graph::new("solve_5x5");
    let a = g.input("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("b", Shape::new(&[n], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n], DType::F64));
    g.set_outputs(vec![x]);

    // 1-D Laplacian: 2 on diagonal, -1 on off-diagonals, 0 elsewhere.
    let mut a_data = vec![0.0_f64; n * n];
    for i in 0..n {
        a_data[i * n + i] = 2.0;
        if i > 0 {
            a_data[i * n + (i - 1)] = -1.0;
        }
        if i + 1 < n {
            a_data[i * n + (i + 1)] = -1.0;
        }
    }
    let b_data: Vec<f64> = (0..n).map(|i| (i + 1) as f64).collect();
    let (sched, mut arena) = prepare_f64(&g, &[(a, &a_data), (b, &b_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());

    let got = read_arena_f64(&arena, x, n);
    // Verify A·x ≈ b by computing the residual.
    let mut residual = vec![0.0_f64; n];
    for i in 0..n {
        for j in 0..n {
            residual[i] += a_data[i * n + j] * got[j];
        }
    }
    for i in 0..n {
        assert!(
            (residual[i] - b_data[i]).abs() < 1e-10,
            "row {i}: residual {} vs b {}",
            residual[i],
            b_data[i]
        );
    }
}

/// Hello Resistor: end-to-end f64 gradient through a dense solve.
///
/// Forward:
///   A      : Param  [N, N]   f64
///   b      : Input  [N]      f64
///   x      = solve(A, b)            (DenseSolve)
///   loss   = sum(x)                 (Reduce::Sum)
///
/// Backward (via grad_with_loss):
///   ones [N] = expand(d_output, [N])      (Reduce::Sum VJP)
///   dx_int   = solve(Aᵀ, ones)             (DenseSolve VJP step 1)
///   dA       = -outer(dx_int, x)           (DenseSolve VJP step 2)
///   db       = dx_int                       (DenseSolve VJP step 3)
///
/// Closed form: with loss = sum(solve(A, b)) = ones·x and
/// implicit-function calculus, db = (Aᵀ)⁻¹·ones, dA = -db ⊗ x.
/// We verify this against the autodiff-emitted graph's output and
/// against a finite-difference baseline.
#[test]
fn hello_resistor_gradient_end_to_end() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 3usize;

    // ── Build forward graph ──
    let mut g = Graph::new("hello_resistor");
    let a = g.param("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("b", Shape::new(&[n], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n], DType::F64));
    let loss = g.reduce(
        x,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    // ── Run reverse-mode AD ──
    let bwd = grad_with_loss(&g, &[a, b]);
    assert_eq!(bwd.outputs.len(), 3, "expect [loss, dA, db]");

    // ── Locate the inputs the bwd graph still needs from us ──
    // grad_with_loss copies forward nodes into bwd, so A/b/d_output
    // appear under their original names. Find them by name.
    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                rlx_ir::Op::Input { name } => Some(name.as_str()),
                rlx_ir::Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?} in bwd graph");
    };
    let a_bwd = find_by_name(&bwd, "A");
    let b_bwd = find_by_name(&bwd, "b");
    let d_out_bwd = find_by_name(&bwd, "d_output");

    // ── Test data ──
    // A = [[2,1,0],[1,3,1],[0,1,2]]   (SPD tridiagonal, well-conditioned)
    // b = [1,2,3]
    let a_data = [2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 2.0_f64];
    let b_data = [1.0, 2.0, 3.0_f64];
    let d_output = [1.0_f64]; // ∂loss/∂loss

    // ── Compile + execute backward graph ──
    let (sched, mut arena) = prepare_f64(
        &bwd,
        &[(a_bwd, &a_data), (b_bwd, &b_data), (d_out_bwd, &d_output)],
    );
    execute_thunks(&sched, arena.raw_buf_mut());

    let loss_out = read_arena_f64(&arena, bwd.outputs[0], 1);
    let da_out = read_arena_f64(&arena, bwd.outputs[1], n * n);
    let db_out = read_arena_f64(&arena, bwd.outputs[2], n);

    // ── Closed-form reference ──
    // x = A⁻¹ b ; loss = sum(x).
    let x_ref = {
        let mut a = a_data;
        let mut b = b_data;
        let info = crate::blas::dgesv(&mut a, &mut b, n, 1);
        assert_eq!(info, 0);
        b
    };
    let loss_ref: f64 = x_ref.iter().sum();
    // db = (Aᵀ)⁻¹ · 1
    let db_ref = {
        let mut at = [0.0_f64; 9];
        for i in 0..n {
            for j in 0..n {
                at[i * n + j] = a_data[j * n + i];
            }
        }
        let mut ones = [1.0_f64; 3];
        let info = crate::blas::dgesv(&mut at, &mut ones, n, 1);
        assert_eq!(info, 0);
        ones
    };
    // dA = -outer(db, x) ; dA[i,j] = -db[i] * x[j]
    let mut da_ref = [0.0_f64; 9];
    for i in 0..n {
        for j in 0..n {
            da_ref[i * n + j] = -db_ref[i] * x_ref[j];
        }
    }

    // ── Assertions vs analytic answer ──
    assert!(
        (loss_out[0] - loss_ref).abs() < 1e-10,
        "loss: got {}, want {}",
        loss_out[0],
        loss_ref
    );
    for i in 0..n {
        assert!(
            (db_out[i] - db_ref[i]).abs() < 1e-10,
            "db[{i}]: got {}, want {}",
            db_out[i],
            db_ref[i]
        );
    }
    for i in 0..n * n {
        assert!(
            (da_out[i] - da_ref[i]).abs() < 1e-10,
            "dA[{i}]: got {}, want {}",
            da_out[i],
            da_ref[i]
        );
    }

    // ── Cross-check vs finite differences on db (a few entries) ──
    // ∂loss/∂b[k] ≈ (loss(b + h·e_k) - loss(b - h·e_k)) / (2h).
    let h = 1e-6_f64;
    for k in 0..n {
        let mut bp = b_data;
        bp[k] += h;
        let mut bm = b_data;
        bm[k] -= h;
        let lp = {
            let mut ac = a_data;
            let info = crate::blas::dgesv(&mut ac, &mut bp, n, 1);
            assert_eq!(info, 0);
            bp.iter().sum::<f64>()
        };
        let lm = {
            let mut ac = a_data;
            let info = crate::blas::dgesv(&mut ac, &mut bm, n, 1);
            assert_eq!(info, 0);
            bm.iter().sum::<f64>()
        };
        let fd = (lp - lm) / (2.0 * h);
        assert!(
            (db_out[k] - fd).abs() < 1e-7,
            "FD mismatch on db[{k}]: AD={} FD={}",
            db_out[k],
            fd
        );
    }
}

/// Smallest possible Op::Scan basic test: geometric growth.
/// init = [1, 1, 1] f64, body = (x → x + 0.1·x) = (x → 1.1·x),
/// length = 10. Final carry must equal init·(1.1)^10 ≈ 2.5937…
/// to f64 precision.
#[test]
fn scan_geometric_growth_f64() {
    let n = 3usize;
    let length = 10u32;

    // Body: (x) → x + 0.1·x. One Input, one output, same shape/dtype.
    let mut body = Graph::new("scan_body");
    let x = body.input("carry", Shape::new(&[n], DType::F64));
    let scale_bytes: Vec<u8> = (0..n).flat_map(|_| 0.1_f64.to_le_bytes()).collect();
    let scale = body.add_node(
        Op::Constant { data: scale_bytes },
        vec![],
        Shape::new(&[n], DType::F64),
    );
    let scaled = body.binary(BinaryOp::Mul, x, scale, Shape::new(&[n], DType::F64));
    let next = body.binary(BinaryOp::Add, x, scaled, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    // Outer graph: scan(init, body, length).
    let mut g = Graph::new("scan_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let final_carry = g.scan(init, body, length);
    g.set_outputs(vec![final_carry]);

    let init_data = vec![1.0_f64; n];
    let (sched, mut arena) = prepare_f64(&g, &[(init, &init_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let got = read_arena_f64(&arena, final_carry, n);
    let want: f64 = 1.1_f64.powi(length as i32);
    for i in 0..n {
        assert!(
            (got[i] - want).abs() < 1e-12,
            "got[{i}] = {} want {}",
            got[i],
            want
        );
    }
}

/// Per-step xs scan: cumulative-sum.
///   carry_0 = init
///   carry_{t+1} = carry_t + xs\[t\]
///   final = sum_{t<length} xs\[t\] + init
/// Body has 2 inputs (carry, x_t) in that NodeId order; one output
/// (next carry). Validates the per-step-input plumbing end-to-end.
#[test]
fn scan_with_xs_cumulative_sum() {
    let n = 3usize;
    let length = 4u32;

    let mut body = Graph::new("cumsum_body");
    // carry must come first in NodeId order — declare it first.
    let carry = body.input("carry", Shape::new(&[n], DType::F64));
    let x_t = body.input("x_t", Shape::new(&[n], DType::F64));
    let next = body.binary(BinaryOp::Add, carry, x_t, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("cumsum_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let xs = g.input("xs", Shape::new(&[length as usize, n], DType::F64));
    let final_carry = g.scan_with_xs(init, &[xs], body, length);
    g.set_outputs(vec![final_carry]);

    let init_data = vec![0.0_f64; n];
    let xs_data: Vec<f64> = (0..length as usize * n).map(|i| (i + 1) as f64).collect(); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
    let (sched, mut arena) = prepare_f64(&g, &[(init, &init_data), (xs, &xs_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let got = read_arena_f64(&arena, final_carry, n);

    // Reference: column-wise sum of xs rows + init. With our row-major
    // layout, column j of xs is xs_data[j], xs_data[n+j], xs_data[2n+j], ...
    // (per-step row at offset t*n contributes element j to slot j).
    let mut want = init_data.clone();
    for t in 0..length as usize {
        for j in 0..n {
            want[j] += xs_data[t * n + j];
        }
    }
    for i in 0..n {
        assert!(
            (got[i] - want[i]).abs() < 1e-12,
            "got[{i}] = {} want {}",
            got[i],
            want[i]
        );
    }
}

/// Per-step xs scan composing with DenseSolve — Circulax-shaped:
///   carry_{t+1} = solve(M, carry_t + xs\[t\])
/// Models a Backward-Euler step driven by a time-varying source.
#[test]
fn scan_with_xs_be_with_drive() {
    let n = 3usize;
    let length = 4u32;
    let dt = 0.1_f64;

    let mut m_data = vec![0.0_f64; n * n];
    for i in 0..n {
        m_data[i * n + i] = 1.0 + dt * 2.0;
        if i > 0 {
            m_data[i * n + (i - 1)] = -dt;
        }
        if i + 1 < n {
            m_data[i * n + (i + 1)] = -dt;
        }
    }
    let m_bytes: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();

    let mut body = Graph::new("be_drive_body");
    let carry = body.input("carry", Shape::new(&[n], DType::F64));
    let drive = body.input("drive", Shape::new(&[n], DType::F64));
    let m = body.add_node(
        Op::Constant { data: m_bytes },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let driven = body.binary(BinaryOp::Add, carry, drive, Shape::new(&[n], DType::F64));
    let next = body.dense_solve(m, driven, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("be_drive_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let xs = g.input("xs", Shape::new(&[length as usize, n], DType::F64));
    let final_carry = g.scan_with_xs(init, &[xs], body, length);
    g.set_outputs(vec![final_carry]);

    let init_data = vec![0.0_f64; n];
    // Drive the system with a unit pulse on element 0 at t=0,
    // zeros after.
    let mut xs_data = vec![0.0_f64; length as usize * n];
    xs_data[0] = 1.0;

    let (sched, mut arena) = prepare_f64(&g, &[(init, &init_data), (xs, &xs_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let got = read_arena_f64(&arena, final_carry, n);

    // Reference: per-step in pure Rust.
    let mut x = init_data.clone();
    for t in 0..length as usize {
        for j in 0..n {
            x[j] += xs_data[t * n + j];
        }
        let mut a_copy = m_data.clone();
        crate::blas::dgesv(&mut a_copy, &mut x, n, 1);
    }
    for i in 0..n {
        assert!(
            (got[i] - x[i]).abs() < 1e-12,
            "got[{i}] = {} ref {}",
            got[i],
            x[i]
        );
    }
}

/// Reverse-mode AD through Op::BatchedDenseSolve. Forward solves
/// `[B, N, N] · x = [B, N]`; loss = sum of all entries. Closed
/// form: dB = (Aᵀ)⁻¹·1, dA = -(Aᵀ)⁻¹·1 ⊗ x. Verified analytically
/// per batch (each slice matches what the unbatched DenseSolve VJP
/// would compute).
#[test]
fn batched_dense_solve_gradient_matches_per_batch_analytic() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 3usize;
    let batch = 4usize;

    let mut g = Graph::new("bds_grad");
    let a = g.param("A", Shape::new(&[batch, n, n], DType::F64));
    let b = g.input("b", Shape::new(&[batch, n], DType::F64));
    let x = g.batched_dense_solve(a, b, Shape::new(&[batch, n], DType::F64));
    let loss = g.reduce(
        x,
        ReduceOp::Sum,
        vec![0, 1],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    let bwd = grad_with_loss(&g, &[a, b]);

    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want}");
    };
    let a_id = find(&bwd, "A");
    let b_id = find(&bwd, "b");
    let d_out_id = find(&bwd, "d_output");

    let mut rng = rlx_ir::Philox4x32::new(0x57e1_u64);
    let mut a_data = vec![0.0_f64; batch * n * n];
    let mut b_data = vec![0.0_f64; batch * n];
    for bi in 0..batch {
        for i in 0..n {
            for j in 0..n {
                a_data[bi * n * n + i * n + j] = rng.next_f32() as f64 * 0.1;
            }
            a_data[bi * n * n + i * n + i] += 1.0 + n as f64;
        }
        for i in 0..n {
            b_data[bi * n + i] = rng.next_f32() as f64;
        }
    }
    let d_seed = [1.0_f64];

    let (sched, mut arena) = prepare_f64(
        &bwd,
        &[(a_id, &a_data), (b_id, &b_data), (d_out_id, &d_seed)],
    );
    execute_thunks(&sched, arena.raw_buf_mut());
    let da_out = read_arena_f64(&arena, bwd.outputs[1], batch * n * n);
    let db_out = read_arena_f64(&arena, bwd.outputs[2], batch * n);

    // Reference: per-batch analytic solve. dB_i = (A_iᵀ)⁻¹ · 1,
    // dA_i = -dB_i ⊗ x_i.
    for bi in 0..batch {
        let a_slice: Vec<f64> = a_data[bi * n * n..(bi + 1) * n * n].to_vec();
        let mut b_slice: Vec<f64> = b_data[bi * n..(bi + 1) * n].to_vec();
        let mut a_copy = a_slice.clone();
        crate::blas::dgesv(&mut a_copy, &mut b_slice, n, 1);
        let x_ref = b_slice.clone();
        // dB: solve(A^T, ones)
        let mut at = vec![0.0_f64; n * n];
        for i in 0..n {
            for j in 0..n {
                at[i * n + j] = a_slice[j * n + i];
            }
        }
        let mut ones = vec![1.0_f64; n];
        crate::blas::dgesv(&mut at, &mut ones, n, 1);
        let db_ref = ones;
        for i in 0..n {
            let got = db_out[bi * n + i];
            assert!(
                (got - db_ref[i]).abs() < 1e-10,
                "batch {bi}, db[{i}]: got {got} ref {}",
                db_ref[i]
            );
        }
        // dA: -outer(db, x)
        for i in 0..n {
            for j in 0..n {
                let got = da_out[bi * n * n + i * n + j];
                let want = -db_ref[i] * x_ref[j];
                assert!(
                    (got - want).abs() < 1e-10,
                    "batch {bi}, dA[{i},{j}]: got {got} ref {want}"
                );
            }
        }
    }
}

/// AD knob: gradient through `scan_checkpointed` automatically
/// uses the recompute backward path. Compares dinit from a plain
/// scan against the same forward written with `scan_checkpointed`,
/// both run through `grad_with_loss`. They must match to f64.
#[test]
fn scan_checkpointed_grad_matches_plain_scan_grad() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 2usize;
    let length = 6u32;

    let make_body = || {
        let mut body = Graph::new("ck_body");
        let carry = body.input("carry", Shape::new(&[n], DType::F64));
        let scale_bytes: Vec<u8> = (0..n).flat_map(|_| 1.05_f64.to_le_bytes()).collect();
        let scale = body.add_node(
            Op::Constant { data: scale_bytes },
            vec![],
            Shape::new(&[n], DType::F64),
        );
        let next = body.binary(BinaryOp::Mul, carry, scale, Shape::new(&[n], DType::F64));
        body.set_outputs(vec![next]);
        body
    };

    // Plain scan path.
    let mut g_plain = Graph::new("ck_plain");
    let init_p = g_plain.input("init", Shape::new(&[n], DType::F64));
    let final_p = g_plain.scan(init_p, make_body(), length);
    let loss_p = g_plain.reduce(
        final_p,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g_plain.set_outputs(vec![loss_p]);
    let bwd_p = grad_with_loss(&g_plain, &[init_p]);

    // Checkpointed scan path with K=2 (length=6).
    let mut g_ck = Graph::new("ck_ckpt");
    let init_c = g_ck.input("init", Shape::new(&[n], DType::F64));
    let final_c = g_ck.scan_checkpointed(init_c, make_body(), length, 2);
    let loss_c = g_ck.reduce(
        final_c,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g_ck.set_outputs(vec![loss_c]);
    let bwd_c = grad_with_loss(&g_ck, &[init_c]);

    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no {want}");
    };

    let init_data = vec![0.5_f64, -0.5];
    let d_seed = [1.0_f64];

    let (s_p, mut a_p) = prepare_f64(
        &bwd_p,
        &[
            (find(&bwd_p, "init"), &init_data),
            (find(&bwd_p, "d_output"), &d_seed),
        ],
    );
    execute_thunks(&s_p, a_p.raw_buf_mut());
    let dinit_p = read_arena_f64(&a_p, bwd_p.outputs[1], n);

    let (s_c, mut a_c) = prepare_f64(
        &bwd_c,
        &[
            (find(&bwd_c, "init"), &init_data),
            (find(&bwd_c, "d_output"), &d_seed),
        ],
    );
    execute_thunks(&s_c, a_c.raw_buf_mut());
    let dinit_c = read_arena_f64(&a_c, bwd_c.outputs[1], n);

    for i in 0..n {
        assert!(
            (dinit_p[i] - dinit_c[i]).abs() < 1e-12,
            "dinit[{i}]: plain={} checkpointed={}",
            dinit_p[i],
            dinit_c[i]
        );
    }
}

/// Recursive checkpointing end-to-end: build a ScanBackward
/// configured with K=2 checkpoints (for length=4), and compare
/// dinit against the same backward graph with full trajectory
/// (K=0). Forward computes a cumulative-sum-style scan; loss = sum.
/// Both paths must agree to f64 precision.
#[test]
fn recursive_checkpointing_matches_full_trajectory() {
    let n = 2usize;
    let length = 4u32;

    // Body: carry + ones (deterministic, no xs)
    let build_body = || -> Graph {
        let mut body = Graph::new("rc_body");
        let carry = body.input("carry", Shape::new(&[n], DType::F64));
        let ones_bytes: Vec<u8> = (0..n).flat_map(|_| 1.0_f64.to_le_bytes()).collect();
        let ones = body.add_node(
            Op::Constant { data: ones_bytes },
            vec![],
            Shape::new(&[n], DType::F64),
        );
        let next = body.binary(BinaryOp::Add, carry, ones, Shape::new(&[n], DType::F64));
        body.set_outputs(vec![next]);
        body
    };

    // body_vjp: same body + d_output, output dcarry. body_vjp is
    // used by ScanBackward to walk the chain rule per step.
    let body_vjp_for = || -> Graph {
        use rlx_opt::autodiff::grad;
        let body = build_body();
        // grad(body, [carry_id]) → graph with dcarry as the output.
        let carry_id = body
            .nodes()
            .iter()
            .find(|n| matches!(n.op, Op::Input { .. }))
            .map(|n| n.id)
            .unwrap();
        grad(&body, &[carry_id])
    };

    // ── Forward (All-strategy): scan with full trajectory ──
    let mut g_full = Graph::new("rc_outer_full");
    let init_full = g_full.input("init", Shape::new(&[n], DType::F64));
    let traj_full_id = g_full.scan_trajectory(init_full, build_body(), length);
    // Hand-build a ScanBackward node that reads the full trajectory.
    let upstream_full = g_full.input("upstream", Shape::new(&[length as usize, n], DType::F64));
    let dinit_full_id = g_full.scan_backward(
        init_full,
        traj_full_id,
        upstream_full,
        &[],
        body_vjp_for(),
        length,
        true,
        Shape::new(&[n], DType::F64),
    );
    g_full.set_outputs(vec![dinit_full_id]);

    // ── Forward (Recursive-2): scan saves only K=2 rows ──
    // Build the trajectory shape [K, *carry] = [2, 2].
    let k = 2u32;
    let mut g_rec = Graph::new("rc_outer_rec");
    let init_rec = g_rec.input("init", Shape::new(&[n], DType::F64));
    let traj_rec_id = g_rec.add_node(
        Op::Scan {
            body: Box::new(build_body()),
            length,
            save_trajectory: true,
            num_bcast: 0,
            num_xs: 0,
            num_checkpoints: k,
        },
        vec![init_rec],
        Shape::new(&[k as usize, n], DType::F64),
    );
    // Same upstream shape as the full version (the upstream is per
    // *forward step*, length rows — independent of K).
    let upstream_rec = g_rec.input("upstream", Shape::new(&[length as usize, n], DType::F64));
    let dinit_rec_id = g_rec.add_node(
        Op::ScanBackward {
            body_vjp: Box::new(body_vjp_for()),
            length,
            save_trajectory: true,
            num_xs: 0,
            num_checkpoints: k,
            forward_body: Some(Box::new(build_body())),
        },
        vec![init_rec, traj_rec_id, upstream_rec],
        Shape::new(&[n], DType::F64),
    );
    g_rec.set_outputs(vec![dinit_rec_id]);

    // ── Run both, same inputs ──
    let init_data = vec![0.5_f64, -0.5];
    let upstream_data: Vec<f64> = (0..length as usize * n).map(|i| (i as f64) * 0.1).collect();

    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            if let Op::Input { name } = &node.op
                && name == want
            {
                return node.id;
            }
        }
        panic!("no input {want}");
    };

    let (s_full, mut a_full) = prepare_f64(
        &g_full,
        &[
            (find(&g_full, "init"), &init_data),
            (find(&g_full, "upstream"), &upstream_data),
        ],
    );
    execute_thunks(&s_full, a_full.raw_buf_mut());
    let dinit_full = read_arena_f64(&a_full, g_full.outputs[0], n);

    let (s_rec, mut a_rec) = prepare_f64(
        &g_rec,
        &[
            (find(&g_rec, "init"), &init_data),
            (find(&g_rec, "upstream"), &upstream_data),
        ],
    );
    execute_thunks(&s_rec, a_rec.raw_buf_mut());
    let dinit_rec = read_arena_f64(&a_rec, g_rec.outputs[0], n);

    for i in 0..n {
        assert!(
            (dinit_full[i] - dinit_rec[i]).abs() < 1e-12,
            "i={i}: full={} rec={}",
            dinit_full[i],
            dinit_rec[i]
        );
    }
}

/// vmap-of-grad: gradient through Scan, vmap'd over init.
/// Forward (per row):
///   carry_{t+1} = carry_t + ones    (body adds a constant)
///   loss = sum(carry_length) = sum(init) + length·n
/// Closed form: dloss/dinit_i = 1 for every i. vmap over init at
/// batch=3 → dinit_batched is all-ones [3, n]. Cross-checks
/// against per-row grad_with_loss runs. Validates the vmap rule
/// for Op::ScanBackward.
#[test]
fn vmap_of_grad_scan_matches_per_row_runs() {
    use rlx_opt::autodiff::grad_with_loss;
    use rlx_opt::vmap::vmap;
    let n = 2usize;
    let length = 3u32;
    let batch = 3usize;

    let mut body = Graph::new("scan_grad_body");
    let carry = body.input("carry", Shape::new(&[n], DType::F64));
    let ones_bytes: Vec<u8> = (0..n).flat_map(|_| 1.0_f64.to_le_bytes()).collect();
    let ones = body.add_node(
        Op::Constant { data: ones_bytes },
        vec![],
        Shape::new(&[n], DType::F64),
    );
    let next = body.binary(BinaryOp::Add, carry, ones, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("scan_grad_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let final_x = g.scan(init, body, length);
    let loss = g.reduce(
        final_x,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    let bwd = grad_with_loss(&g, &[init]);
    let bg = vmap(&bwd, &["init"], batch);

    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want}");
    };
    let init_b = find(&bg, "init");
    let d_out_b = find(&bg, "d_output");

    let init_data: Vec<f64> = (0..batch * n).map(|i| (i as f64) * 0.5).collect();
    let d_seed = [1.0_f64];

    let (sched, mut arena) = prepare_f64(&bg, &[(init_b, &init_data), (d_out_b, &d_seed)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let dinit_b = read_arena_f64(&arena, bg.outputs[1], batch * n);

    for i in 0..batch * n {
        assert!(
            (dinit_b[i] - 1.0).abs() < 1e-12,
            "dinit[{i}] = {} (expected 1.0)",
            dinit_b[i]
        );
    }

    // Cross-check vs per-row grad_with_loss.
    for bi in 0..batch {
        let row = &init_data[bi * n..(bi + 1) * n];
        let mut g2 = Graph::new("per_row_grad");
        let init2 = g2.input("init", Shape::new(&[n], DType::F64));
        let mut body2 = Graph::new("per_row_body");
        let c2 = body2.input("carry", Shape::new(&[n], DType::F64));
        let ones2_bytes: Vec<u8> = (0..n).flat_map(|_| 1.0_f64.to_le_bytes()).collect();
        let ones2 = body2.add_node(
            Op::Constant { data: ones2_bytes },
            vec![],
            Shape::new(&[n], DType::F64),
        );
        let next2 = body2.binary(BinaryOp::Add, c2, ones2, Shape::new(&[n], DType::F64));
        body2.set_outputs(vec![next2]);
        let final2 = g2.scan(init2, body2, length);
        let loss2 = g2.reduce(
            final2,
            ReduceOp::Sum,
            vec![0],
            false,
            Shape::new(&[1], DType::F64),
        );
        g2.set_outputs(vec![loss2]);
        let bwd2 = grad_with_loss(&g2, &[init2]);
        let init2_id = find(&bwd2, "init");
        let d_out2_id = find(&bwd2, "d_output");
        let (s2, mut a2) = prepare_f64(&bwd2, &[(init2_id, row), (d_out2_id, &d_seed)]);
        execute_thunks(&s2, a2.raw_buf_mut());
        let row_dinit = read_arena_f64(&a2, bwd2.outputs[1], n);
        for j in 0..n {
            let got = dinit_b[bi * n + j];
            let want = row_dinit[j];
            assert!(
                (got - want).abs() < 1e-12,
                "row {bi}, j {j}: vmap'd={got} per-row={want}"
            );
        }
    }
}

/// vmap of Op::Scan: batched cumulative-sum. Forward
///   carry_{t+1} = carry_t + xs\[t\]
///   final = init + sum(xs)
/// vmap over both init and xs at batch=3. Each batch row should
/// equal the scalar run of the same body+xs subset.
#[test]
fn vmap_scan_cumulative_sum_matches_scalar_runs() {
    use rlx_opt::vmap::vmap;
    let n = 2usize;
    let length = 4u32;
    let batch = 3usize;

    // Body: (carry, x_t) → carry + x_t
    let mut body = Graph::new("scan_body_cumsum");
    let carry = body.input("carry", Shape::new(&[n], DType::F64));
    let x_t = body.input("x_t", Shape::new(&[n], DType::F64));
    let next = body.binary(BinaryOp::Add, carry, x_t, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("scan_outer_cumsum");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let xs = g.input("xs", Shape::new(&[length as usize, n], DType::F64));
    let final_carry = g.scan_with_xs(init, &[xs], body, length);
    g.set_outputs(vec![final_carry]);

    // vmap over both init and xs.
    let bg = vmap(&g, &["init", "xs"], batch);

    // Test data — distinct per-batch rows.
    let init_data: Vec<f64> = (0..batch * n).map(|i| (i + 1) as f64).collect();
    // xs has shape [B, length, n] after vmap (the outer's xs is
    // [length, n]; vmap lifts it to [B, length, n]).
    let xs_data: Vec<f64> = (0..batch * length as usize * n)
        .map(|i| 0.1 * (i as f64))
        .collect();

    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            if let Op::Input { name } = &node.op
                && name == want
            {
                return node.id;
            }
        }
        panic!("no input {want}");
    };
    let init_b = find(&bg, "init");
    let xs_b = find(&bg, "xs");
    let (sched, mut arena) = prepare_f64(&bg, &[(init_b, &init_data), (xs_b, &xs_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let batched_out = read_arena_f64(&arena, bg.outputs[0], batch * n);

    // Reference: per-batch scalar Scan.
    for bi in 0..batch {
        let init_slice = &init_data[bi * n..(bi + 1) * n];
        let mut x = init_slice.to_vec();
        for t in 0..length as usize {
            for j in 0..n {
                x[j] += xs_data[bi * length as usize * n + t * n + j];
            }
        }

        for i in 0..n {
            let got = batched_out[bi * n + i];
            assert!(
                (got - x[i]).abs() < 1e-12,
                "row {bi}, i {i}: got {got} ref {}",
                x[i]
            );
        }
    }
}

/// vmap of dense solve — Circulax-shaped batched parameter sweep.
/// Forward: x = solve(A, b). vmap over both A (batched [B,N,N])
/// and b (batched [B,N]). Run on CPU and compare each batch row
/// against an independent scalar dgesv.
#[test]
fn vmap_dense_solve_matches_scalar_runs() {
    use rlx_opt::vmap::vmap;
    let n = 3usize;
    let batch = 4usize;

    let mut g = Graph::new("solve_forward");
    let a = g.input("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("b", Shape::new(&[n], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n], DType::F64));
    g.set_outputs(vec![x]);

    // vmap both A and b across the batch.
    let bg = vmap(&g, &["A", "b"], batch);

    // Independent A and b per batch row.
    let mut rng = rlx_ir::Philox4x32::new(0xb47c_u64);
    let mut a_data = vec![0.0_f64; batch * n * n];
    let mut b_data = vec![0.0_f64; batch * n];
    for bi in 0..batch {
        // Diagonally dominant A — guaranteed non-singular.
        for i in 0..n {
            for j in 0..n {
                a_data[bi * n * n + i * n + j] = rng.next_f32() as f64 * 0.1;
            }
            a_data[bi * n * n + i * n + i] += 1.0 + n as f64;
        }
        for i in 0..n {
            b_data[bi * n + i] = rng.next_f32() as f64;
        }
    }

    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            if let Op::Input { name } = &node.op
                && name == want
            {
                return node.id;
            }
        }
        panic!("no input named {want}");
    };
    let ba = find(&bg, "A");
    let bb = find(&bg, "b");
    let (sched, mut arena) = prepare_f64(&bg, &[(ba, &a_data), (bb, &b_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let batched_x = read_arena_f64(&arena, bg.outputs[0], batch * n);

    // Reference: per-batch dgesv.
    for bi in 0..batch {
        let mut a_slice: Vec<f64> = a_data[bi * n * n..(bi + 1) * n * n].to_vec();
        let mut b_slice: Vec<f64> = b_data[bi * n..(bi + 1) * n].to_vec();
        crate::blas::dgesv(&mut a_slice, &mut b_slice, n, 1);
        for i in 0..n {
            let got = batched_x[bi * n + i];
            let want = b_slice[i];
            assert!(
                (got - want).abs() < 1e-12,
                "row {bi}, i {i}: got {got} want {want}"
            );
        }
    }
}

/// vmap end-to-end: build a graph that computes y = MatMul(x, w) + b
/// and reduces to a per-element loss. vmap over x with batch=4.
/// Run the batched graph and compare each output row against an
/// independent scalar run of the original graph. Validates the
/// structural lift + the runtime path for batched MatMul +
/// batched Binary + batched Reduce.
#[test]
fn vmap_matmul_add_reduce_matches_scalar_runs() {
    use rlx_opt::vmap::vmap;
    let n = 3usize;
    let batch = 4usize;

    // Forward graph: y = MatMul(reshape(x, [1,n]), w) + b ; loss = sum(y).
    let mut g = Graph::new("vmap_e2e_forward");
    let x = g.input("x", Shape::new(&[n], DType::F64));
    let w = g.input("w", Shape::new(&[n, n], DType::F64));
    let b = g.input("b", Shape::new(&[n], DType::F64));
    let x_row = g.add_node(
        Op::Reshape {
            new_shape: vec![1, n as i64],
        },
        vec![x],
        Shape::new(&[1, n], DType::F64),
    );
    let mm = g.matmul(x_row, w, Shape::new(&[1, n], DType::F64));
    let mm_flat = g.add_node(
        Op::Reshape {
            new_shape: vec![n as i64],
        },
        vec![mm],
        Shape::new(&[n], DType::F64),
    );
    let yv = g.binary(BinaryOp::Add, mm_flat, b, Shape::new(&[n], DType::F64));
    let loss = g.reduce(
        yv,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    // Build the vmap'd version (batch over x; w and b shared).
    let bg = vmap(&g, &["x"], batch);

    // Test data — distinct rows so we can verify the per-row dispatch.
    let mut rng = rlx_ir::Philox4x32::new(0xc1c0_u64);
    let n_w = n * n;
    let w_data: Vec<f64> = (0..n_w).map(|_| rng.next_f32() as f64).collect();
    let b_data: Vec<f64> = (0..n).map(|_| rng.next_f32() as f64).collect();
    let mut x_data_batched: Vec<f64> = Vec::with_capacity(batch * n);
    for _ in 0..batch * n {
        x_data_batched.push(rng.next_f32() as f64);
    }

    // Run the batched graph.
    let find = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            if let Op::Input { name } = &node.op
                && name == want
            {
                return node.id;
            }
        }
        panic!("no input named {want}");
    };
    let bx = find(&bg, "x");
    let bw = find(&bg, "w");
    let bb = find(&bg, "b");
    let (sched, mut arena) =
        prepare_f64(&bg, &[(bx, &x_data_batched), (bw, &w_data), (bb, &b_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    // Reduce::Sum on shifted axis 1 with keep_dim=false → output [B, 1]
    // (it preserves the leading batch axis but reduces what was [n] to [].
    // Since the original output was [1] f64 and the reduce was over
    // axis 0, after vmap the leading-axis-shifted reduce keeps the
    // leading 1 from the original output's [1] shape.)
    let batched_out = read_arena_f64(&arena, bg.outputs[0], batch);

    // Reference: run the original (un-batched) graph once per batch row.
    for bi in 0..batch {
        let xs_slice = &x_data_batched[bi * n..(bi + 1) * n];
        let mut g2 = Graph::new("scalar_run");
        let x2 = g2.input("x", Shape::new(&[n], DType::F64));
        let w2 = g2.input("w", Shape::new(&[n, n], DType::F64));
        let b2 = g2.input("b", Shape::new(&[n], DType::F64));
        let xr = g2.add_node(
            Op::Reshape {
                new_shape: vec![1, n as i64],
            },
            vec![x2],
            Shape::new(&[1, n], DType::F64),
        );
        let m = g2.matmul(xr, w2, Shape::new(&[1, n], DType::F64));
        let mf = g2.add_node(
            Op::Reshape {
                new_shape: vec![n as i64],
            },
            vec![m],
            Shape::new(&[n], DType::F64),
        );
        let yv2 = g2.binary(BinaryOp::Add, mf, b2, Shape::new(&[n], DType::F64));
        let l2 = g2.reduce(
            yv2,
            ReduceOp::Sum,
            vec![0],
            false,
            Shape::new(&[1], DType::F64),
        );
        g2.set_outputs(vec![l2]);
        let (s2, mut a2) = prepare_f64(&g2, &[(x2, xs_slice), (w2, &w_data), (b2, &b_data)]);
        execute_thunks(&s2, a2.raw_buf_mut());
        let scalar_out = read_arena_f64(&a2, l2, 1);
        assert!(
            (batched_out[bi] - scalar_out[0]).abs() < 1e-12,
            "row {bi}: batched={} scalar={}",
            batched_out[bi],
            scalar_out[0]
        );
    }
}

/// Full gradient through scan-with-xs: dinit AND dxs both checked
/// against finite differences. Forward
///   carry_{t+1} = solve(M, carry_t + xs\[t\])
///   loss        = sum(carry_length)
/// Verifies that grad_with_loss returns gradients w.r.t. both
/// `init` and `xs` and that dxs matches per-element FD.
#[test]
fn scan_with_xs_dxs_matches_fd() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 3usize;
    let length = 3u32;
    let dt = 0.1_f64;

    let mut m_data = vec![0.0_f64; n * n];
    for i in 0..n {
        m_data[i * n + i] = 1.0 + dt * 2.0;
        if i > 0 {
            m_data[i * n + (i - 1)] = -dt;
        }
        if i + 1 < n {
            m_data[i * n + (i + 1)] = -dt;
        }
    }
    let m_bytes: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();

    let mut body = Graph::new("be_dxs_body");
    let carry = body.input("carry", Shape::new(&[n], DType::F64));
    let drive = body.input("drive", Shape::new(&[n], DType::F64));
    let m = body.add_node(
        Op::Constant { data: m_bytes },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let driven = body.binary(BinaryOp::Add, carry, drive, Shape::new(&[n], DType::F64));
    let next = body.dense_solve(m, driven, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("be_dxs_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let xs = g.input("xs", Shape::new(&[length as usize, n], DType::F64));
    let final_carry = g.scan_with_xs(init, &[xs], body, length);
    let loss = g.reduce(
        final_carry,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    // wrt = [init, xs] — get both gradients back.
    let bwd = grad_with_loss(&g, &[init, xs]);
    assert_eq!(bwd.outputs.len(), 3, "[loss, dinit, dxs]");

    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let init_bwd = find_by_name(&bwd, "init");
    let xs_bwd = find_by_name(&bwd, "xs");
    let d_out_bwd = find_by_name(&bwd, "d_output");

    let init_data = vec![0.5_f64, 0.0, -0.5];
    let xs_data: Vec<f64> = (0..length as usize * n)
        .map(|i| 0.1_f64 * ((i as f64) - 4.0))
        .collect();
    let d_seed = [1.0_f64];

    let (sched, mut arena) = prepare_f64(
        &bwd,
        &[
            (init_bwd, &init_data),
            (xs_bwd, &xs_data),
            (d_out_bwd, &d_seed),
        ],
    );
    execute_thunks(&sched, arena.raw_buf_mut());
    let dinit = read_arena_f64(&arena, bwd.outputs[1], n);
    let dxs = read_arena_f64(&arena, bwd.outputs[2], length as usize * n);

    let h = 1e-6;
    let loss_at = |x0: &[f64], xs_in: &[f64]| -> f64 {
        let mut acc = x0.to_vec();
        for t in 0..length as usize {
            for j in 0..n {
                acc[j] += xs_in[t * n + j];
            }
            let mut a_copy = m_data.clone();
            crate::blas::dgesv(&mut a_copy, &mut acc, n, 1);
        }
        acc.iter().sum()
    };

    // FD on dinit (sanity).
    for i in 0..n {
        let mut ip = init_data.to_vec();
        ip[i] += h;
        let mut im = init_data.to_vec();
        im[i] -= h;
        let fd = (loss_at(&ip, &xs_data) - loss_at(&im, &xs_data)) / (2.0 * h);
        assert!(
            (dinit[i] - fd).abs() < 1e-7,
            "FD dinit[{i}]: AD={} FD={}",
            dinit[i],
            fd
        );
    }

    // FD on every dxs entry — full per-step gradient check.
    for t in 0..length as usize {
        for j in 0..n {
            let idx = t * n + j;
            let mut xp = xs_data.clone();
            xp[idx] += h;
            let mut xm = xs_data.clone();
            xm[idx] -= h;
            let fd = (loss_at(&init_data, &xp) - loss_at(&init_data, &xm)) / (2.0 * h);
            assert!(
                (dxs[idx] - fd).abs() < 1e-7,
                "FD dxs[t={t},j={j}]: AD={} FD={}",
                dxs[idx],
                fd
            );
        }
    }
}

/// Gradient through a scan with per-step xs (Circulax-shaped).
/// Forward:
///   carry_{t+1} = solve(M, carry_t + xs\[t\])
///   loss = sum(carry_length)
/// dxs is out of MVP (asserted in the VJP rule's body_vjp `wrt`),
/// but `dinit` flows correctly through the body's reverse Jacobian
/// even with xs in the chain. Verify dinit against finite differences.
#[test]
fn scan_with_xs_gradient_dinit_matches_fd() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 3usize;
    let length = 3u32;
    let dt = 0.1_f64;

    let mut m_data = vec![0.0_f64; n * n];
    for i in 0..n {
        m_data[i * n + i] = 1.0 + dt * 2.0;
        if i > 0 {
            m_data[i * n + (i - 1)] = -dt;
        }
        if i + 1 < n {
            m_data[i * n + (i + 1)] = -dt;
        }
    }
    let m_bytes: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();

    let mut body = Graph::new("be_xs_grad_body");
    let carry = body.input("carry", Shape::new(&[n], DType::F64));
    let drive = body.input("drive", Shape::new(&[n], DType::F64));
    let m = body.add_node(
        Op::Constant { data: m_bytes },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let driven = body.binary(BinaryOp::Add, carry, drive, Shape::new(&[n], DType::F64));
    let next = body.dense_solve(m, driven, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("be_xs_grad_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let xs = g.input("xs", Shape::new(&[length as usize, n], DType::F64));
    let final_carry = g.scan_with_xs(init, &[xs], body, length);
    let loss = g.reduce(
        final_carry,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    let bwd = grad_with_loss(&g, &[init]);

    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let init_bwd = find_by_name(&bwd, "init");
    let xs_bwd = find_by_name(&bwd, "xs");
    let d_out_bwd = find_by_name(&bwd, "d_output");

    let init_data = vec![0.5_f64, 0.0, -0.5];
    // Drive: small per-step pulse, varying per element.
    let xs_data: Vec<f64> = (0..length as usize * n)
        .map(|i| 0.1_f64 * ((i as f64) - 4.0))
        .collect();
    let d_seed = [1.0_f64];

    let (sched, mut arena) = prepare_f64(
        &bwd,
        &[
            (init_bwd, &init_data),
            (xs_bwd, &xs_data),
            (d_out_bwd, &d_seed),
        ],
    );
    execute_thunks(&sched, arena.raw_buf_mut());
    let dinit = read_arena_f64(&arena, bwd.outputs[1], n);

    let h = 1e-6;
    let loss_at = |x0: &[f64]| -> f64 {
        let mut acc = x0.to_vec();
        for t in 0..length as usize {
            for j in 0..n {
                acc[j] += xs_data[t * n + j];
            }
            let mut a_copy = m_data.clone();
            crate::blas::dgesv(&mut a_copy, &mut acc, n, 1);
        }
        acc.iter().sum()
    };
    for i in 0..n {
        let mut ip = init_data.to_vec();
        ip[i] += h;
        let mut im = init_data.to_vec();
        im[i] -= h;
        let fd = (loss_at(&ip) - loss_at(&im)) / (2.0 * h);
        assert!(
            (dinit[i] - fd).abs() < 1e-7,
            "FD dinit[{i}]: AD={} FD={}",
            dinit[i],
            fd
        );
    }
}

/// Gradient through a geometric-growth scan: forward
///   x_{t+1} = 1.1 · x_t,    x_0 = init
///   final   = x_length     = init · 1.1^length
///   loss    = sum(final)
/// closed-form ∂loss/∂init\[i\] = 1.1^length for every i.
/// Validates the VJP path: AD pre-pass rewrites save_trajectory=false
/// to true, autodiff emits Op::ScanBackward, executor walks t back.
#[test]
fn scan_gradient_geometric_matches_closed_form() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 3usize;
    let length = 5u32;

    let mut body = Graph::new("scan_grad_body");
    let x = body.input("carry", Shape::new(&[n], DType::F64));
    let scale_bytes: Vec<u8> = (0..n).flat_map(|_| 1.1_f64.to_le_bytes()).collect();
    let scale = body.add_node(
        Op::Constant { data: scale_bytes },
        vec![],
        Shape::new(&[n], DType::F64),
    );
    let next = body.binary(BinaryOp::Mul, x, scale, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("scan_grad_outer");
    let init = g.input("init", Shape::new(&[n], DType::F64));
    let final_x = g.scan(init, body, length);
    let loss = g.reduce(
        final_x,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    let bwd = grad_with_loss(&g, &[init]);
    assert_eq!(bwd.outputs.len(), 2);

    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let init_bwd = find_by_name(&bwd, "init");
    let d_out_bwd = find_by_name(&bwd, "d_output");

    let init_data = vec![1.0_f64; n];
    let d_seed = [1.0_f64];
    let (sched, mut arena) = prepare_f64(&bwd, &[(init_bwd, &init_data), (d_out_bwd, &d_seed)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let dinit = read_arena_f64(&arena, bwd.outputs[1], n);

    let want = 1.1_f64.powi(length as i32);
    for i in 0..n {
        assert!(
            (dinit[i] - want).abs() < 1e-12,
            "dinit[{i}] = {} want {}",
            dinit[i],
            want
        );
    }

    // Finite-difference cross-check on init[0].
    let h = 1e-6;
    let loss_at = |x: &[f64]| -> f64 {
        let mut acc = x.to_vec();
        for _ in 0..length {
            for v in acc.iter_mut() {
                *v *= 1.1;
            }
        }
        acc.iter().sum()
    };
    let mut ip = init_data.clone();
    ip[0] += h;
    let mut im = init_data.clone();
    im[0] -= h;
    let fd = (loss_at(&ip) - loss_at(&im)) / (2.0 * h);
    assert!(
        (dinit[0] - fd).abs() < 1e-7,
        "FD dinit[0]: AD={} FD={}",
        dinit[0],
        fd
    );
}

/// Gradient through Backward Euler scan composing with DenseSolve.
/// Asserts dinit matches finite-difference per coordinate.
#[test]
fn scan_gradient_backward_euler_matches_fd() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 4usize;
    let length = 3u32;
    let dt = 0.05_f64;

    let mut m_data = vec![0.0_f64; n * n];
    for i in 0..n {
        m_data[i * n + i] = 1.0 + dt * 2.0;
        if i > 0 {
            m_data[i * n + (i - 1)] = -dt;
        }
        if i + 1 < n {
            m_data[i * n + (i + 1)] = -dt;
        }
    }
    let m_bytes: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();

    let mut body = Graph::new("be_grad_body");
    let x = body.input("x", Shape::new(&[n], DType::F64));
    let m = body.add_node(
        Op::Constant { data: m_bytes },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let next = body.dense_solve(m, x, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("be_grad_outer");
    let init = g.input("x0", Shape::new(&[n], DType::F64));
    let final_x = g.scan(init, body, length);
    let loss = g.reduce(
        final_x,
        ReduceOp::Sum,
        vec![0],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    let bwd = grad_with_loss(&g, &[init]);

    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let init_bwd = find_by_name(&bwd, "x0");
    let d_out_bwd = find_by_name(&bwd, "d_output");

    let init_data: [f64; 4] = [0.0, 1.0, 0.0, 0.0];
    let d_seed = [1.0_f64];
    let (sched, mut arena) = prepare_f64(&bwd, &[(init_bwd, &init_data), (d_out_bwd, &d_seed)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let dinit = read_arena_f64(&arena, bwd.outputs[1], n);

    let h = 1e-6;
    let loss_at = |x0: &[f64]| -> f64 {
        let mut acc = x0.to_vec();
        for _ in 0..length {
            let mut a_copy = m_data.clone();
            crate::blas::dgesv(&mut a_copy, &mut acc, n, 1);
        }
        acc.iter().sum()
    };
    for i in 0..n {
        let mut ip = init_data.to_vec();
        ip[i] += h;
        let mut im = init_data.to_vec();
        im[i] -= h;
        let fd = (loss_at(&ip) - loss_at(&im)) / (2.0 * h);
        assert!(
            (dinit[i] - fd).abs() < 1e-7,
            "FD dinit[{i}]: AD={} FD={}",
            dinit[i],
            fd
        );
    }
}

/// Trajectory-mode scan: same Backward Euler body, but record the
/// carry at every step. Output is `[length, n]` — row `t` is the
/// state after step `t+1`. Validates the SaveAt-style waveform
/// recording end-to-end, including that the last row equals what
/// the no-trajectory variant would have returned.
#[test]
fn scan_trajectory_backward_euler_records_waveform() {
    let n = 4usize;
    let length = 5u32;
    let dt = 0.05_f64;

    let mut m_data = vec![0.0_f64; n * n];
    for i in 0..n {
        m_data[i * n + i] = 1.0 + dt * 2.0;
        if i > 0 {
            m_data[i * n + (i - 1)] = -dt;
        }
        if i + 1 < n {
            m_data[i * n + (i + 1)] = -dt;
        }
    }
    let m_bytes: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();

    let mut body = Graph::new("be_traj_body");
    let x = body.input("x", Shape::new(&[n], DType::F64));
    let m = body.add_node(
        Op::Constant { data: m_bytes },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let next = body.dense_solve(m, x, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("be_traj_outer");
    let init = g.input("x0", Shape::new(&[n], DType::F64));
    let traj = g.scan_trajectory(init, body, length);
    g.set_outputs(vec![traj]);

    let init_data: [f64; 4] = [0.0, 1.0, 0.0, 0.0];
    let (sched, mut arena) = prepare_f64(&g, &[(init, &init_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let got = read_arena_f64(&arena, traj, length as usize * n);

    // Reference: each step's solve, recorded.
    let mut want = Vec::<f64>::with_capacity(length as usize * n);
    let mut x_ref = init_data.to_vec();
    for _ in 0..length {
        let mut a_copy = m_data.clone();
        crate::blas::dgesv(&mut a_copy, &mut x_ref, n, 1);
        want.extend_from_slice(&x_ref);
    }
    for i in 0..length as usize * n {
        assert!(
            (got[i] - want[i]).abs() < 1e-12,
            "got[{i}] = {} ref {}",
            got[i],
            want[i]
        );
    }

    // Sanity: trajectory rows are monotone-decreasing in mass
    // (Backward Euler diffuses; boundary leak removes mass).
    for t in 1..length as usize {
        let prev: f64 = got[(t - 1) * n..t * n].iter().sum();
        let curr: f64 = got[t * n..(t + 1) * n].iter().sum();
        assert!(
            curr <= prev + 1e-15,
            "mass should decay: row {} sum {prev}, row {t} sum {curr}",
            t - 1
        );
    }

    // Last row of the trajectory equals what a non-trajectory
    // scan returns — verify by running the same forward through
    // the simpler API and comparing.
    let mut body2 = Graph::new("be_final_body");
    let x2 = body2.input("x", Shape::new(&[n], DType::F64));
    let m_bytes2: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();
    let m2 = body2.add_node(
        Op::Constant { data: m_bytes2 },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let next2 = body2.dense_solve(m2, x2, Shape::new(&[n], DType::F64));
    body2.set_outputs(vec![next2]);

    let mut g2 = Graph::new("be_final_outer");
    let init2 = g2.input("x0", Shape::new(&[n], DType::F64));
    let final_x = g2.scan(init2, body2, length);
    g2.set_outputs(vec![final_x]);
    let (sched2, mut arena2) = prepare_f64(&g2, &[(init2, &init_data)]);
    execute_thunks(&sched2, arena2.raw_buf_mut());
    let final_got = read_arena_f64(&arena2, final_x, n);

    let last_row = &got[(length as usize - 1) * n..length as usize * n];
    for i in 0..n {
        assert!(
            (last_row[i] - final_got[i]).abs() < 1e-15,
            "last trajectory row[{i}] = {} vs final-scan = {}",
            last_row[i],
            final_got[i]
        );
    }
}

/// Op::Scan composing with Op::DenseSolve — the Circulax-shaped
/// pattern for Backward Euler.
/// Body: x_{t+1} = solve(I + dt·A, x_t).
/// 1-D heat-equation Laplacian A; analytic ground truth from
/// composing the same per-step solve in Rust.
#[test]
fn scan_backward_euler_heat_f64() {
    let n = 4usize;
    let length = 5u32;
    let dt = 0.05_f64;

    // Construct M = I + dt · L  where L is the Laplacian (-1, 2, -1).
    // M is constant across iterations; embed it in the body via Op::Constant.
    let mut m_data = vec![0.0_f64; n * n];
    for i in 0..n {
        m_data[i * n + i] = 1.0 + dt * 2.0;
        if i > 0 {
            m_data[i * n + (i - 1)] = -dt;
        }
        if i + 1 < n {
            m_data[i * n + (i + 1)] = -dt;
        }
    }
    let m_bytes: Vec<u8> = m_data.iter().flat_map(|x| x.to_le_bytes()).collect();

    let mut body = Graph::new("be_body");
    let x = body.input("x", Shape::new(&[n], DType::F64));
    let m = body.add_node(
        Op::Constant { data: m_bytes },
        vec![],
        Shape::new(&[n, n], DType::F64),
    );
    let next = body.dense_solve(m, x, Shape::new(&[n], DType::F64));
    body.set_outputs(vec![next]);

    let mut g = Graph::new("be_outer");
    let init = g.input("x0", Shape::new(&[n], DType::F64));
    let final_x = g.scan(init, body, length);
    g.set_outputs(vec![final_x]);

    // Initial: a sharp pulse at index 1.
    let init_data: [f64; 4] = [0.0, 1.0, 0.0, 0.0];
    let (sched, mut arena) = prepare_f64(&g, &[(init, &init_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let got = read_arena_f64(&arena, final_x, n);

    // Reference: apply the same M-solve `length` times in pure Rust.
    let mut ref_x = init_data.to_vec();
    for _ in 0..length {
        let mut a_copy = m_data.clone();
        crate::blas::dgesv(&mut a_copy, &mut ref_x, n, 1);
    }
    for i in 0..n {
        assert!(
            (got[i] - ref_x[i]).abs() < 1e-12,
            "got[{i}] = {} ref {}",
            got[i],
            ref_x[i]
        );
    }
    // Sanity: pulse should diffuse, mass should be conserved-ish
    // (Backward Euler is mass-conserving for this stencil with
    // zero-flux boundaries — but our boundaries leak, so check
    // that mass strictly decreases instead).
    let mass: f64 = got.iter().sum();
    assert!(mass > 0.0 && mass < 1.0, "diffusion mass: {mass}");
}

/// Multi-RHS forward DenseSolve: X = solve(A, B) with B [N, K]
/// stays correct end-to-end. Verifies the executor/lowering and
/// the LAPACK column-major dance both honour `nrhs > 1`.
#[test]
fn dense_solve_f64_multi_rhs_forward() {
    let n = 3usize;
    let k = 2usize;
    let mut g = Graph::new("solve_multi_rhs");
    let a = g.input("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("B", Shape::new(&[n, k], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n, k], DType::F64));
    g.set_outputs(vec![x]);

    let a_data = [2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 2.0_f64];
    let b_data = [1.0, 4.0, 2.0, -1.0, 3.0, 2.0_f64];
    let (sched, mut arena) = prepare_f64(&g, &[(a, &a_data), (b, &b_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let x_got = read_arena_f64(&arena, x, n * k);
    for c in 0..k {
        for i in 0..n {
            let mut acc = 0.0_f64;
            for j in 0..n {
                acc += a_data[i * n + j] * x_got[j * k + c];
            }
            let want = b_data[i * k + c];
            assert!(
                (acc - want).abs() < 1e-10,
                "col {c} row {i}: got {acc} want {want}"
            );
        }
    }
}

/// Multi-RHS reverse-mode VJP: dB = (Aᵀ)⁻¹·1, dA = -dB · Xᵀ.
/// Verified analytically + finite differences on dB[0,0].
#[test]
fn dense_solve_f64_multi_rhs_gradient() {
    use rlx_opt::autodiff::grad_with_loss;
    let n = 3usize;
    let k = 2usize;
    let mut g = Graph::new("solve_mrhs_grad");
    let a = g.param("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("B", Shape::new(&[n, k], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n, k], DType::F64));
    let loss = g.reduce(
        x,
        ReduceOp::Sum,
        vec![0, 1],
        false,
        Shape::new(&[1], DType::F64),
    );
    g.set_outputs(vec![loss]);

    let bwd = grad_with_loss(&g, &[a, b]);
    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let a_bwd = find_by_name(&bwd, "A");
    let b_bwd = find_by_name(&bwd, "B");
    let d_out = find_by_name(&bwd, "d_output");

    let a_data = [2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 2.0_f64];
    let b_data = [1.0, 4.0, 2.0, -1.0, 3.0, 2.0_f64];
    let d_seed = [1.0_f64];

    let (sched, mut arena) = prepare_f64(
        &bwd,
        &[(a_bwd, &a_data), (b_bwd, &b_data), (d_out, &d_seed)],
    );
    execute_thunks(&sched, arena.raw_buf_mut());
    let da_got = read_arena_f64(&arena, bwd.outputs[1], n * n);
    let db_got = read_arena_f64(&arena, bwd.outputs[2], n * k);

    // Reference.
    let mut x_ref = b_data;
    {
        let mut a_copy = a_data;
        crate::blas::dgesv(&mut a_copy, &mut x_ref, n, k);
    }
    let mut at = [0.0_f64; 9];
    for i in 0..n {
        for j in 0..n {
            at[i * n + j] = a_data[j * n + i];
        }
    }
    let mut ones_nk = vec![1.0_f64; n * k];
    crate::blas::dgesv(&mut at, &mut ones_nk, n, k);
    let db_ref = ones_nk;
    let mut da_ref = [0.0_f64; 9];
    for i in 0..n {
        for j in 0..n {
            let mut acc = 0.0_f64;
            for c in 0..k {
                acc += db_ref[i * k + c] * x_ref[j * k + c];
            }
            da_ref[i * n + j] = -acc;
        }
    }
    for i in 0..n * k {
        assert!(
            (db_got[i] - db_ref[i]).abs() < 1e-10,
            "dB[{i}]: got {} want {}",
            db_got[i],
            db_ref[i]
        );
    }
    for i in 0..n * n {
        assert!(
            (da_got[i] - da_ref[i]).abs() < 1e-10,
            "dA[{i}]: got {} want {}",
            da_got[i],
            da_ref[i]
        );
    }

    // FD on dB[0,0].
    let h = 1e-6;
    let mut bp = b_data;
    bp[0] += h;
    let mut bm = b_data;
    bm[0] -= h;
    let xp = {
        let mut a_copy = a_data;
        crate::blas::dgesv(&mut a_copy, &mut bp, n, k);
        bp
    };
    let xm = {
        let mut a_copy = a_data;
        crate::blas::dgesv(&mut a_copy, &mut bm, n, k);
        bm
    };
    let lp: f64 = xp.iter().sum();
    let lm: f64 = xm.iter().sum();
    let fd = (lp - lm) / (2.0 * h);
    assert!(
        (db_got[0] - fd).abs() < 1e-7,
        "FD dB[0,0]: AD={} FD={}",
        db_got[0],
        fd
    );
}

/// Multi-RHS forward-mode JVP w.r.t. B. Closed form: t_X = solve(A, t_B).
#[test]
fn dense_solve_f64_multi_rhs_jvp() {
    use rlx_opt::autodiff_fwd::jvp;
    let n = 3usize;
    let k = 2usize;
    let mut g = Graph::new("solve_mrhs_jvp");
    let a = g.input("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("B", Shape::new(&[n, k], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n, k], DType::F64));
    g.set_outputs(vec![x]);

    let jg = jvp(&g, &[b]);
    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let a_id = find_by_name(&jg, "A");
    let b_id = find_by_name(&jg, "B");
    let tb_id = find_by_name(&jg, "tangent_B");

    let a_data = [2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 2.0_f64];
    let b_data = [1.0, 4.0, 2.0, -1.0, 3.0, 2.0_f64];
    let tb_data = [0.5, 0.0, -0.25, 1.0, 1.0, -0.5_f64];

    let (sched, mut arena) =
        prepare_f64(&jg, &[(a_id, &a_data), (b_id, &b_data), (tb_id, &tb_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let tangent_x = read_arena_f64(&arena, jg.outputs[1], n * k);

    let mut a_copy = a_data;
    let mut tb_copy = tb_data;
    crate::blas::dgesv(&mut a_copy, &mut tb_copy, n, k);
    for i in 0..n * k {
        assert!(
            (tangent_x[i] - tb_copy[i]).abs() < 1e-10,
            "t_X[{i}]: AD={} ref={}",
            tangent_x[i],
            tb_copy[i]
        );
    }

    let h = 1e-6;
    let mut bp = b_data;
    let mut bm = b_data;
    for i in 0..n * k {
        bp[i] += h * tb_data[i];
        bm[i] -= h * tb_data[i];
    }
    let xp = {
        let mut a_copy = a_data;
        crate::blas::dgesv(&mut a_copy, &mut bp, n, k);
        bp
    };
    let xm = {
        let mut a_copy = a_data;
        crate::blas::dgesv(&mut a_copy, &mut bm, n, k);
        bm
    };
    for i in 0..n * k {
        let fd = (xp[i] - xm[i]) / (2.0 * h);
        assert!(
            (tangent_x[i] - fd).abs() < 1e-7,
            "FD t_X[{i}]: AD={} FD={}",
            tangent_x[i],
            fd
        );
    }
}

/// Forward-mode JVP through DenseSolve, end-to-end at f64.
///
/// Build forward x = solve(A, b), call `jvp(forward, [b])`,
/// compile + run, and check the tangent output matches the
/// closed form `t_x = solve(A, t_b)` plus a finite-difference
/// cross-check `(solve(A, b + h·t_b) − solve(A, b − h·t_b)) / 2h`.
#[test]
fn jvp_dense_solve_b_runs_and_matches_fd() {
    use rlx_opt::autodiff_fwd::jvp;
    let n = 3usize;

    // Forward.
    let mut g = Graph::new("jvp_b_e2e");
    let a = g.input("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("b", Shape::new(&[n], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n], DType::F64));
    g.set_outputs(vec![x]);

    // JVP graph perturbing b only.
    let jg = jvp(&g, &[b]);
    // The JVP graph holds a fresh "tangent_b" Input on top of A and b.
    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let a_id = find_by_name(&jg, "A");
    let b_id = find_by_name(&jg, "b");
    let tb_id = find_by_name(&jg, "tangent_b");

    let a_data: [f64; 9] = [2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 2.0];
    let b_data: [f64; 3] = [1.0, 2.0, 3.0];
    // Pick an arbitrary perturbation direction.
    let tb_data: [f64; 3] = [0.5, -0.25, 1.0];

    let (sched, mut arena) =
        prepare_f64(&jg, &[(a_id, &a_data), (b_id, &b_data), (tb_id, &tb_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());

    // Outputs: [primal_x, tangent_x].
    let primal_x = read_arena_f64(&arena, jg.outputs[0], n);
    let tangent_x = read_arena_f64(&arena, jg.outputs[1], n);

    // Closed form: t_x = solve(A, t_b).
    let t_x_ref = {
        let mut a = a_data;
        let mut tb = tb_data;
        let info = crate::blas::dgesv(&mut a, &mut tb, n, 1);
        assert_eq!(info, 0);
        tb
    };
    for i in 0..n {
        assert!(
            (tangent_x[i] - t_x_ref[i]).abs() < 1e-10,
            "t_x[{i}]: got {} want {}",
            tangent_x[i],
            t_x_ref[i]
        );
    }

    // FD: x(b + h·tb) − x(b − h·tb)) / 2h
    let h = 1e-6;
    let mut bp = b_data;
    let mut bm = b_data;
    for i in 0..n {
        bp[i] += h * tb_data[i];
        bm[i] -= h * tb_data[i];
    }
    let xp = {
        let mut a = a_data;
        let info = crate::blas::dgesv(&mut a, &mut bp, n, 1);
        assert_eq!(info, 0);
        bp
    };
    let xm = {
        let mut a = a_data;
        let info = crate::blas::dgesv(&mut a, &mut bm, n, 1);
        assert_eq!(info, 0);
        bm
    };
    let fd: Vec<f64> = (0..n).map(|i| (xp[i] - xm[i]) / (2.0 * h)).collect();
    for i in 0..n {
        assert!(
            (tangent_x[i] - fd[i]).abs() < 1e-7,
            "FD mismatch t_x[{i}]: AD={} FD={}",
            tangent_x[i],
            fd[i]
        );
    }
    // Sanity: primal output is the actual solve.
    let primal_ref = {
        let mut a = a_data;
        let mut b = b_data;
        crate::blas::dgesv(&mut a, &mut b, n, 1);
        b
    };
    for i in 0..n {
        assert!((primal_x[i] - primal_ref[i]).abs() < 1e-10);
    }
}

/// Forward-mode JVP through DenseSolve perturbing A. The tangent
/// path includes the −t_A·x correction term.
/// `t_x = −solve(A, t_A · x)` should match a finite-difference
/// directional derivative of `solve(A, b)` w.r.t. A in the
/// `t_A` direction.
#[test]
fn jvp_dense_solve_a_runs_and_matches_fd() {
    use rlx_opt::autodiff_fwd::jvp;
    let n = 3usize;

    let mut g = Graph::new("jvp_a_e2e");
    let a = g.input("A", Shape::new(&[n, n], DType::F64));
    let b = g.input("b", Shape::new(&[n], DType::F64));
    let x = g.dense_solve(a, b, Shape::new(&[n], DType::F64));
    g.set_outputs(vec![x]);

    let jg = jvp(&g, &[a]);
    let find_by_name = |graph: &Graph, want: &str| -> NodeId {
        for node in graph.nodes() {
            let name = match &node.op {
                Op::Input { name } | Op::Param { name } => Some(name.as_str()),
                _ => None,
            };
            if name == Some(want) {
                return node.id;
            }
        }
        panic!("no node named {want:?}");
    };
    let a_id = find_by_name(&jg, "A");
    let b_id = find_by_name(&jg, "b");
    let ta_id = find_by_name(&jg, "tangent_A");

    let a_data: [f64; 9] = [2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 2.0];
    let b_data: [f64; 3] = [1.0, 2.0, 3.0];
    // Asymmetric perturbation direction for A.
    let ta_data: [f64; 9] = [0.10, -0.05, 0.02, 0.03, 0.20, -0.04, -0.01, 0.07, 0.15];

    let (sched, mut arena) =
        prepare_f64(&jg, &[(a_id, &a_data), (b_id, &b_data), (ta_id, &ta_data)]);
    execute_thunks(&sched, arena.raw_buf_mut());

    let tangent_x = read_arena_f64(&arena, jg.outputs[1], n);

    // Closed form: x = solve(A, b); t_x = −solve(A, t_A · x).
    let x_ref = {
        let mut a = a_data;
        let mut b = b_data;
        crate::blas::dgesv(&mut a, &mut b, n, 1);
        b
    };
    let mut prod = [0.0_f64; 3];
    for i in 0..n {
        for j in 0..n {
            prod[i] += ta_data[i * n + j] * x_ref[j];
        }
    }
    let t_x_ref = {
        let mut a = a_data;
        let mut p = prod;
        crate::blas::dgesv(&mut a, &mut p, n, 1);
        [-p[0], -p[1], -p[2]]
    };
    for i in 0..n {
        assert!(
            (tangent_x[i] - t_x_ref[i]).abs() < 1e-10,
            "closed-form t_x[{i}]: AD={} ref={}",
            tangent_x[i],
            t_x_ref[i]
        );
    }

    // FD: solve(A + h·t_A, b) and solve(A − h·t_A, b).
    let h = 1e-6;
    let mut ap = a_data;
    let mut am = a_data;
    for i in 0..n * n {
        ap[i] += h * ta_data[i];
        am[i] -= h * ta_data[i];
    }
    let xp = {
        let mut a = ap;
        let mut b = b_data;
        crate::blas::dgesv(&mut a, &mut b, n, 1);
        b
    };
    let xm = {
        let mut a = am;
        let mut b = b_data;
        crate::blas::dgesv(&mut a, &mut b, n, 1);
        b
    };
    for i in 0..n {
        let fd = (xp[i] - xm[i]) / (2.0 * h);
        assert!(
            (tangent_x[i] - fd).abs() < 1e-7,
            "FD t_x[{i}]: AD={} FD={}",
            tangent_x[i],
            fd
        );
    }
}

/// Real INT8 conv2d parity. Same setup as QMatMul: pre-quantize
/// f32 inputs to i8, run `Op::QConv2d`, compare against an
/// in-test reference loop that does the same i32 accumulation
/// and requantize math. Symmetric quant (zp=0) to keep the math
/// head-to-head.
#[test]
fn q_conv2d_matches_reference() {
    use rlx_ir::Philox4x32;
    // Small NCHW shape — enough to exercise stride/padding edges.
    let n = 1usize;
    let c_in = 2usize;
    let h = 5usize;
    let w_in = 5usize;
    let c_out = 3usize;
    let kh = 3usize;
    let kw = 3usize;
    let ph = 1usize;
    let pw = 1usize;
    let sh = 1usize;
    let sw = 1usize;
    let h_out = (h + 2 * ph - kh) / sh + 1;
    let w_out = (w_in + 2 * pw - kw) / sw + 1;

    let x_scale = 0.04f32;
    let w_scale = 0.02f32;
    let out_scale = 0.5f32;
    let mult = x_scale * w_scale / out_scale;

    let mut rng = Philox4x32::new(2099);
    let mut xf = vec![0f32; n * c_in * h * w_in];
    rng.fill_normal(&mut xf);
    let mut wf = vec![0f32; c_out * c_in * kh * kw];
    rng.fill_normal(&mut wf);
    let xq: Vec<i8> = xf
        .iter()
        .map(|&v| ((v / x_scale).round() as i32).clamp(-128, 127) as i8)
        .collect();
    let wq: Vec<i8> = wf
        .iter()
        .map(|&v| ((v / w_scale).round() as i32).clamp(-128, 127) as i8)
        .collect();
    let bias: Vec<i32> = vec![0i32; c_out];

    let mut g = Graph::new("qconv");
    let xn = g.input("x", Shape::new(&[n, c_in, h, w_in], DType::I8));
    let wn = g.input("w", Shape::new(&[c_out, c_in, kh, kw], DType::I8));
    let bn = g.input("b", Shape::new(&[c_out], DType::I32));
    let out = g.q_conv2d(
        xn,
        wn,
        bn,
        vec![kh, kw],
        vec![sh, sw],
        vec![ph, pw],
        vec![1, 1],
        1,
        0,
        0,
        0,
        mult,
        Shape::new(&[n, c_out, h_out, w_out], DType::I8),
    );
    g.set_outputs(vec![out]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    // Capture offsets before borrowing the buf mutably (avoids
    // overlap between &mut and the &arena.byte_offset reads).
    let xn_off = arena.byte_offset(xn);
    let wn_off = arena.byte_offset(wn);
    let bn_off = arena.byte_offset(bn);
    let out_off = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(xn_off) as *mut i8;
        for (i, &v) in xq.iter().enumerate() {
            *p.add(i) = v;
        }
        let p = buf.as_mut_ptr().add(wn_off) as *mut i8;
        for (i, &v) in wq.iter().enumerate() {
            *p.add(i) = v;
        }
        let p = buf.as_mut_ptr().add(bn_off) as *mut i32;
        for (i, &v) in bias.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let out_q: Vec<i8> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const i8;
        (0..n * c_out * h_out * w_out).map(|i| *p.add(i)).collect()
    };

    // Reference: scalar loop in NCHW with the same requantize.
    let mut out_ref = vec![0i8; n * c_out * h_out * w_out];
    for ni in 0..n {
        for co in 0..c_out {
            for ho in 0..h_out {
                for wo in 0..w_out {
                    let mut acc: i32 = 0;
                    for ci in 0..c_in {
                        for ki in 0..kh {
                            for kj in 0..kw {
                                let hi = ho * sh + ki;
                                let wi = wo * sw + kj;
                                if hi < ph || wi < pw {
                                    continue;
                                }
                                let hi = hi - ph;
                                let wi = wi - pw;
                                if hi >= h || wi >= w_in {
                                    continue;
                                }
                                let xv = xq[((ni * c_in) + ci) * h * w_in + hi * w_in + wi] as i32;
                                let wv = wq[((co * c_in) + ci) * kh * kw + ki * kw + kj] as i32;
                                acc += xv * wv;
                            }
                        }
                    }
                    let r = (acc as f32 * mult).round() as i32;
                    let r = r.clamp(-128, 127) as i8;
                    out_ref[((ni * c_out) + co) * h_out * w_out + ho * w_out + wo] = r;
                }
            }
        }
    }

    for (i, (a, r)) in out_q.iter().zip(&out_ref).enumerate() {
        assert_eq!(a, r, "q_conv2d[{i}]: kernel {a} vs reference {r}");
    }
}

/// Real INT8 matmul parity: compare `Op::QMatMul` against the
/// fake-quant reference `Dequantize → MatMul → Quantize` that
/// would produce the same output if we round-tripped through
/// f32. Both should agree element-for-element (or within ±1 i8
/// step, since rounding in the requantize uses different code
/// paths). Symmetric quantization (zp=0) for both paths to keep
/// the math head-to-head.
#[test]
fn q_matmul_matches_fake_quant_reference() {
    use rlx_ir::Philox4x32;
    let m = 3usize;
    let k = 8usize;
    let n = 5usize;
    let mut rng = Philox4x32::new(2031);

    // Pick scales and quantize random f32 inputs to i8.
    let x_scale = 0.05f32;
    let w_scale = 0.03f32;
    let out_scale = 0.4f32;
    let mult = x_scale * w_scale / out_scale;
    let mut xf = vec![0f32; m * k];
    rng.fill_normal(&mut xf);
    let mut wf = vec![0f32; k * n];
    rng.fill_normal(&mut wf);
    let xq: Vec<i8> = xf
        .iter()
        .map(|&v| ((v / x_scale).round() as i32).clamp(-128, 127) as i8)
        .collect();
    let wq: Vec<i8> = wf
        .iter()
        .map(|&v| ((v / w_scale).round() as i32).clamp(-128, 127) as i8)
        .collect();
    let bias: Vec<i32> = vec![0i32; n];

    // ── Direct INT8 path ──
    let _f = DType::F32;
    let mut g_q = Graph::new("qmm_direct");
    let xn = g_q.input("x", Shape::new(&[m, k], DType::I8));
    let wn = g_q.input("w", Shape::new(&[k, n], DType::I8));
    let bn = g_q.input("b", Shape::new(&[n], DType::I32));
    let out = g_q.q_matmul(xn, wn, bn, 0, 0, 0, mult, Shape::new(&[m, n], DType::I8));
    g_q.set_outputs(vec![out]);
    let plan = rlx_opt::memory::plan_memory(&g_q);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g_q, &arena);

    // Fill inputs.
    let xn_off = arena.byte_offset(xn);
    let wn_off = arena.byte_offset(wn);
    let bn_off = arena.byte_offset(bn);
    let out_off = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(xn_off) as *mut i8;
        for (i, &v) in xq.iter().enumerate() {
            *p.add(i) = v;
        }
        let p = buf.as_mut_ptr().add(wn_off) as *mut i8;
        for (i, &v) in wq.iter().enumerate() {
            *p.add(i) = v;
        }
        let p = buf.as_mut_ptr().add(bn_off) as *mut i32;
        for (i, &v) in bias.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let out_q: Vec<i8> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const i8;
        (0..m * n).map(|i| *p.add(i)).collect()
    };

    // ── Fake-quant reference: scalar emulation in plain Rust ──
    // Same arithmetic the kernel does, but in a verifier loop:
    //   acc = Σ (x[m,k]) · (w[k,n]),  // zps are 0
    //   out[m,n] = saturate_i8(round(acc · mult) + 0)
    let mut out_ref = vec![0i8; m * n];
    for mi in 0..m {
        for ni in 0..n {
            let mut acc: i32 = 0;
            for ki in 0..k {
                acc += (xq[mi * k + ki] as i32) * (wq[ki * n + ni] as i32);
            }
            let r = (acc as f32 * mult).round() as i32;
            out_ref[mi * n + ni] = r.clamp(-128, 127) as i8;
        }
    }

    for (i, (a, r)) in out_q.iter().zip(&out_ref).enumerate() {
        assert_eq!(a, r, "q_matmul[{i}]: kernel {a} vs reference {r}");
    }
}

/// Quantize/Dequantize round-trip — quantize an f32 tensor, then
/// dequantize back, and confirm the result tracks the input
/// within the per-element scale (the inevitable rounding error).
/// Also pins the kernel's saturation behavior at the i8 limits.
#[test]
fn quantize_dequantize_round_trip() {
    use rlx_ir::Philox4x32;
    let len = 64;
    let mut rng = Philox4x32::new(2027);
    let mut x = vec![0f32; len];
    rng.fill_normal(&mut x);
    // Stretch a couple values past the +/- saturation cliff so
    // the saturate_i8 path is exercised.
    x[0] = 999.0;
    x[1] = -999.0;

    let scale = 0.05f32;
    let zp = 3i32;

    let f = DType::F32;
    let mut g = Graph::new("qdq");
    let xn = g.input("x", Shape::new(&[len], f));
    let q = g.quantize(xn, scale, zp);
    let dq = g.dequantize(q, scale, zp);
    g.set_outputs(vec![dq]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let xn_off = arena.byte_offset(xn);
    let dq_off = arena.byte_offset(dq);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(xn_off) as *mut f32;
        for (i, &v) in x.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let out: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(dq_off) as *const f32;
        (0..len).map(|i| *p.add(i)).collect()
    };

    // Saturated values at i=0,1 should clamp to ±127's dequant
    // range (= (±127 - zp) · scale).
    let sat_pos = (127 - zp) as f32 * scale;
    let sat_neg = (-128 - zp) as f32 * scale;
    assert!((out[0] - sat_pos).abs() < 1e-6, "+sat: {}", out[0]);
    assert!((out[1] - sat_neg).abs() < 1e-6, "-sat: {}", out[1]);

    // Everything else should round-trip within `scale` (one quant
    // step = the worst-case rounding error).
    for i in 2..len {
        assert!(
            (out[i] - x[i]).abs() <= scale + 1e-5,
            "qdq[{i}]: {} → {}, scale={scale}",
            x[i],
            out[i]
        );
    }
}

/// Per-channel quantize / dequantize: independent scale and zp
/// per slice along an axis. Verifies (a) each channel uses its
/// own scale (not a shared one), (b) saturation still respects
/// the i8 range, (c) channel data layout decomposition is
/// correct (no cross-channel leakage).
#[test]
fn quantize_per_channel_round_trip() {
    let c = 4usize;
    let inner = 5usize;
    // Different magnitudes per channel — proves the per-channel
    // scale is actually being read for each row.
    let mags = [0.01f32, 0.5, 5.0, 50.0];
    let mut x = vec![0f32; c * inner];
    for ci in 0..c {
        for ii in 0..inner {
            // Sweep through values that span [-max_abs, +max_abs]
            // for each channel, plus one value past the cliff to
            // trigger saturation.
            x[ci * inner + ii] = match ii {
                0 => -mags[ci],
                1 => 0.0,
                2 => mags[ci],
                3 => mags[ci] * 1000.0,  // saturates +
                _ => -mags[ci] * 1000.0, // saturates -
            };
        }
    }
    let scales: Vec<f32> = mags.iter().map(|&m| m / 127.0).collect();
    let zps: Vec<i32> = vec![0, 0, 0, 0];

    let f = DType::F32;
    let mut g = Graph::new("qdq_pc");
    let xn = g.input("x", Shape::new(&[c, inner], f));
    let q = g.quantize_per_channel(xn, 0, scales.clone(), zps.clone());
    let dq = g.dequantize_per_channel(q, 0, scales.clone(), zps);
    g.set_outputs(vec![dq]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let xn_off = arena.byte_offset(xn);
    let dq_off = arena.byte_offset(dq);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(xn_off) as *mut f32;
        for (i, &v) in x.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let out: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(dq_off) as *const f32;
        (0..c * inner).map(|i| *p.add(i)).collect()
    };

    for ci in 0..c {
        // Within-range entries (positions 0, 1, 2) must round-trip
        // within one quant step of *that channel's* scale.
        for ii in 0..3 {
            let idx = ci * inner + ii;
            assert!(
                (out[idx] - x[idx]).abs() <= scales[ci] + 1e-5,
                "ch {ci} idx {ii}: {} vs {}",
                x[idx],
                out[idx]
            );
        }
        // Saturated positions clamp to ±127 · scale[ci].
        let sat_pos = 127.0 * scales[ci];
        let sat_neg = -128.0 * scales[ci];
        assert!(
            (out[ci * inner + 3] - sat_pos).abs() < 1e-5,
            "ch {ci} +sat: {}",
            out[ci * inner + 3]
        );
        assert!(
            (out[ci * inner + 4] - sat_neg).abs() < 1e-5,
            "ch {ci} -sat: {}",
            out[ci * inner + 4]
        );
    }
}

/// `Op::ActivationBackward` parity for every supported kind.
/// Builds a single-op graph `dx = activation_backward(x, dy)` and
/// compares each `dx[i]` to the central-difference `(act(x+ε) -
/// act(x-ε)) / (2ε) · dy\[i\]`. Sweeps the closed-form covered by
/// the kernel.
#[test]
fn activation_backward_matches_numerical_per_kind() {
    use rlx_ir::Philox4x32;
    use rlx_ir::op::Activation;
    let mut rng = Philox4x32::new(91);
    let len = 32;
    // x sampled away from kink/branch points: shifted positive
    // (exp/sqrt/log domain) for the unary-positive activations;
    // wide range otherwise. Two parallel tests would be cleaner
    // but this is concise enough.
    let mut x_pos = vec![0f32; len];
    rng.fill_normal(&mut x_pos);
    for v in x_pos.iter_mut() {
        *v = v.abs() + 0.5;
    }
    let mut x_any = vec![0f32; len];
    rng.fill_normal(&mut x_any);
    let mut dy = vec![0f32; len];
    rng.fill_normal(&mut dy);

    for &(kind, x_data, eps, tol) in &[
        (Activation::Sigmoid, &x_any[..], 1e-3, 5e-3),
        (Activation::Tanh, &x_any[..], 1e-3, 5e-3),
        (Activation::Silu, &x_any[..], 1e-3, 5e-3),
        (Activation::Gelu, &x_any[..], 1e-3, 5e-3),
        (Activation::GeluApprox, &x_any[..], 1e-3, 5e-3),
        (Activation::Exp, &x_any[..], 1e-4, 5e-3),
        (Activation::Log, &x_pos[..], 1e-4, 5e-3),
        (Activation::Sqrt, &x_pos[..], 1e-4, 5e-3),
        (Activation::Rsqrt, &x_pos[..], 1e-4, 5e-3),
        (Activation::Neg, &x_any[..], 1e-3, 5e-4),
    ] {
        let f = DType::F32;
        let mut g = Graph::new("act_bw");
        let xn = g.input("x", Shape::new(&[len], f));
        let dyn_ = g.input("dy", Shape::new(&[len], f));
        let dx = g.activation_backward(kind, xn, dyn_);
        g.set_outputs(vec![dx]);

        let plan = rlx_opt::memory::plan_memory(&g);
        let mut arena = crate::arena::Arena::from_plan(plan);
        let sched = compile_thunks(&g, &arena);

        let xn_off = arena.byte_offset(xn);
        let dyn_off = arena.byte_offset(dyn_);
        let dx_off = arena.byte_offset(dx);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(xn_off) as *mut f32;
            for (i, &v) in x_data.iter().enumerate() {
                *p.add(i) = v;
            }
            let p = buf.as_mut_ptr().add(dyn_off) as *mut f32;
            for (i, &v) in dy.iter().enumerate() {
                *p.add(i) = v;
            }
        }
        execute_thunks(&sched, arena.raw_buf_mut());
        let analytical: Vec<f32> = unsafe {
            let p = arena.raw_buf().as_ptr().add(dx_off) as *const f32;
            (0..len).map(|i| *p.add(i)).collect()
        };

        // Apply the forward activation manually; finite-difference
        // each element.
        let act_apply = |kind: Activation, x: f32| -> f32 {
            match kind {
                Activation::Sigmoid => 1.0 / (1.0 + (-x).exp()),
                Activation::Tanh => x.tanh(),
                Activation::Silu => x / (1.0 + (-x).exp()),
                Activation::Gelu => {
                    // Match the kernel's exact erf form.
                    const INV_SQRT2: f32 = 0.707_106_77;
                    0.5 * x * (1.0 + erf_f32(x * INV_SQRT2))
                }
                Activation::GeluApprox => {
                    const C: f32 = 0.797_884_6;
                    const A: f32 = 0.044_715;
                    let inner = C * (x + A * x * x * x);
                    0.5 * x * (1.0 + inner.tanh())
                }
                Activation::Exp => x.exp(),
                Activation::Log => x.ln(),
                Activation::Sqrt => x.sqrt(),
                Activation::Rsqrt => 1.0 / x.sqrt(),
                Activation::Neg => -x,
                Activation::Relu => x.max(0.0),
                Activation::Abs => x.abs(),
                Activation::Round => x.round(),
                Activation::Sin => x.sin(),
                Activation::Cos => x.cos(),
                Activation::Tan => x.tan(),
                Activation::Atan => x.atan(),
            }
        };
        for i in 0..len {
            let xv = x_data[i];
            let plus = act_apply(kind, xv + eps);
            let minus = act_apply(kind, xv - eps);
            let num = (plus - minus) / (2.0 * eps) * dy[i];
            assert!(
                (analytical[i] - num).abs() < tol,
                "{kind:?}[{i}]: analytical {} vs numerical {num}",
                analytical[i]
            );
        }
    }
}

/// Batched 3-D MatMul VJP — the transformer-attention shape
/// `[B, M, K] @ [B, K, N] = [B, M, N]`. Both gradients flow through
/// `Op::Transpose` with a perm that swaps the last two dims.
#[test]
fn matmul_3d_gradient_matches_numerical() {
    use rlx_ir::Philox4x32;
    let batch = 2usize;
    let m = 3usize;
    let k = 4usize;
    let n = 5usize;
    let mut rng = Philox4x32::new(101);
    let mut a_data = vec![0f32; batch * m * k];
    rng.fill_normal(&mut a_data);
    let mut b_data = vec![0f32; batch * k * n];
    rng.fill_normal(&mut b_data);

    let f = DType::F32;
    let mut fwd = Graph::new("matmul_3d");
    let an = fwd.input("a", Shape::new(&[batch, m, k], f));
    let bp = fwd.param("b", Shape::new(&[batch, k, n], f));
    let mm = fwd.matmul(an, bp, Shape::new(&[batch, m, n], f));
    let loss = fwd.add_node(
        Op::Reduce {
            op: ReduceOp::Sum,
            axes: vec![0, 1, 2],
            keep_dim: false,
        },
        vec![mm],
        Shape::from_dims(&[], f),
    );
    fwd.set_outputs(vec![loss]);

    let bwd_graph = rlx_opt::autodiff::grad_with_loss(&fwd, &[bp]);
    let d_out = bwd_graph
        .nodes()
        .iter()
        .find(|n| matches!(&n.op, Op::Input { name } if name == "d_output"))
        .map(|n| n.id)
        .unwrap();

    let plan = rlx_opt::memory::plan_memory(&bwd_graph);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&bwd_graph, &arena);
    for &(id, data) in &[(an, &a_data), (bp, &b_data), (d_out, &vec![1.0f32])] {
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(off) as *mut f32;
            for (i, &v) in data.iter().enumerate() {
                *p.add(i) = v;
            }
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let gb_id = bwd_graph.outputs[1];
    let g_b: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(arena.byte_offset(gb_id)) as *const f32;
        (0..batch * k * n).map(|i| *p.add(i)).collect()
    };

    // Numerical gradient: differentiate sum(a @ b) w.r.t. each b entry.
    let forward_loss = |b_vals: &[f32]| -> f32 {
        let mut out = vec![0f32; batch * m * n];
        for bi in 0..batch {
            for mi in 0..m {
                for ni in 0..n {
                    let mut acc = 0f32;
                    for ki in 0..k {
                        acc += a_data[bi * m * k + mi * k + ki] * b_vals[bi * k * n + ki * n + ni];
                    }
                    out[bi * m * n + mi * n + ni] = acc;
                }
            }
        }
        out.iter().sum()
    };
    let eps = 1e-3f32;
    let mut bp_p = b_data.clone();
    let mut g_b_num = vec![0f32; b_data.len()];
    for i in 0..b_data.len() {
        let s = bp_p[i];
        bp_p[i] = s + eps;
        let lp = forward_loss(&bp_p);
        bp_p[i] = s - eps;
        let lm = forward_loss(&bp_p);
        bp_p[i] = s;
        g_b_num[i] = (lp - lm) / (2.0 * eps);
    }
    for (i, (a, n)) in g_b.iter().zip(&g_b_num).enumerate() {
        assert!(
            (a - n).abs() < 5e-3,
            "matmul_3d g_b[{i}]: analytical {a} vs numerical {n}"
        );
    }
}

/// Composed `Op::Softmax` VJP — the gradient is built from
/// `mul + reduce_sum + expand + sub + mul`, no dedicated
/// SoftmaxBackward kernel. Verifies the closed-form
/// `dx = y · (g - Σ y·g)` matches the FD gradient over a small
/// 2-D logits tensor.
#[test]
fn softmax_gradient_matches_numerical() {
    use rlx_ir::Philox4x32;
    let n = 3usize;
    let c = 5usize;
    let mut rng = Philox4x32::new(57);
    let mut x_data = vec![0f32; n * c];
    rng.fill_normal(&mut x_data);

    let f = DType::F32;
    let mut fwd = Graph::new("softmax_only");
    let xn = fwd.input("x", Shape::new(&[n, c], f));
    let sm = fwd.add_node(Op::Softmax { axis: -1 }, vec![xn], Shape::new(&[n, c], f));
    // Loss = sum(softmax · target) for some random fixed target —
    // any linear loss will do; sum-of-all is the simplest and gives
    // a uniform gradient flow into the softmax.
    let loss = fwd.add_node(
        Op::Reduce {
            op: ReduceOp::Sum,
            axes: vec![0, 1],
            keep_dim: false,
        },
        vec![sm],
        Shape::from_dims(&[], f),
    );
    fwd.set_outputs(vec![loss]);

    // `wrt = [xn]` — autodiff exposes the gradient w.r.t. the
    // input so we can compare it directly. The forward NodeId for
    // `xn` doubles as its bwd-graph mirror.
    let bwd_graph = rlx_opt::autodiff::grad_with_loss(&fwd, &[xn]);
    let d_out = bwd_graph
        .nodes()
        .iter()
        .find(|n| matches!(&n.op, Op::Input { name } if name == "d_output"))
        .map(|n| n.id)
        .unwrap();

    let plan = rlx_opt::memory::plan_memory(&bwd_graph);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&bwd_graph, &arena);
    for &(id, data) in &[(xn, &x_data), (d_out, &vec![1.0f32])] {
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(off) as *mut f32;
            for (i, &v) in data.iter().enumerate() {
                *p.add(i) = v;
            }
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let g_x_id = bwd_graph.outputs[1];
    let g_x: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(arena.byte_offset(g_x_id)) as *const f32;
        (0..n * c).map(|i| *p.add(i)).collect()
    };

    // Loss derivative: softmax sums to 1 per row → d/dx_i sum(softmax) = 0
    // analytically. So expect g_x ≈ 0 within FD precision. (This
    // doubles as a strong sanity check for the composition.)
    let forward_loss = |x: &[f32]| -> f32 {
        let mut total = 0f32;
        for ni in 0..n {
            let row = &x[ni * c..(ni + 1) * c];
            let m = row.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
            let denom: f32 = row.iter().map(|&v| (v - m).exp()).sum();
            for &v in row {
                total += (v - m).exp() / denom;
            }
        }
        total
    };
    let eps = 1e-3f32;
    let mut p = x_data.clone();
    for i in 0..x_data.len() {
        let s = p[i];
        p[i] = s + eps;
        let lp = forward_loss(&p);
        p[i] = s - eps;
        let lm = forward_loss(&p);
        p[i] = s;
        let num = (lp - lm) / (2.0 * eps);
        assert!(
            (g_x[i] - num).abs() < 5e-3,
            "softmax g_x[{i}]: analytical {} vs numerical {num}",
            g_x[i]
        );
    }
}

/// LayerNorm VJP — three gradients in one pass:
///   d_x via `LayerNormBackwardInput`,
///   d_gamma via `LayerNormBackwardGamma`,
///   d_beta = `unbroadcast(upstream)` to gamma's shape.
#[test]
fn layer_norm_gradient_matches_numerical() {
    use rlx_ir::Philox4x32;
    let rows = 3usize;
    let h = 6usize;
    let mut rng = Philox4x32::new(1009);
    let mut x_data = vec![0f32; rows * h];
    rng.fill_normal(&mut x_data);
    let mut g_data = vec![0f32; h];
    rng.fill_normal(&mut g_data);
    for v in g_data.iter_mut() {
        *v = v.abs() + 0.5;
    }
    let mut b_data = vec![0f32; h];
    rng.fill_normal(&mut b_data);
    let eps = 1e-5f32;

    let f = DType::F32;
    let mut fwd = Graph::new("ln_only");
    let xn = fwd.input("x", Shape::new(&[rows, h], f));
    let gp = fwd.param("gamma", Shape::new(&[h], f));
    let bp = fwd.param("beta", Shape::new(&[h], f));
    let ln = fwd.add_node(
        Op::LayerNorm { axis: -1, eps },
        vec![xn, gp, bp],
        Shape::new(&[rows, h], f),
    );
    let loss = fwd.add_node(
        Op::Reduce {
            op: ReduceOp::Sum,
            axes: vec![0, 1],
            keep_dim: false,
        },
        vec![ln],
        Shape::from_dims(&[], f),
    );
    fwd.set_outputs(vec![loss]);

    let bwd_graph = rlx_opt::autodiff::grad_with_loss(&fwd, &[xn, gp, bp]);
    let d_out = bwd_graph
        .nodes()
        .iter()
        .find(|n| matches!(&n.op, Op::Input { name } if name == "d_output"))
        .map(|n| n.id)
        .unwrap();

    let plan = rlx_opt::memory::plan_memory(&bwd_graph);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&bwd_graph, &arena);
    for &(id, data) in &[
        (xn, &x_data),
        (gp, &g_data),
        (bp, &b_data),
        (d_out, &vec![1.0f32]),
    ] {
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let p = buf.as_mut_ptr().add(off) as *mut f32;
            for (i, &v) in data.iter().enumerate() {
                *p.add(i) = v;
            }
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let read = |id: NodeId, n: usize| -> Vec<f32> {
        let off = arena.byte_offset(id);
        unsafe {
            let p = arena.raw_buf().as_ptr().add(off) as *const f32;
            (0..n).map(|i| *p.add(i)).collect()
        }
    };
    let dx_a = read(bwd_graph.outputs[1], rows * h);
    let dg_a = read(bwd_graph.outputs[2], h);
    let db_a = read(bwd_graph.outputs[3], h);

    let forward_loss = |x: &[f32], g: &[f32], b: &[f32]| -> f32 {
        let mut total = 0f32;
        for r in 0..rows {
            let row = &x[r * h..(r + 1) * h];
            let mean = row.iter().sum::<f32>() / h as f32;
            let var = row.iter().map(|&v| (v - mean) * (v - mean)).sum::<f32>() / h as f32;
            let inv_std = 1.0 / (var + eps).sqrt();
            for d in 0..h {
                total += ((row[d] - mean) * inv_std) * g[d] + b[d];
            }
        }
        total
    };
    let h_eps = 1e-3f32;

    let mut x_p = x_data.clone();
    for i in 0..x_p.len() {
        let s = x_p[i];
        x_p[i] = s + h_eps;
        let lp = forward_loss(&x_p, &g_data, &b_data);
        x_p[i] = s - h_eps;
        let lm = forward_loss(&x_p, &g_data, &b_data);
        x_p[i] = s;
        let num = (lp - lm) / (2.0 * h_eps);
        assert!(
            (dx_a[i] - num).abs() < 5e-3,
            "ln dx[{i}]: analytical {} vs numerical {num}",
            dx_a[i]
        );
    }
    let mut g_p = g_data.clone();
    for i in 0..g_p.len() {
        let s = g_p[i];
        g_p[i] = s + h_eps;
        let lp = forward_loss(&x_data, &g_p, &b_data);
        g_p[i] = s - h_eps;
        let lm = forward_loss(&x_data, &g_p, &b_data);
        g_p[i] = s;
        let num = (lp - lm) / (2.0 * h_eps);
        assert!(
            (dg_a[i] - num).abs() < 5e-3,
            "ln dg[{i}]: analytical {} vs numerical {num}",
            dg_a[i]
        );
    }
    let mut b_p = b_data.clone();
    for i in 0..b_p.len() {
        let s = b_p[i];
        b_p[i] = s + h_eps;
        let lp = forward_loss(&x_data, &g_data, &b_p);
        b_p[i] = s - h_eps;
        let lm = forward_loss(&x_data, &g_data, &b_p);
        b_p[i] = s;
        let num = (lp - lm) / (2.0 * h_eps);
        assert!(
            (db_a[i] - num).abs() < 5e-3,
            "ln db[{i}]: analytical {} vs numerical {num}",
            db_a[i]
        );
    }
}

/// Single dense layer + softmax-cross-entropy + mean reduce —
/// the simplest non-trivial training graph. Validates MatMul,
/// broadcast Add, SCE, Reduce(Mean) VJPs and the grad_with_loss
/// plumbing all at once.
#[test]
fn dense_sce_mean_gradient_matches_numerical() {
    use rlx_ir::Philox4x32;
    let bs = 4usize;
    let k_in = 3usize;
    let c = 5usize;
    let mut rng = Philox4x32::new(7);
    let mut x = vec![0f32; bs * k_in];
    rng.fill_normal(&mut x);
    let mut w_init = vec![0f32; k_in * c];
    rng.fill_normal(&mut w_init);
    let mut b_init = vec![0f32; c];
    rng.fill_normal(&mut b_init);
    let labels: Vec<f32> = (0..bs).map(|i| (i % c) as f32).collect();

    // ── Forward graph: loss = mean(sce(x @ w + b, labels)) ──
    let f = DType::F32;
    let mut fwd = Graph::new("dense_sce");
    let xn = fwd.input("x", Shape::new(&[bs, k_in], f));
    let lb = fwd.input("labels", Shape::new(&[bs], f));
    let wp = fwd.param("w", Shape::new(&[k_in, c], f));
    let bp = fwd.param("b", Shape::new(&[c], f));
    let mm = fwd.matmul(xn, wp, Shape::new(&[bs, c], f));
    let logits = fwd.binary(BinaryOp::Add, mm, bp, Shape::new(&[bs, c], f));
    let loss_per = fwd.softmax_cross_entropy_with_logits(logits, lb);
    let loss = fwd.add_node(
        Op::Reduce {
            op: ReduceOp::Sum,
            axes: vec![0],
            keep_dim: false,
        },
        vec![loss_per],
        // Reduce sum of [bs] with axes=[0] keep_dim=false → scalar [].
        Shape::from_dims(&[], f),
    );
    // Use Sum + manual /bs scalar mul — also exercises BinaryOp::Mul VJP path
    // less aggressively than Mean would, and gives us a closed-form
    // reference for the loss we expect.
    // For simplicity though, switch to Mean which the tests should also cover.
    // (Re-using `loss` with Sum here for now; the mean factor cancels in
    // the gradient comparison since both analytical and numerical use the
    // same forward.)
    fwd.set_outputs(vec![loss]);

    // ── Backward graph ──
    let bwd_graph = rlx_opt::autodiff::grad_with_loss(&fwd, &[wp, bp]);
    // Outputs: [loss, grad_w, grad_b]. NodeIds for x/labels/w/b/loss
    // in bwd_graph match their fwd ids (the mirror keeps order).
    let d_out = bwd_graph
        .nodes()
        .iter()
        .find(|n| matches!(&n.op, Op::Input { name } if name == "d_output"))
        .map(|n| n.id)
        .expect("d_output input");

    let (sched, mut arena) = prepare(
        &bwd_graph,
        &[
            (xn, &x),
            (lb, &labels),
            (wp, &w_init),
            (bp, &b_init),
            (d_out, &[1.0]),
        ],
    );
    execute_thunks(&sched, arena.raw_buf_mut());

    let outs = &bwd_graph.outputs;
    let loss_id = outs[0];
    let gw_id = outs[1];
    let gb_id = outs[2];
    let loss_actual = read_arena(&arena, loss_id, 1)[0];
    let gw_actual = read_arena(&arena, gw_id, k_in * c);
    let gb_actual = read_arena(&arena, gb_id, c);

    // ── Forward-only graph for finite differences ──
    // Re-use the same `fwd` graph; set up its own arena and rerun
    // for each perturbed parameter.
    let plan = rlx_opt::memory::plan_memory(&fwd);
    let mut fwd_arena = crate::arena::Arena::from_plan(plan);
    let fwd_sched = compile_thunks(&fwd, &fwd_arena);
    write_arena(&mut fwd_arena, xn, &x);
    write_arena(&mut fwd_arena, lb, &labels);

    let run_loss = |arena: &mut crate::arena::Arena, w: &[f32], b: &[f32]| -> f32 {
        write_arena(arena, wp, w);
        write_arena(arena, bp, b);
        execute_thunks(&fwd_sched, arena.raw_buf_mut());
        read_arena(arena, loss, 1)[0]
    };

    // Sanity: the loss reported by the bwd graph matches the
    // forward-only graph on the unperturbed inputs.
    let loss_check = run_loss(&mut fwd_arena, &w_init, &b_init);
    assert!(
        (loss_actual - loss_check).abs() < 1e-4,
        "loss mismatch: bwd graph {loss_actual} vs fwd-only {loss_check}"
    );

    let eps = 1e-3f32;
    let mut w_perturbed = w_init.clone();
    let mut gw_numerical = vec![0f32; w_init.len()];
    for i in 0..w_init.len() {
        let saved = w_perturbed[i];
        w_perturbed[i] = saved + eps;
        let lp = run_loss(&mut fwd_arena, &w_perturbed, &b_init);
        w_perturbed[i] = saved - eps;
        let lm = run_loss(&mut fwd_arena, &w_perturbed, &b_init);
        w_perturbed[i] = saved;
        gw_numerical[i] = (lp - lm) / (2.0 * eps);
    }
    for (i, (a, n)) in gw_actual.iter().zip(&gw_numerical).enumerate() {
        assert!(
            (a - n).abs() < 5e-3,
            "grad_w[{i}]: analytical {a} vs numerical {n}"
        );
    }

    let mut b_perturbed = b_init.clone();
    let mut gb_numerical = vec![0f32; b_init.len()];
    for i in 0..b_init.len() {
        let saved = b_perturbed[i];
        b_perturbed[i] = saved + eps;
        let lp = run_loss(&mut fwd_arena, &w_init, &b_perturbed);
        b_perturbed[i] = saved - eps;
        let lm = run_loss(&mut fwd_arena, &w_init, &b_perturbed);
        b_perturbed[i] = saved;
        gb_numerical[i] = (lp - lm) / (2.0 * eps);
    }
    for (i, (a, n)) in gb_actual.iter().zip(&gb_numerical).enumerate() {
        assert!(
            (a - n).abs() < 5e-3,
            "grad_b[{i}]: analytical {a} vs numerical {n}"
        );
    }
}

/// Reduce::Mean specifically — verifies the 1/N scaling in the VJP.
/// The same dense+SCE graph but with Mean instead of Sum on the loss.
#[test]
fn dense_sce_mean_reduce_gradient_matches_numerical() {
    use rlx_ir::Philox4x32;
    let bs = 3usize;
    let k_in = 2usize;
    let c = 4usize;
    let mut rng = Philox4x32::new(13);
    let mut x = vec![0f32; bs * k_in];
    rng.fill_normal(&mut x);
    let mut w_init = vec![0f32; k_in * c];
    rng.fill_normal(&mut w_init);
    let labels: Vec<f32> = (0..bs).map(|i| (i % c) as f32).collect();

    let f = DType::F32;
    let mut fwd = Graph::new("dense_sce_mean");
    let xn = fwd.input("x", Shape::new(&[bs, k_in], f));
    let lb = fwd.input("labels", Shape::new(&[bs], f));
    let wp = fwd.param("w", Shape::new(&[k_in, c], f));
    let mm = fwd.matmul(xn, wp, Shape::new(&[bs, c], f));
    let loss_per = fwd.softmax_cross_entropy_with_logits(mm, lb);
    let loss = fwd.add_node(
        Op::Reduce {
            op: ReduceOp::Mean,
            axes: vec![0],
            keep_dim: false,
        },
        vec![loss_per],
        Shape::from_dims(&[], f),
    );
    fwd.set_outputs(vec![loss]);

    let bwd_graph = rlx_opt::autodiff::grad_with_loss(&fwd, &[wp]);
    let d_out = bwd_graph
        .nodes()
        .iter()
        .find(|n| matches!(&n.op, Op::Input { name } if name == "d_output"))
        .map(|n| n.id)
        .unwrap();

    let (sched, mut arena) = prepare(
        &bwd_graph,
        &[(xn, &x), (lb, &labels), (wp, &w_init), (d_out, &[1.0])],
    );
    execute_thunks(&sched, arena.raw_buf_mut());

    let outs = &bwd_graph.outputs;
    let loss_id = outs[0];
    let gw_id = outs[1];
    let _ = read_arena(&arena, loss_id, 1)[0];
    let gw_actual = read_arena(&arena, gw_id, k_in * c);

    let plan = rlx_opt::memory::plan_memory(&fwd);
    let mut fwd_arena = crate::arena::Arena::from_plan(plan);
    let fwd_sched = compile_thunks(&fwd, &fwd_arena);
    write_arena(&mut fwd_arena, xn, &x);
    write_arena(&mut fwd_arena, lb, &labels);

    let run_loss = |arena: &mut crate::arena::Arena, w: &[f32]| -> f32 {
        write_arena(arena, wp, w);
        execute_thunks(&fwd_sched, arena.raw_buf_mut());
        read_arena(arena, loss, 1)[0]
    };

    let eps = 1e-3f32;
    let mut wp_p = w_init.clone();
    let mut gw_num = vec![0f32; w_init.len()];
    for i in 0..w_init.len() {
        let s = wp_p[i];
        wp_p[i] = s + eps;
        let lp = run_loss(&mut fwd_arena, &wp_p);
        wp_p[i] = s - eps;
        let lm = run_loss(&mut fwd_arena, &wp_p);
        wp_p[i] = s;
        gw_num[i] = (lp - lm) / (2.0 * eps);
    }
    for (i, (a, n)) in gw_actual.iter().zip(&gw_num).enumerate() {
        assert!((a - n).abs() < 5e-3, "mean reduce grad_w[{i}]: {a} vs {n}");
    }
}
/// The full TinyConv-MNIST forward path (downsized) plumbed
/// through grad_with_loss. Validates that Conv, Pool(Max), ReLU,
/// Reshape, MatMul, Add (broadcast), SCE, Reduce(Mean) VJPs all
/// compose into a graph that produces correct gradients.
#[test]
fn tinyconv_full_gradient_matches_numerical() {
    use rlx_ir::Philox4x32;
    // Tiny shapes so finite differences finish in <1s.
    let n = 1usize;
    let c_in = 1usize;
    let h = 6usize;
    let w_in = 6usize;
    let c_mid = 2usize; // first conv output channels
    let kh = 3;
    let kw = 3;
    let h1 = h - kh + 1; // 4
    let w1 = w_in - kw + 1; // 4
    let h2 = h1 / 2;
    let w2 = w1 / 2; // 2 × 2 after 2× pool
    let flat = c_mid * h2 * w2; // 8
    let num_classes = 3usize;

    let mut rng = Philox4x32::new(31);
    let mut x = vec![0f32; n * c_in * h * w_in];
    rng.fill_normal(&mut x);
    let mut wc = vec![0f32; c_mid * c_in * kh * kw];
    rng.fill_normal(&mut wc);
    for v in wc.iter_mut() {
        *v *= 0.2;
    }
    // Shift conv-bias well away from the ReLU zero-boundary. Without
    // this, an ε-perturbation of bc[c] can flip the ReLU mask on a
    // pre-activation that happened to land near zero — making the
    // central-difference numerical gradient discontinuous and
    // diverge from the analytical (which assumes local smoothness).
    // +5.0 keeps every pre-activation positive for any random init
    // produced by Philox seed 31 with the wc/x scales used here, so
    // ReLU acts as an identity and finite differences are exact.
    let bc: Vec<f32> = (0..c_mid).map(|i| 5.0 + 0.1 * i as f32).collect();
    let mut wfc = vec![0f32; flat * num_classes];
    rng.fill_normal(&mut wfc);
    for v in wfc.iter_mut() {
        *v *= 0.5;
    }
    let mut bfc = vec![0f32; num_classes];
    rng.fill_normal(&mut bfc);
    let labels: Vec<f32> = vec![1.0]; // batch=1

    let f = DType::F32;
    let mut fwd = Graph::new("tinyconv");
    let xn = fwd.input("x", Shape::new(&[n, c_in, h, w_in], f));
    let lb = fwd.input("labels", Shape::new(&[n], f));
    let wcp = fwd.param("wc", Shape::new(&[c_mid, c_in, kh, kw], f));
    let bcp = fwd.param("bc", Shape::new(&[c_mid], f));
    let wfp = fwd.param("wfc", Shape::new(&[flat, num_classes], f));
    let bfp = fwd.param("bfc", Shape::new(&[num_classes], f));

    // conv: [n, c_in, h, w] → [n, c_mid, h1, w1]
    let conv = fwd.add_node(
        Op::Conv {
            kernel_size: vec![kh, kw],
            stride: vec![1, 1],
            padding: vec![0, 0],
            dilation: vec![1, 1],
            groups: 1,
        },
        vec![xn, wcp],
        Shape::new(&[n, c_mid, h1, w1], f),
    );
    // Bias add: expand bc[c_mid] up to the full [n, c_mid, h1, w1]
    // shape so the Add becomes a plain element-wise op. Going through
    // an explicit Reshape→Expand instead of relying on the Add to
    // broadcast `[1, C, 1, 1]` → `[N, C, H, W]` works around a known
    // limitation of `rlx-cpu`'s `Op::Binary` lowering: it dispatches
    // on `out_len % rhs_len == 0` and treats `rhs` as a last-axis
    // bias, which produces `bc[0], bc[1], bc[0], bc[1], …` alternating
    // across all positions instead of channel-broadcasting. Going
    // through Expand (a real broadcast thunk) avoids that path
    // entirely. The autodiff still exercises `unbroadcast` because
    // `Op::Expand`'s VJP reduces over the broadcast axes.
    let bc_4d = fwd.add_node(
        Op::Reshape {
            new_shape: vec![1, c_mid as i64, 1, 1],
        },
        vec![bcp],
        Shape::new(&[1, c_mid, 1, 1], f),
    );
    let bc_expanded = fwd.add_node(
        Op::Expand {
            target_shape: vec![n as i64, c_mid as i64, h1 as i64, w1 as i64],
        },
        vec![bc_4d],
        Shape::new(&[n, c_mid, h1, w1], f),
    );
    let conv_b = fwd.binary(
        BinaryOp::Add,
        conv,
        bc_expanded,
        Shape::new(&[n, c_mid, h1, w1], f),
    );
    let relu = fwd.activation(Activation::Relu, conv_b, Shape::new(&[n, c_mid, h1, w1], f));
    let pool = fwd.add_node(
        Op::Pool {
            kind: ReduceOp::Max,
            kernel_size: vec![2, 2],
            stride: vec![2, 2],
            padding: vec![0, 0],
        },
        vec![relu],
        Shape::new(&[n, c_mid, h2, w2], f),
    );
    let flatn = fwd.add_node(
        Op::Reshape {
            new_shape: vec![n as i64, flat as i64],
        },
        vec![pool],
        Shape::new(&[n, flat], f),
    );
    let mm = fwd.matmul(flatn, wfp, Shape::new(&[n, num_classes], f));
    let logits = fwd.binary(BinaryOp::Add, mm, bfp, Shape::new(&[n, num_classes], f));
    let loss_per = fwd.softmax_cross_entropy_with_logits(logits, lb);
    let loss = fwd.add_node(
        Op::Reduce {
            op: ReduceOp::Mean,
            axes: vec![0],
            keep_dim: false,
        },
        vec![loss_per],
        Shape::from_dims(&[], f),
    );
    fwd.set_outputs(vec![loss]);

    let bwd_graph = rlx_opt::autodiff::grad_with_loss(&fwd, &[wcp, bcp, wfp, bfp]);
    let d_out = bwd_graph
        .nodes()
        .iter()
        .find(|n| matches!(&n.op, Op::Input { name } if name == "d_output"))
        .map(|n| n.id)
        .unwrap();

    let (sched, mut arena) = prepare(
        &bwd_graph,
        &[
            (xn, &x),
            (lb, &labels),
            (wcp, &wc),
            (bcp, &bc),
            (wfp, &wfc),
            (bfp, &bfc),
            (d_out, &[1.0]),
        ],
    );
    execute_thunks(&sched, arena.raw_buf_mut());

    let outs = bwd_graph.outputs.clone();
    let loss_id = outs[0];
    let g_wc_id = outs[1];
    let g_bc_id = outs[2];
    let g_wfc_id = outs[3];
    let g_bfc_id = outs[4];
    let loss_actual = read_arena(&arena, loss_id, 1)[0];
    let g_wc = read_arena(&arena, g_wc_id, wc.len());
    let g_bc = read_arena(&arena, g_bc_id, bc.len());
    let g_wfc = read_arena(&arena, g_wfc_id, wfc.len());
    let g_bfc = read_arena(&arena, g_bfc_id, bfc.len());

    // Forward-only arena for finite differences.
    let plan = rlx_opt::memory::plan_memory(&fwd);
    let mut fwd_arena = crate::arena::Arena::from_plan(plan);
    let fwd_sched = compile_thunks(&fwd, &fwd_arena);
    write_arena(&mut fwd_arena, xn, &x);
    write_arena(&mut fwd_arena, lb, &labels);

    // Closure variant: we need to set all four params each call so
    // perturbations to one don't leak between sweeps.
    let run_loss = |arena: &mut crate::arena::Arena,
                    wc: &[f32],
                    bc: &[f32],
                    wfc: &[f32],
                    bfc: &[f32]|
     -> f32 {
        write_arena(arena, wcp, wc);
        write_arena(arena, bcp, bc);
        write_arena(arena, wfp, wfc);
        write_arena(arena, bfp, bfc);
        execute_thunks(&fwd_sched, arena.raw_buf_mut());
        read_arena(arena, loss, 1)[0]
    };

    let loss_check = run_loss(&mut fwd_arena, &wc, &bc, &wfc, &bfc);
    assert!(
        (loss_actual - loss_check).abs() < 1e-4,
        "tinyconv loss mismatch: bwd {loss_actual} vs fwd {loss_check}"
    );

    let eps = 1e-3f32;
    let check_grad = |arena: &mut crate::arena::Arena,
                      name: &str,
                      analytical: &[f32],
                      mut perturb: Box<
        dyn FnMut(&mut [f32], usize, f32, &mut crate::arena::Arena) -> f32 + '_,
    >,
                      n: usize| {
        for i in 0..n {
            let lp = perturb(&mut analytical.to_vec(), i, eps, arena);
            let lm = perturb(&mut analytical.to_vec(), i, -eps, arena);
            let num = (lp - lm) / (2.0 * eps);
            assert!(
                (analytical[i] - num).abs() < 5e-3,
                "{name}[{i}]: analytical {} vs numerical {num}",
                analytical[i]
            );
        }
    };

    // Helper to perturb one param and run forward. Kept as a
    // reference for the explicit per-param sweep pattern below.
    #[allow(unused_macros)]
    macro_rules! sweep {
        ($name:expr, $base:expr, $analytical:expr, $set_param:ident) => {{
            let n = $base.len();
            for i in 0..n {
                let mut p = $base.clone();
                let s = p[i];
                p[i] = s + eps;
                let lp = {
                    let $set_param = &p;
                    run_loss(&mut fwd_arena, &wc, &bc, &wfc, &bfc).max(f32::NEG_INFINITY);
                    // Reset others, set the one being swept, run.
                    // (the macro receives one of the four params via $set_param)
                    let _ = $set_param;
                    // Fall through to the explicit per-param helper:
                    0.0_f32
                };
                let _ = lp;
            }
        }};
    }
    let _ = check_grad; // silence unused (sweep! macro is intentionally\n        // unused — kept as reference for the per-param sweep pattern below)

    // Per-param sweeps (explicit, not macro — clearer).
    for i in 0..wc.len() {
        let mut p = wc.clone();
        let s = p[i];
        p[i] = s + eps;
        let lp = run_loss(&mut fwd_arena, &p, &bc, &wfc, &bfc);
        p[i] = s - eps;
        let lm = run_loss(&mut fwd_arena, &p, &bc, &wfc, &bfc);
        let num = (lp - lm) / (2.0 * eps);
        assert!(
            (g_wc[i] - num).abs() < 5e-3,
            "g_wc[{i}]: {} vs {num}",
            g_wc[i]
        );
    }
    for i in 0..bc.len() {
        let mut p = bc.clone();
        let s = p[i];
        p[i] = s + eps;
        let lp = run_loss(&mut fwd_arena, &wc, &p, &wfc, &bfc);
        p[i] = s - eps;
        let lm = run_loss(&mut fwd_arena, &wc, &p, &wfc, &bfc);
        let num = (lp - lm) / (2.0 * eps);
        assert!(
            (g_bc[i] - num).abs() < 5e-3,
            "g_bc[{i}]: {} vs {num}",
            g_bc[i]
        );
    }
    for i in 0..wfc.len() {
        let mut p = wfc.clone();
        let s = p[i];
        p[i] = s + eps;
        let lp = run_loss(&mut fwd_arena, &wc, &bc, &p, &bfc);
        p[i] = s - eps;
        let lm = run_loss(&mut fwd_arena, &wc, &bc, &p, &bfc);
        let num = (lp - lm) / (2.0 * eps);
        assert!(
            (g_wfc[i] - num).abs() < 5e-3,
            "g_wfc[{i}]: {} vs {num}",
            g_wfc[i]
        );
    }
    for i in 0..bfc.len() {
        let mut p = bfc.clone();
        let s = p[i];
        p[i] = s + eps;
        let lp = run_loss(&mut fwd_arena, &wc, &bc, &wfc, &p);
        p[i] = s - eps;
        let lm = run_loss(&mut fwd_arena, &wc, &bc, &wfc, &p);
        let num = (lp - lm) / (2.0 * eps);
        assert!(
            (g_bfc[i] - num).abs() < 5e-3,
            "g_bfc[{i}]: {} vs {num}",
            g_bfc[i]
        );
    }
}

/// Negative case: a Narrow whose output has multiple consumers
/// must NOT be fused (we can't elide its write — something else
/// reads it).
#[test]
fn narrow_rope_skips_when_narrow_has_multiple_consumers() {
    let f = DType::F32;
    let mut g = Graph::new("nr_skip");
    let qkv = g.input("qkv", Shape::new(&[16, 8, 192], f));
    let cos = g.input("cos", Shape::new(&[16], f));
    let sin = g.input("sin", Shape::new(&[16], f));
    let q = g.narrow_(qkv, 2, 0, 64);
    let q_rope = g.rope(q, cos, sin, 16);
    // Second consumer of `q` blocks the fusion.
    let q_dup = g.activation(rlx_ir::op::Activation::Relu, q, Shape::new(&[16, 8, 64], f));
    g.set_outputs(vec![q_rope, q_dup]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let narrow_count = sched
        .thunks
        .iter()
        .filter(|t| matches!(t, Thunk::Narrow { .. }))
        .count();
    assert!(
        narrow_count >= 1,
        "Narrow with multiple consumers must NOT be fused away"
    );
}

// ── Op::CustomFn (custom_vjp / custom_jvp) tests ──
//
// Validates: forward execution inlines fwd_body; VJP rule inlines
// vjp_body in place of recursing into fwd_body; JVP rule inlines
// jvp_body. Each test deliberately picks a body whose AD-via-tracing
// would yield a *different* gradient than the override, so we know
// the override actually fired.

/// Forward only: CustomFn wrapping `f(x) = x + c` (c=1 inside body)
/// without override AD bodies. Verifies the body is compiled,
/// constants in the body fill correctly, and the output lands at
/// the outer node's slot.
#[test]
fn custom_fn_forward_inlines_body() {
    let s = Shape::new(&[3], DType::F32);

    // Body: f(x) = x + 1
    let mut body = Graph::new("addone_body");
    let x = body.input("x", s.clone());
    let one_data: Vec<u8> = (0..3).flat_map(|_| 1.0_f32.to_le_bytes()).collect();
    let one = body.add_node(Op::Constant { data: one_data }, vec![], s.clone());
    let y = body.binary(BinaryOp::Add, x, one, s.clone());
    body.set_outputs(vec![y]);

    let mut g = Graph::new("custom_fn_outer");
    let xin = g.input("x_in", s.clone());
    let cf = g.custom_fn(vec![xin], body, None, None);
    g.set_outputs(vec![cf]);

    let xs = vec![10.0_f32, 20.0, 30.0];
    let (sched, mut arena) = prepare(&g, &[(xin, &xs)]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let got = read_arena(&arena, cf, 3);
    assert_eq!(got, vec![11.0, 21.0, 31.0]);
}

/// Locate an Op::Input or Op::Param by name in a graph.
fn find_named(graph: &Graph, want: &str) -> NodeId {
    for n in graph.nodes() {
        let name = match &n.op {
            Op::Input { name } | Op::Param { name } => Some(name.as_str()),
            _ => None,
        };
        if name == Some(want) {
            return n.id;
        }
    }
    panic!("no node named {want:?} in graph");
}

/// VJP override: f(x) = x but vjp_body returns 2 * d_output, so the
/// reported gradient should be 2 — different from the natural 1
/// you'd get by recursing into the identity body.
#[test]
fn custom_fn_vjp_overrides_natural_gradient() {
    use rlx_opt::autodiff::grad_with_loss;
    let s = Shape::new(&[1], DType::F32);

    let mut fwd = Graph::new("id_fwd");
    let x = fwd.input("x", s.clone());
    fwd.set_outputs(vec![x]);

    let mut vjp_g = Graph::new("id_vjp");
    let _x_p = vjp_g.input("x", s.clone());
    let _y_p = vjp_g.input("primal_output", s.clone());
    let dy = vjp_g.input("d_output", s.clone());
    let two_data: Vec<u8> = 2.0_f32.to_le_bytes().to_vec();
    let two = vjp_g.add_node(Op::Constant { data: two_data }, vec![], s.clone());
    let dx = vjp_g.binary(BinaryOp::Mul, dy, two, s.clone());
    vjp_g.set_outputs(vec![dx]);

    let mut g = Graph::new("outer");
    let xp = g.param("x", s.clone());
    let cf = g.custom_fn(vec![xp], fwd, Some(vjp_g), None);
    g.set_outputs(vec![cf]);

    let bwd = grad_with_loss(&g, &[xp]);
    assert_eq!(bwd.outputs.len(), 2, "expect [loss, dx]");

    let xb = find_named(&bwd, "x");
    let dout = find_named(&bwd, "d_output");
    let (sched, mut arena) = prepare(&bwd, &[(xb, &[7.0]), (dout, &[1.0])]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let loss = read_arena(&arena, bwd.outputs[0], 1);
    let dx_v = read_arena(&arena, bwd.outputs[1], 1);
    assert!((loss[0] - 7.0).abs() < 1e-6, "loss should be 7.0");
    assert!(
        (dx_v[0] - 2.0).abs() < 1e-6,
        "vjp override should yield dx=2.0, got {} (natural autodiff would give 1.0)",
        dx_v[0]
    );
}

/// VJP override: f(a, b) = a*b with vjp_body returning
/// (b * d_output, a * d_output). Validates routing of multiple
/// primals + d_output through the override; matches the natural
/// autodiff-of-Mul gradient (b, a).
#[test]
fn custom_fn_vjp_two_inputs_matches_mul_autodiff() {
    use rlx_opt::autodiff::grad_with_loss;
    let s = Shape::new(&[1], DType::F32);

    let mut fwd = Graph::new("mul_fwd");
    let a_f = fwd.input("a", s.clone());
    let b_f = fwd.input("b", s.clone());
    let y_f = fwd.binary(BinaryOp::Mul, a_f, b_f, s.clone());
    fwd.set_outputs(vec![y_f]);

    let mut vjp_g = Graph::new("mul_vjp");
    let a_v = vjp_g.input("a", s.clone());
    let b_v = vjp_g.input("b", s.clone());
    let _y_v = vjp_g.input("primal_output", s.clone());
    let dy_v = vjp_g.input("d_output", s.clone());
    let da = vjp_g.binary(BinaryOp::Mul, b_v, dy_v, s.clone());
    let db = vjp_g.binary(BinaryOp::Mul, a_v, dy_v, s.clone());
    vjp_g.set_outputs(vec![da, db]);

    let mut g = Graph::new("outer");
    let ap = g.param("a", s.clone());
    let bp = g.param("b", s.clone());
    let cf = g.custom_fn(vec![ap, bp], fwd, Some(vjp_g), None);
    g.set_outputs(vec![cf]);

    let bwd = grad_with_loss(&g, &[ap, bp]);
    assert_eq!(bwd.outputs.len(), 3, "expect [loss, da, db]");

    let ab = find_named(&bwd, "a");
    let bb = find_named(&bwd, "b");
    let dout = find_named(&bwd, "d_output");
    let (sched, mut arena) = prepare(&bwd, &[(ab, &[3.0]), (bb, &[5.0]), (dout, &[1.0])]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let loss = read_arena(&arena, bwd.outputs[0], 1);
    let da_v = read_arena(&arena, bwd.outputs[1], 1);
    let db_v = read_arena(&arena, bwd.outputs[2], 1);
    assert!((loss[0] - 15.0).abs() < 1e-5);
    assert!(
        (da_v[0] - 5.0).abs() < 1e-5,
        "da should be b=5.0, got {}",
        da_v[0]
    );
    assert!(
        (db_v[0] - 3.0).abs() < 1e-5,
        "db should be a=3.0, got {}",
        db_v[0]
    );
}

/// JVP override: f(x) = x but jvp_body returns 2 * tangent_0.
/// Forward-mode tangent should be 2x the seed (1.0) → 2.0.
#[test]
fn custom_fn_jvp_overrides_natural_tangent() {
    use rlx_opt::autodiff_fwd::jvp;
    let s = Shape::new(&[1], DType::F32);

    let mut fwd = Graph::new("id_fwd");
    let x = fwd.input("x", s.clone());
    fwd.set_outputs(vec![x]);

    let mut jvp_g = Graph::new("id_jvp");
    let _x_p = jvp_g.input("x", s.clone());
    let tx = jvp_g.input("tangent_0", s.clone());
    let two_data: Vec<u8> = 2.0_f32.to_le_bytes().to_vec();
    let two = jvp_g.add_node(Op::Constant { data: two_data }, vec![], s.clone());
    let ty = jvp_g.binary(BinaryOp::Mul, tx, two, s.clone());
    jvp_g.set_outputs(vec![ty]);

    let mut g = Graph::new("outer");
    let xin = g.input("x_in", s.clone());
    let cf = g.custom_fn(vec![xin], fwd, None, Some(jvp_g));
    g.set_outputs(vec![cf]);

    let fwd_g = jvp(&g, &[xin]);
    assert_eq!(fwd_g.outputs.len(), 2, "expect [primal_y, tangent_y]");

    let xb = find_named(&fwd_g, "x_in");
    let tan = find_named(&fwd_g, "tangent_x_in");
    let (sched, mut arena) = prepare(&fwd_g, &[(xb, &[7.0]), (tan, &[1.0])]);
    execute_thunks(&sched, arena.raw_buf_mut());
    let y = read_arena(&arena, fwd_g.outputs[0], 1);
    let ty_v = read_arena(&arena, fwd_g.outputs[1], 1);
    assert!((y[0] - 7.0).abs() < 1e-6);
    assert!(
        (ty_v[0] - 2.0).abs() < 1e-6,
        "jvp override should yield t_y=2.0 (natural autodiff would give 1.0), got {}",
        ty_v[0]
    );
}

/// IR-level basic test: `DType::C64` is wired through the dtype
/// table — `size_bytes() == 8`, `is_complex()` reports true, and
/// a `[2]`-shaped C64 buffer in the arena occupies the expected
/// 16 bytes.
#[test]
fn c64_dtype_storage_layout() {
    assert_eq!(
        DType::C64.size_bytes(),
        8,
        "C64 should be 8 bytes (f32 real + f32 imag)"
    );
    assert!(DType::C64.is_complex());
    assert!(!DType::C64.is_float());

    // A length-2 C64 buffer should have shape size_bytes = 16.
    let s = Shape::new(&[2], DType::C64);
    assert_eq!(s.size_bytes().unwrap(), 16);
}

// ── C64 element-wise binary kernel witnesses (2026-05-17) ──────
//
// Build a tiny graph: Input `a` + Input `b` (both C64 [2]),
// output = a OP b. Run through CompileResult and compare against
// the closed-form complex arithmetic on the four chosen pairs.

fn run_c64_binary(op: BinaryOp, a: &[(f32, f32)], b: &[(f32, f32)]) -> Vec<(f32, f32)> {
    let n = a.len();
    let s = Shape::new(&[n], DType::C64);
    let mut g = Graph::new("c64_bin");
    let in_a = g.input("a", s.clone());
    let in_b = g.input("b", s.clone());
    let out = g.binary(op, in_a, in_b, s.clone());
    g.set_outputs(vec![out]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);

    let a_off = arena.byte_offset(in_a);
    let b_off = arena.byte_offset(in_b);
    let out_off = arena.byte_offset(out);
    // Interleave [re_0, im_0, re_1, im_1, ...] in the f32 buffer.
    let buf = arena.raw_buf_mut();
    unsafe {
        let pa = buf.as_mut_ptr().add(a_off) as *mut f32;
        let pb = buf.as_mut_ptr().add(b_off) as *mut f32;
        for (i, &(re, im)) in a.iter().enumerate() {
            *pa.add(2 * i) = re;
            *pa.add(2 * i + 1) = im;
        }
        for (i, &(re, im)) in b.iter().enumerate() {
            *pb.add(2 * i) = re;
            *pb.add(2 * i + 1) = im;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let raw_out: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..(2 * n)).map(|i| *p.add(i)).collect()
    };
    (0..n)
        .map(|i| (raw_out[2 * i], raw_out[2 * i + 1]))
        .collect()
}

#[track_caller]
fn assert_close_c(got: (f32, f32), expected: (f32, f32), tol: f32, label: &str) {
    let dr = (got.0 - expected.0).abs();
    let di = (got.1 - expected.1).abs();
    assert!(
        dr < tol && di < tol,
        "[{label}] got ({:+.4}, {:+.4}), expected ({:+.4}, {:+.4})",
        got.0,
        got.1,
        expected.0,
        expected.1
    );
}

#[test]
fn c64_binary_add_matches_complex_arithmetic() {
    let a = [(1.0_f32, 2.0_f32), (3.0_f32, -1.0_f32)];
    let b = [(4.0_f32, -1.0_f32), (0.5_f32, 0.5_f32)];
    let out = run_c64_binary(BinaryOp::Add, &a, &b);
    assert_close_c(out[0], (5.0, 1.0), 1e-6, "add[0]");
    assert_close_c(out[1], (3.5, -0.5), 1e-6, "add[1]");
}

#[test]
fn c64_binary_sub_matches_complex_arithmetic() {
    let a = [(5.0_f32, 1.0_f32)];
    let b = [(2.0_f32, 3.0_f32)];
    let out = run_c64_binary(BinaryOp::Sub, &a, &b);
    assert_close_c(out[0], (3.0, -2.0), 1e-6, "sub");
}

#[test]
fn c64_binary_mul_matches_complex_arithmetic() {
    // (1 + 2i)(3 + 4i) = 3 + 4i + 6i + 8i² = -5 + 10i.
    let a = [(1.0_f32, 2.0_f32)];
    let b = [(3.0_f32, 4.0_f32)];
    let out = run_c64_binary(BinaryOp::Mul, &a, &b);
    assert_close_c(out[0], (-5.0, 10.0), 1e-5, "mul");
}

#[test]
fn c64_binary_div_matches_complex_arithmetic() {
    // (1 + 2i) / (3 + 4i) = ((1·3 + 2·4) + (2·3 − 1·4)i) / 25
    //                     = (11 + 2i) / 25
    //                     = 0.44 + 0.08i
    let a = [(1.0_f32, 2.0_f32)];
    let b = [(3.0_f32, 4.0_f32)];
    let out = run_c64_binary(BinaryOp::Div, &a, &b);
    assert_close_c(out[0], (0.44, 0.08), 1e-5, "div");
}

#[test]
fn c64_binary_mul_identity_one_is_no_op() {
    // (a + bi) · (1 + 0i) = a + bi.
    let a = [(3.5_f32, -1.25_f32), (-2.0_f32, 7.0_f32)];
    let b = [(1.0_f32, 0.0_f32), (1.0_f32, 0.0_f32)];
    let out = run_c64_binary(BinaryOp::Mul, &a, &b);
    assert_close_c(out[0], a[0], 1e-6, "mul·1[0]");
    assert_close_c(out[1], a[1], 1e-6, "mul·1[1]");
}

#[test]
fn c64_binary_mul_by_i_rotates_90_degrees() {
    // (a + bi) · i = (a + bi)(0 + i) = -b + ai. 90° CCW rotation.
    let a = [(1.0_f32, 0.0_f32)];
    let b = [(0.0_f32, 1.0_f32)];
    let out = run_c64_binary(BinaryOp::Mul, &a, &b);
    assert_close_c(out[0], (0.0, 1.0), 1e-6, "1·i");
}

#[test]
fn c64_binary_div_by_self_gives_unity() {
    let a = [(2.5_f32, -1.5_f32), (-0.7_f32, 4.2_f32)];
    let out = run_c64_binary(BinaryOp::Div, &a, &a);
    assert_close_c(out[0], (1.0, 0.0), 1e-5, "div_self[0]");
    assert_close_c(out[1], (1.0, 0.0), 1e-5, "div_self[1]");
}

#[test]
#[should_panic(expected = "C64: complex max/min/pow")]
fn c64_binary_max_is_rejected_at_lowering() {
    run_c64_binary(BinaryOp::Max, &[(1.0_f32, 2.0_f32)], &[(3.0_f32, 4.0_f32)]);
}

fn run_c64_activation(act: Activation, a: &[(f32, f32)]) -> Vec<(f32, f32)> {
    let n = a.len();
    let s = Shape::new(&[n], DType::C64);
    let mut g = Graph::new("c64_act");
    let in_a = g.input("a", s.clone());
    let out = g.activation(act, in_a, s.clone());
    g.set_outputs(vec![out]);
    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let a_off = arena.byte_offset(in_a);
    let out_off = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let pa = buf.as_mut_ptr().add(a_off) as *mut f32;
        for (i, &(re, im)) in a.iter().enumerate() {
            *pa.add(2 * i) = re;
            *pa.add(2 * i + 1) = im;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let raw: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..(2 * n)).map(|i| *p.add(i)).collect()
    };
    (0..n).map(|i| (raw[2 * i], raw[2 * i + 1])).collect()
}

#[test]
fn c64_activation_neg_negates_both_components() {
    let inp = [(3.5_f32, -1.25_f32), (-2.0_f32, 0.0_f32)];
    let out = run_c64_activation(Activation::Neg, &inp);
    assert_close_c(out[0], (-3.5, 1.25), 1e-6, "neg[0]");
    assert_close_c(out[1], (2.0, 0.0), 1e-6, "neg[1]");
}

#[test]
fn c64_activation_exp_matches_euler() {
    // exp(0 + i·π) = -1 + 0i.
    // exp(1 + 0i) = e ≈ 2.71828.
    let inp = [(0.0_f32, std::f32::consts::PI), (1.0_f32, 0.0_f32)];
    let out = run_c64_activation(Activation::Exp, &inp);
    assert_close_c(out[0], (-1.0, 0.0), 1e-5, "exp(iπ)");
    assert_close_c(out[1], (std::f32::consts::E, 0.0), 1e-5, "exp(1)");
}

#[test]
fn c64_activation_log_matches_principal_branch() {
    // log(1 + 0i) = 0.
    // log(0 + i) = log(1) + i·π/2 = 0 + i·π/2.
    // log(-1 + 0i) = 0 + i·π.
    let inp = [(1.0_f32, 0.0_f32), (0.0_f32, 1.0_f32), (-1.0_f32, 0.0_f32)];
    let out = run_c64_activation(Activation::Log, &inp);
    assert_close_c(out[0], (0.0, 0.0), 1e-5, "log(1)");
    assert_close_c(out[1], (0.0, std::f32::consts::FRAC_PI_2), 1e-5, "log(i)");
    assert_close_c(out[2], (0.0, std::f32::consts::PI), 1e-5, "log(-1)");
}

#[test]
fn c64_activation_sqrt_squared_recovers_input() {
    // For positive-real-part inputs, sqrt(z)² should equal z exactly
    // to f32 noise.
    let inp = [(4.0_f32, 0.0_f32), (3.0_f32, 4.0_f32)];
    let roots = run_c64_activation(Activation::Sqrt, &inp);
    // sqrt(4) = 2 + 0i; sqrt(3+4i) = 2 + i (since (2+i)² = 4+4i-1 = 3+4i).
    assert_close_c(roots[0], (2.0, 0.0), 1e-5, "sqrt(4)");
    assert_close_c(roots[1], (2.0, 1.0), 1e-5, "sqrt(3+4i)");
}

#[test]
#[should_panic(expected = "no natural complex extension")]
fn c64_activation_relu_is_rejected_at_lowering() {
    run_c64_activation(Activation::Relu, &[(1.0_f32, 2.0_f32)]);
}

// ── ComplexNormSq + Wirtinger backward witnesses ───────────────

/// Forward `|z|²`: returns `[n]` f32.
fn run_complex_norm_sq(z: &[(f32, f32)]) -> Vec<f32> {
    let n = z.len();
    let mut g = Graph::new("cns_fwd");
    let in_z = g.input("z", Shape::new(&[n], DType::C64));
    let out = g.complex_norm_sq(in_z);
    g.set_outputs(vec![out]);
    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let z_off = arena.byte_offset(in_z);
    let out_off = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let pz = buf.as_mut_ptr().add(z_off) as *mut f32;
        for (i, &(re, im)) in z.iter().enumerate() {
            *pz.add(2 * i) = re;
            *pz.add(2 * i + 1) = im;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..n).map(|i| *p.add(i)).collect()
    }
}

/// Backward: given z and upstream g, return dz = g·z element-wise (C64).
fn run_complex_norm_sq_bwd(z: &[(f32, f32)], g: &[f32]) -> Vec<(f32, f32)> {
    let n = z.len();
    let mut gr = Graph::new("cns_bwd");
    let in_z = gr.input("z", Shape::new(&[n], DType::C64));
    let in_g = gr.input("g", Shape::new(&[n], DType::F32));
    let out = gr.complex_norm_sq_backward(in_z, in_g);
    gr.set_outputs(vec![out]);
    let plan = rlx_opt::memory::plan_memory(&gr);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&gr, &arena);
    let z_off = arena.byte_offset(in_z);
    let g_off = arena.byte_offset(in_g);
    let out_off = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let pz = buf.as_mut_ptr().add(z_off) as *mut f32;
        let pg = buf.as_mut_ptr().add(g_off) as *mut f32;
        for (i, &(re, im)) in z.iter().enumerate() {
            *pz.add(2 * i) = re;
            *pz.add(2 * i + 1) = im;
        }
        for (i, &v) in g.iter().enumerate() {
            *pg.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..n).map(|i| (*p.add(2 * i), *p.add(2 * i + 1))).collect()
    }
}

#[test]
fn complex_norm_sq_matches_textbook() {
    // |3 + 4i|² = 9 + 16 = 25.
    // |1 + 0i|² = 1.
    // |0 + 0i|² = 0.
    let z = [(3.0_f32, 4.0_f32), (1.0_f32, 0.0_f32), (0.0_f32, 0.0_f32)];
    let out = run_complex_norm_sq(&z);
    assert!((out[0] - 25.0).abs() < 1e-5);
    assert!((out[1] - 1.0).abs() < 1e-6);
    assert!(out[2].abs() < 1e-6);
}

#[test]
fn complex_norm_sq_backward_matches_wirtinger_formula() {
    // Wirtinger: ∂|z|²/∂z̄ = z. With upstream g = 1, dz = z.
    let z = [(3.0_f32, 4.0_f32), (1.5_f32, -2.5_f32)];
    let g = [1.0_f32, 1.0_f32];
    let dz = run_complex_norm_sq_bwd(&z, &g);
    assert_close_c(dz[0], z[0], 1e-6, "dz[0] = g·z[0]");
    assert_close_c(dz[1], z[1], 1e-6, "dz[1] = g·z[1]");
}

#[test]
fn complex_norm_sq_backward_scales_with_upstream() {
    // With upstream g[i] ≠ 1: dz[i] = g[i]·z[i].
    let z = [(2.0_f32, 1.0_f32), (-1.0_f32, 3.0_f32)];
    let g = [0.5_f32, -2.0_f32];
    let dz = run_complex_norm_sq_bwd(&z, &g);
    assert_close_c(dz[0], (1.0, 0.5), 1e-6, "g=0.5 · (2,1)");
    assert_close_c(dz[1], (2.0, -6.0), 1e-6, "g=-2 · (-1,3)");
}

/// Multi-output Op::CustomFn via the concat-with-Narrow design
/// (rlx-ir::Graph::custom_fn_multi). Build a custom_fn whose
/// fwd_body returns two outputs (x², 2x), then materialize each
/// via the MultiOutputHandle and verify both numerically.
#[test]
fn custom_fn_multi_extracts_each_subgraph_output() {
    use rlx_ir::ops::special::MultiOutputHandle;

    let _ = MultiOutputHandle {
        source: NodeId(0),
        sub_shapes: vec![],
        offsets: vec![],
    }; // import sanity

    // Inner body: input x [3] f32, outputs (x², 2x) both [3] f32.
    let mut body = Graph::new("multi_body");
    let s3 = Shape::new(&[3], DType::F32);
    let x = body.input("x", s3.clone());
    let x_sq = body.binary(BinaryOp::Mul, x, x, s3.clone());
    let two = body.add_node(
        Op::Constant {
            data: vec![
                2.0_f32.to_le_bytes(),
                2.0_f32.to_le_bytes(),
                2.0_f32.to_le_bytes(),
            ]
            .into_iter()
            .flatten()
            .collect(),
        },
        vec![],
        s3.clone(),
    );
    let two_x = body.binary(BinaryOp::Mul, two, x, s3.clone());
    body.set_outputs(vec![x_sq, two_x]);

    // Outer graph: feed in_x → custom_fn_multi → handle.output(0/1).
    let mut outer = Graph::new("multi_outer");
    let in_x = outer.input("xin", s3.clone());
    let handle = outer.custom_fn_multi(vec![in_x], body);
    assert_eq!(handle.n_outputs(), 2);
    let out0 = handle.output(&mut outer, 0); //    let out1 = handle.output(&mut outer, 1); // 2x
    outer.set_outputs(vec![out0, out1]);

    let plan = rlx_opt::memory::plan_memory(&outer);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&outer, &arena);
    let xin_off = arena.byte_offset(in_x);
    let out0_off = arena.byte_offset(out0);
    let out1_off = arena.byte_offset(out1);
    let xs = [1.0_f32, 2.0, 3.0];
    unsafe {
        let p = arena.raw_buf_mut().as_mut_ptr().add(xin_off) as *mut f32;
        for (i, &v) in xs.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let out0_v: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out0_off) as *const f32;
        (0..3).map(|i| *p.add(i)).collect()
    };
    let out1_v: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out1_off) as *const f32;
        (0..3).map(|i| *p.add(i)).collect()
    };
    // x² = [1, 4, 9]; 2x = [2, 4, 6].
    for i in 0..3 {
        assert!(
            (out0_v[i] - xs[i] * xs[i]).abs() < 1e-5,
            "out0[{i}] = {} != x² = {}",
            out0_v[i],
            xs[i] * xs[i]
        );
        assert!(
            (out1_v[i] - 2.0 * xs[i]).abs() < 1e-5,
            "out1[{i}] = {} != 2x = {}",
            out1_v[i],
            2.0 * xs[i]
        );
    }
}

#[test]
fn complex_norm_sq_gradient_matches_finite_difference() {
    // Numerical sanity: perturb z[0].re by ε, observe Δ|z|² ≈ 2·re·ε.
    let z = [(3.0_f32, 4.0_f32)];
    let eps = 1e-3_f32;
    let v0 = run_complex_norm_sq(&z)[0];
    let z_pert = [(3.0_f32 + eps, 4.0_f32)];
    let v1 = run_complex_norm_sq(&z_pert)[0];
    let fd_re = (v1 - v0) / eps;
    let analytic_re = 2.0 * z[0].0;
    assert!((fd_re - analytic_re).abs() < 1e-2);

    // ∂/∂im at z = (3, 4) is 2·im = 8.
    let z_pert_im = [(3.0_f32, 4.0_f32 + eps)];
    let v2 = run_complex_norm_sq(&z_pert_im)[0];
    let fd_im = (v2 - v0) / eps;
    let analytic_im = 2.0 * z[0].1;
    assert!((fd_im - analytic_im).abs() < 1e-2);

    // Compare with the Wirtinger backward at upstream g = 1.
    // Wirtinger ∂/∂z̄ = z gives dz = (re, im). The "real
    // gradient" wrt (re, im) is 2·(re, im), i.e. 2·dz = (2·re,
    // 2·im) — that's the factor 2 difference between Wirtinger
    // ∂/∂z̄ and the real-vector gradient on (re, im).
    let dz = run_complex_norm_sq_bwd(&z, &[1.0_f32]);
    assert!((2.0 * dz[0].0 - analytic_re).abs() < 1e-5);
    assert!((2.0 * dz[0].1 - analytic_im).abs() < 1e-5);
}

/// Direct regression test for the 5-D mid-shape singleton broadcast
/// (SAM rel_pos pattern: `[bh, h, w, 1, w] + [bh, h, w, h, w]`).
/// The SAM port worked around this by `concat`-tiling the rhs; this
/// test verifies the in-graph broadcast path is bit-correct.
#[test]
fn binary_full_5d_mid_singleton_broadcast() {
    let bh = 2usize;
    let h = 3;
    let w = 4;
    let f = DType::F32;

    let mut g = Graph::new("bcast_5d");
    let lhs = g.input("lhs", Shape::new(&[bh, h, w, h, w], f));
    // rhs shape with size-1 at axis 3 (mid-shape singleton).
    let rhs = g.input("rhs", Shape::new(&[bh, h, w, 1, w], f));
    let out = g.binary(BinaryOp::Add, lhs, rhs, Shape::new(&[bh, h, w, h, w], f));
    g.set_outputs(vec![out]);

    // Deterministic data.
    let lhs_data: Vec<f32> = (0..bh * h * w * h * w).map(|i| i as f32 * 0.01).collect();
    let rhs_data: Vec<f32> = (0..bh * h * w * w)
        .map(|i| (i as f32 + 100.0) * 0.01)
        .collect();

    // Compute expected output by hand.
    let mut expected = vec![0f32; bh * h * w * h * w];
    for b_ in 0..bh {
        for hq in 0..h {
            for wq in 0..w {
                for hk in 0..h {
                    for wk in 0..w {
                        let li = (((b_ * h + hq) * w + wq) * h + hk) * w + wk;
                        // rhs has hk dim = 1, so it's always index 0 there.
                        let ri = ((b_ * h + hq) * w + wq) * w + wk;
                        expected[li] = lhs_data[li] + rhs_data[ri];
                    }
                }
            }
        }
    }

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let lhs_off = arena.byte_offset(lhs);
    let rhs_off = arena.byte_offset(rhs);
    let out_off = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let p = buf.as_mut_ptr().add(lhs_off) as *mut f32;
        for (i, &v) in lhs_data.iter().enumerate() {
            *p.add(i) = v;
        }
        let p = buf.as_mut_ptr().add(rhs_off) as *mut f32;
        for (i, &v) in rhs_data.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..bh * h * w * h * w).map(|i| *p.add(i)).collect()
    };

    // Bit-exact check.
    let mut max_diff = 0f32;
    let mut max_idx = 0;
    for i in 0..actual.len() {
        let d = (actual[i] - expected[i]).abs();
        if d > max_diff {
            max_diff = d;
            max_idx = i;
        }
    }
    assert!(
        max_diff < 1e-6,
        "5D mid-shape singleton broadcast wrong: max |Δ| = {max_diff} at idx {max_idx} \
             (actual={}, expected={})",
        actual[max_idx],
        expected[max_idx]
    );
}

#[test]
fn layer_norm2d_and_conv_transpose2d_kernels() {
    let mut out = vec![0f32; 8];
    crate::kernels::layer_norm2d_nchw(
        &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
        &[1.0, 1.0],
        &[0.0, 0.0],
        &mut out,
        1,
        2,
        2,
        2,
        1e-5,
    );
    let mean0: f32 = (1.0 + 3.0) / 2.0;
    assert!((out[0] - mean0).abs() > 0.1);

    let mut up = vec![0f32; 4];
    crate::kernels::conv_transpose2d_nchw(
        &[2.0],
        &[1.0, 0.0, 0.0, 1.0],
        &mut up,
        1,
        1,
        1,
        1,
        1,
        2,
        2,
        2,
        2,
        2,
        2,
        0,
        0,
        1,
        1,
        1,
    );
    assert!((up[0] - 2.0).abs() < 1e-5);
    assert!((up[3] - 2.0).abs() < 1e-5);
}

/// End-to-end native-low-precision GEMM oracle: build the full
/// ScaledQuantScale → ScaledQuantize → ScaledMatMul pipeline through the
/// thunk path and check the f32-accumulated result tracks a plain f32 TN
/// matmul (cosine), for every format × scale-layout. This exercises shape
/// inference, memory planning, the build arms, and both execute paths.
#[test]
fn scaled_matmul_oracle_matches_f32() {
    use rlx_ir::ScaledFormat::*;
    use rlx_ir::{ScaleLayout, ScaledFormat};

    fn cosine(a: &[f32], b: &[f32]) -> f32 {
        let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
        let na = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let nb = b.iter().map(|x| x * x).sum::<f32>().sqrt();
        dot / (na * nb)
    }

    #[allow(clippy::too_many_arguments)]
    fn run_scaled(
        lhs: &[f32],
        rhs: &[f32],
        m: usize,
        k: usize,
        n: usize,
        lf: ScaledFormat,
        rf: ScaledFormat,
        layout: ScaleLayout,
    ) -> Vec<f32> {
        let f = DType::F32;
        let u8t = DType::U8;
        let mut g = Graph::new("scaled");
        let lhs_in = g.input("lhs", Shape::new(&[m, k], f));
        let rhs_in = g.input("rhs", Shape::new(&[n, k], f));
        let (ls_shape, rs_shape) = match layout {
            ScaleLayout::PerTensor => (Shape::new(&[1], f), Shape::new(&[1], f)),
            _ => {
                let nb = k.div_ceil(layout.block() as usize);
                (Shape::new(&[m, nb], u8t), Shape::new(&[n, nb], u8t))
            }
        };
        let ls = g.add_node(
            Op::ScaledQuantScale {
                format: lf,
                scale_layout: layout,
            },
            vec![lhs_in],
            ls_shape,
        );
        let lq = g.add_node(
            Op::ScaledQuantize {
                format: lf,
                scale_layout: layout,
            },
            vec![lhs_in, ls],
            Shape::new(&[m, k], u8t),
        );
        let rs = g.add_node(
            Op::ScaledQuantScale {
                format: rf,
                scale_layout: layout,
            },
            vec![rhs_in],
            rs_shape,
        );
        let rq = g.add_node(
            Op::ScaledQuantize {
                format: rf,
                scale_layout: layout,
            },
            vec![rhs_in, rs],
            Shape::new(&[n, k], u8t),
        );
        let out = g.add_node(
            Op::ScaledMatMul {
                lhs_format: lf,
                rhs_format: rf,
                scale_layout: layout,
                has_bias: false,
            },
            vec![lq, rq, ls, rs],
            Shape::new(&[m, n], f),
        );
        g.set_outputs(vec![out]);

        let plan = rlx_opt::memory::plan_memory(&g);
        let mut arena = crate::arena::Arena::from_plan(plan);
        let sched = compile_thunks(&g, &arena);
        let lhs_off = arena.byte_offset(lhs_in);
        let rhs_off = arena.byte_offset(rhs_in);
        let out_off = arena.byte_offset(out);
        let buf = arena.raw_buf_mut();
        unsafe {
            let lp = buf.as_mut_ptr().add(lhs_off) as *mut f32;
            for (i, &v) in lhs.iter().enumerate() {
                *lp.add(i) = v;
            }
            let rp = buf.as_mut_ptr().add(rhs_off) as *mut f32;
            for (i, &v) in rhs.iter().enumerate() {
                *rp.add(i) = v;
            }
        }
        execute_thunks(&sched, arena.raw_buf_mut());
        unsafe {
            let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
            (0..m * n).map(|i| *p.add(i)).collect()
        }
    }

    let (m, k, n) = (4usize, 64usize, 8usize);
    let lhs: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.13).sin() * 1.5).collect();
    let rhs: Vec<f32> = (0..n * k).map(|i| (i as f32 * 0.07).cos() * 1.2).collect();
    let mut reference = vec![0f32; m * n];
    for i in 0..m {
        for j in 0..n {
            let mut acc = 0f32;
            for p in 0..k {
                acc += lhs[i * k + p] * rhs[j * k + p];
            }
            reference[i * n + j] = acc;
        }
    }

    // Per-tensor scaling across all 7 element formats.
    let cases = [
        (F8E4M3, 0.999f32),
        (F8E5M2, 0.99),
        (F8E4M3Fnuz, 0.999),
        (F8E5M2Fnuz, 0.99),
        (F6E2M3, 0.99),
        (F6E3M2, 0.98),
        (F4E2M1, 0.90),
    ];
    for (fmt, thresh) in cases {
        let out = run_scaled(&lhs, &rhs, m, k, n, fmt, fmt, ScaleLayout::PerTensor);
        let c = cosine(&out, &reference);
        assert!(c >= thresh, "{fmt} per-tensor cosine {c} < {thresh}");
    }

    // Block layouts: MX E8M0 (FP8) and NVFP4 (FP4) — finer scaling, higher fidelity.
    let out_mx = run_scaled(&lhs, &rhs, m, k, n, F8E4M3, F8E4M3, ScaleLayout::mx());
    let c_mx = cosine(&out_mx, &reference);
    assert!(c_mx >= 0.999, "mx-e8m0 e4m3 cosine {c_mx}");
    let out_nv = run_scaled(&lhs, &rhs, m, k, n, F4E2M1, F4E2M1, ScaleLayout::nvfp4());
    let c_nv = cosine(&out_nv, &reference);
    assert!(c_nv >= 0.95, "nvfp4 e2m1 cosine {c_nv}");
}

/// `Op::ScaledDequantize` (`decode(code)·scale`) must invert
/// `Op::ScaledQuantize`: a quantize→dequantize round-trip reconstructs the
/// original f32 within the format's resolution. Exercises the standalone
/// dequantizer the `ScaledMatMul` backward graph relies on.
#[test]
fn scaled_dequantize_inverts_quantize() {
    use rlx_ir::ScaledFormat::*;
    use rlx_ir::{ScaleLayout, ScaledFormat};

    fn cosine(a: &[f32], b: &[f32]) -> f32 {
        let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
        let na = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let nb = b.iter().map(|x| x * x).sum::<f32>().sqrt();
        dot / (na * nb)
    }

    fn roundtrip(x: &[f32], rows: usize, cols: usize, fmt: ScaledFormat) -> Vec<f32> {
        let f = DType::F32;
        let u8t = DType::U8;
        let layout = ScaleLayout::PerTensor;
        let mut g = Graph::new("dequant_rt");
        let x_in = g.input("x", Shape::new(&[rows, cols], f));
        let scale = g.add_node(
            Op::ScaledQuantScale {
                format: fmt,
                scale_layout: layout,
            },
            vec![x_in],
            Shape::new(&[1], f),
        );
        let codes = g.add_node(
            Op::ScaledQuantize {
                format: fmt,
                scale_layout: layout,
            },
            vec![x_in, scale],
            Shape::new(&[rows, cols], u8t),
        );
        let recon = g.add_node(
            Op::ScaledDequantize {
                format: fmt,
                scale_layout: layout,
            },
            vec![codes, scale],
            Shape::new(&[rows, cols], f),
        );
        g.set_outputs(vec![recon]);

        let plan = rlx_opt::memory::plan_memory(&g);
        let mut arena = crate::arena::Arena::from_plan(plan);
        let sched = compile_thunks(&g, &arena);
        let x_off = arena.byte_offset(x_in);
        let r_off = arena.byte_offset(recon);
        unsafe {
            let p = arena.raw_buf_mut().as_mut_ptr().add(x_off) as *mut f32;
            for (i, &v) in x.iter().enumerate() {
                *p.add(i) = v;
            }
        }
        execute_thunks(&sched, arena.raw_buf_mut());
        unsafe {
            let p = arena.raw_buf().as_ptr().add(r_off) as *const f32;
            (0..rows * cols).map(|i| *p.add(i)).collect()
        }
    }

    let (rows, cols) = (4usize, 16usize);
    let x: Vec<f32> = (0..rows * cols)
        .map(|i| (i as f32 * 0.21).sin() * 1.7)
        .collect();
    // FP8 reconstructs tightly; FP4 is coarse but still strongly correlated.
    for (fmt, min_cos) in [(F8E4M3, 0.999f32), (F8E5M2, 0.99), (F4E2M1, 0.93)] {
        let recon = roundtrip(&x, rows, cols, fmt);
        assert_eq!(recon.len(), x.len());
        assert!(
            recon.iter().all(|v| v.is_finite()),
            "{fmt:?} produced non-finite"
        );
        let c = cosine(&recon, &x);
        assert!(c >= min_cos, "{fmt:?} round-trip cosine {c} < {min_cos}");
    }
}

/// A parameterized `Custom` minifloat (`f4e3m0` — 3 exp, 0 mant: a signed
/// power-of-two grid) must run end-to-end through the real quantize →
/// dequantize graph on the CPU executor. Values drawn from the format's own
/// grid — with ±16 present so the per-tensor scale is exactly 1 — must
/// reconstruct bit-exactly, proving the generic decode/encode path that the
/// graph, the CPU backend, and the Metal host-fallback all share works for
/// an arbitrary (exp, mant) split, not just the seven named formats.
#[test]
fn scaled_custom_f4e3m0_round_trip_is_exact() {
    use rlx_ir::{ScaleLayout, ScaledFormat};

    let fmt = ScaledFormat::custom(3, 0); // f4e3m0
    assert_eq!(fmt.to_string(), "f4e3m0");
    let (rows, cols) = (3usize, 8usize);
    // Grid: 0 and ±{0.25,0.5,1,2,4,8,16}. ±16 present → amax 16 → scale 1.
    let grid = [16.0f32, -8.0, 4.0, -2.0, 1.0, -0.5, 0.25, 0.0];
    let x: Vec<f32> = (0..rows * cols).map(|i| grid[i % grid.len()]).collect();

    let f = DType::F32;
    let u8t = DType::U8;
    let layout = ScaleLayout::PerTensor;
    let mut g = Graph::new("f4e3m0_rt");
    let x_in = g.input("x", Shape::new(&[rows, cols], f));
    let scale = g.add_node(
        Op::ScaledQuantScale {
            format: fmt,
            scale_layout: layout,
        },
        vec![x_in],
        Shape::new(&[1], f),
    );
    let codes = g.add_node(
        Op::ScaledQuantize {
            format: fmt,
            scale_layout: layout,
        },
        vec![x_in, scale],
        Shape::new(&[rows, cols], u8t),
    );
    let recon = g.add_node(
        Op::ScaledDequantize {
            format: fmt,
            scale_layout: layout,
        },
        vec![codes, scale],
        Shape::new(&[rows, cols], f),
    );
    g.set_outputs(vec![recon]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let x_off = arena.byte_offset(x_in);
    let r_off = arena.byte_offset(recon);
    unsafe {
        let p = arena.raw_buf_mut().as_mut_ptr().add(x_off) as *mut f32;
        for (i, &v) in x.iter().enumerate() {
            *p.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let recon_vals: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(r_off) as *const f32;
        (0..rows * cols).map(|i| *p.add(i)).collect()
    };
    assert_eq!(recon_vals, x, "f4e3m0 grid values must round-trip exactly");
}

/// The ergonomic `Graph::scaled_matmul` builder — one call composes the whole
/// ScaledQuantScale→ScaledQuantize→ScaledMatMul chain from a `ScaledFormat` +
/// `ScaleLayout` — must produce a graph that runs and tracks the f32 matmul.
#[test]
fn scaled_matmul_builder_helper_tracks_f32() {
    use rlx_ir::{ScaleLayout, ScaledFormat};

    let (m, k, n) = (4usize, 64usize, 8usize);
    let lhs: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.13).sin() * 1.5).collect();
    let rhs: Vec<f32> = (0..n * k).map(|i| (i as f32 * 0.07).cos() * 1.2).collect();

    let mut g = Graph::new("scaled_builder");
    let lhs_in = g.input("lhs", Shape::new(&[m, k], DType::F32));
    let rhs_in = g.input("rhs", Shape::new(&[n, k], DType::F32));
    // One call instead of hand-wiring five ops.
    let y = g.scaled_matmul(
        lhs_in,
        rhs_in,
        ScaledFormat::custom(3, 0),
        ScaleLayout::mx(),
    );
    g.set_outputs(vec![y]);

    // Builder wired the expected op chain.
    let count = |k: rlx_ir::OpKind| g.nodes().iter().filter(|nd| nd.op.kind() == k).count();
    assert_eq!(count(rlx_ir::OpKind::ScaledMatMul), 1);
    assert_eq!(count(rlx_ir::OpKind::ScaledQuantize), 2);
    assert_eq!(count(rlx_ir::OpKind::ScaledQuantScale), 2);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let lhs_off = arena.byte_offset(lhs_in);
    let rhs_off = arena.byte_offset(rhs_in);
    let y_off = arena.byte_offset(y);
    unsafe {
        let p = arena.raw_buf_mut().as_mut_ptr();
        let lp = p.add(lhs_off) as *mut f32;
        for (i, &v) in lhs.iter().enumerate() {
            *lp.add(i) = v;
        }
        let rp = p.add(rhs_off) as *mut f32;
        for (i, &v) in rhs.iter().enumerate() {
            *rp.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let out: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(y_off) as *const f32;
        (0..m * n).map(|i| *p.add(i)).collect()
    };

    // Reference f32 matmul (TN).
    let mut reference = vec![0f32; m * n];
    for i in 0..m {
        for j in 0..n {
            let mut acc = 0f32;
            for p in 0..k {
                acc += lhs[i * k + p] * rhs[j * k + p];
            }
            reference[i * n + j] = acc;
        }
    }
    let dot: f32 = out.iter().zip(&reference).map(|(a, b)| a * b).sum();
    let na = out.iter().map(|x| x * x).sum::<f32>().sqrt();
    let nb = reference.iter().map(|x| x * x).sum::<f32>().sqrt();
    let cos = dot / (na * nb);
    assert!(cos >= 0.9, "scaled_matmul builder cosine {cos} < 0.9");
}

/// `Op::Fma` computes the single-rounded `a*b + c` elementwise. Verify it
/// matches `f32::mul_add` (the hardware FMA), and that the `LowerFma`
/// fallback (`Mul` + `Add`) stays close on a benign case.
#[test]
fn fma_matches_mul_add() {
    let f = DType::F32;
    let n = 9usize;
    let a: Vec<f32> = vec![1.5, -2.0, 0.0, 3.25, -1.1, 7.0, -0.5, 2.2, 9.9];
    let b: Vec<f32> = vec![2.0, 0.5, 4.0, -1.0, 6.0, -2.5, 8.0, -3.3, 0.1];
    let c: Vec<f32> = vec![0.25, 1.0, -3.0, 2.0, -0.5, 4.0, 1.5, -2.2, 0.0];

    let mut g = Graph::new("fma");
    let an = g.input("a", Shape::new(&[n], f));
    let bn = g.input("b", Shape::new(&[n], f));
    let cn = g.input("c", Shape::new(&[n], f));
    let out = g.add_node(Op::Fma, vec![an, bn, cn], Shape::new(&[n], f));
    g.set_outputs(vec![out]);

    let actual = run_graph(&g, &[(an, &a), (bn, &b), (cn, &c)], out, n);
    for i in 0..n {
        let expected = a[i].mul_add(b[i], c[i]);
        assert!(
            (actual[i] - expected).abs() <= f32::EPSILON * (1.0 + expected.abs()),
            "fma[{i}]: {} vs mul_add {expected}",
            actual[i]
        );
    }
}

/// End-to-end AMP-FP8: take a plain `MatMul` graph, run the
/// `insert_scaled_matmul` compile pass, then execute the rewritten graph on
/// CPU and confirm it tracks the f32 matmul. Proves the pass emits a
/// runnable, numerically-sound graph (rhs transpose + dynamic quantize).
#[test]
fn scaled_quant_pass_runs_end_to_end() {
    use rlx_opt::rlx_compile::scaled_quant_insert::{ScaledQuantConfig, insert_scaled_matmul};

    let f = DType::F32;
    let (m, k, n) = (3usize, 16usize, 5usize);
    let mut g = Graph::new("amp_fp8");
    let x = g.input("x", Shape::new(&[m, k], f));
    let w = g.param("w", Shape::new(&[k, n], f));
    let mm = g.matmul(x, w, Shape::new(&[m, n], f));
    g.set_outputs(vec![mm]);

    let g = insert_scaled_matmul(g, ScaledQuantConfig::fp8_e4m3());

    let x_data: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.11).sin()).collect();
    let w_data: Vec<f32> = (0..k * n).map(|i| (i as f32 * 0.05).cos()).collect();
    // reference NN matmul: out[i,j] = Σ_p x[i,p]·w[p,j]
    let mut reference = vec![0f32; m * n];
    for i in 0..m {
        for j in 0..n {
            let mut acc = 0f32;
            for p in 0..k {
                acc += x_data[i * k + p] * w_data[p * n + j];
            }
            reference[i * n + j] = acc;
        }
    }

    // Locate the (preserved) input/param + output nodes in the rewritten graph.
    let mut x_id = None;
    let mut w_id = None;
    for node in g.nodes() {
        match &node.op {
            Op::Input { name } if name == "x" => x_id = Some(node.id),
            Op::Param { name } if name == "w" => w_id = Some(node.id),
            _ => {}
        }
    }
    let (x_id, w_id) = (x_id.unwrap(), w_id.unwrap());
    let out_id = g.outputs[0];

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let x_off = arena.byte_offset(x_id);
    let w_off = arena.byte_offset(w_id);
    let out_off = arena.byte_offset(out_id);
    let buf = arena.raw_buf_mut();
    unsafe {
        let xp = buf.as_mut_ptr().add(x_off) as *mut f32;
        for (i, &v) in x_data.iter().enumerate() {
            *xp.add(i) = v;
        }
        let wp = buf.as_mut_ptr().add(w_off) as *mut f32;
        for (i, &v) in w_data.iter().enumerate() {
            *wp.add(i) = v;
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(out_off) as *const f32;
        (0..m * n).map(|i| *p.add(i)).collect()
    };

    let dot: f32 = actual.iter().zip(&reference).map(|(a, b)| a * b).sum();
    let na = actual.iter().map(|x| x * x).sum::<f32>().sqrt();
    let nb = reference.iter().map(|x| x * x).sum::<f32>().sqrt();
    let cos = dot / (na * nb);
    assert!(cos >= 0.999, "AMP-fp8 e2e cosine {cos}");
}

// ── DiT modulation ops (AdaLayerNorm / GatedResidual) ───────────────────

/// `Op::AdaLayerNorm` native CPU kernel must match the reference
/// `norm(x)·(1+scale)+shift` for both LayerNorm and RMSNorm flavors, with
/// the `[B,1,D]` modulation broadcast over the sequence axis.
#[test]
fn ada_layer_norm_matches_reference() {
    use rlx_ir::infer::GraphExt;
    use rlx_ir::op::AdaNormKind;
    let f = DType::F32;
    let (bch, s, d) = (2usize, 5usize, 8usize);
    let eps = 1e-5f32;

    let mut seed: u32 = 0x1234_5678;
    let mut rand = || {
        seed ^= seed << 13;
        seed ^= seed >> 17;
        seed ^= seed << 5;
        (seed as f32 / u32::MAX as f32) - 0.5
    };
    let x: Vec<f32> = (0..bch * s * d).map(|_| rand()).collect();
    let scale: Vec<f32> = (0..bch * d).map(|_| rand()).collect(); // [B,1,D]
    let shift: Vec<f32> = (0..bch * d).map(|_| rand()).collect();

    for &ln in &[true, false] {
        // Reference.
        let mut expected = vec![0f32; bch * s * d];
        for b in 0..bch {
            for si in 0..s {
                let row = &x[(b * s + si) * d..(b * s + si) * d + d];
                let (mean, inv) = if ln {
                    let mean = row.iter().sum::<f32>() / d as f32;
                    let var = row.iter().map(|v| (v - mean) * (v - mean)).sum::<f32>() / d as f32;
                    (mean, 1.0 / (var + eps).sqrt())
                } else {
                    let ms = row.iter().map(|v| v * v).sum::<f32>() / d as f32;
                    (0f32, 1.0 / (ms + eps).sqrt())
                };
                for di in 0..d {
                    let n = (row[di] - mean) * inv;
                    expected[(b * s + si) * d + di] =
                        n * (1.0 + scale[b * d + di]) + shift[b * d + di];
                }
            }
        }

        // RLX.
        let mut g = Graph::new("ada");
        let xn = g.input("x", Shape::new(&[bch, s, d], f));
        let scn = g.input("scale", Shape::new(&[bch, 1, d], f));
        let shn = g.input("shift", Shape::new(&[bch, 1, d], f));
        let norm = if ln {
            AdaNormKind::LayerNorm
        } else {
            AdaNormKind::RmsNorm
        };
        let out = g.ada_layer_norm(xn, scn, shn, norm, eps);
        g.set_outputs(vec![out]);

        let plan = rlx_opt::memory::plan_memory(&g);
        let mut arena = crate::arena::Arena::from_plan(plan);
        let sched = compile_thunks(&g, &arena);
        let xoff = arena.byte_offset(xn);
        let scoff = arena.byte_offset(scn);
        let shoff = arena.byte_offset(shn);
        let ooff = arena.byte_offset(out);
        let buf = arena.raw_buf_mut();
        unsafe {
            let cp = |dst: *mut f32, data: &[f32]| {
                for (i, &v) in data.iter().enumerate() {
                    *dst.add(i) = v;
                }
            };
            cp(buf.as_mut_ptr().add(xoff) as *mut f32, &x);
            cp(buf.as_mut_ptr().add(scoff) as *mut f32, &scale);
            cp(buf.as_mut_ptr().add(shoff) as *mut f32, &shift);
        }
        execute_thunks(&sched, arena.raw_buf_mut());
        let actual: Vec<f32> = unsafe {
            let p = arena.raw_buf().as_ptr().add(ooff) as *const f32;
            (0..bch * s * d).map(|i| *p.add(i)).collect()
        };
        for (i, (e, a)) in expected.iter().zip(&actual).enumerate() {
            assert!(
                (e - a).abs() < 1e-4,
                "ada layer_norm={ln} mismatch at {i}: expected {e}, got {a}"
            );
        }
    }
}

/// `Op::GatedResidual` native CPU kernel must match `x + gate·y` with the
/// `[B,1,D]` gate broadcast over the sequence axis.
#[test]
fn gated_residual_matches_reference() {
    use rlx_ir::infer::GraphExt;
    let f = DType::F32;
    let (bch, s, d) = (2usize, 4usize, 6usize);

    let mut seed: u32 = 0xdead_beef;
    let mut rand = || {
        seed ^= seed << 13;
        seed ^= seed >> 17;
        seed ^= seed << 5;
        (seed as f32 / u32::MAX as f32) - 0.5
    };
    let x: Vec<f32> = (0..bch * s * d).map(|_| rand()).collect();
    let y: Vec<f32> = (0..bch * s * d).map(|_| rand()).collect();
    let gate: Vec<f32> = (0..bch * d).map(|_| rand()).collect(); // [B,1,D]

    let mut expected = vec![0f32; bch * s * d];
    for b in 0..bch {
        for si in 0..s {
            for di in 0..d {
                let idx = (b * s + si) * d + di;
                expected[idx] = x[idx] + gate[b * d + di] * y[idx];
            }
        }
    }

    let mut g = Graph::new("gated");
    let xn = g.input("x", Shape::new(&[bch, s, d], f));
    let yn = g.input("y", Shape::new(&[bch, s, d], f));
    let gn = g.input("gate", Shape::new(&[bch, 1, d], f));
    let out = g.gated_residual(xn, yn, gn);
    g.set_outputs(vec![out]);

    let plan = rlx_opt::memory::plan_memory(&g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(&g, &arena);
    let xoff = arena.byte_offset(xn);
    let yoff = arena.byte_offset(yn);
    let goff = arena.byte_offset(gn);
    let ooff = arena.byte_offset(out);
    let buf = arena.raw_buf_mut();
    unsafe {
        let cp = |dst: *mut f32, data: &[f32]| {
            for (i, &v) in data.iter().enumerate() {
                *dst.add(i) = v;
            }
        };
        cp(buf.as_mut_ptr().add(xoff) as *mut f32, &x);
        cp(buf.as_mut_ptr().add(yoff) as *mut f32, &y);
        cp(buf.as_mut_ptr().add(goff) as *mut f32, &gate);
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let actual: Vec<f32> = unsafe {
        let p = arena.raw_buf().as_ptr().add(ooff) as *const f32;
        (0..bch * s * d).map(|i| *p.add(i)).collect()
    };
    for (i, (e, a)) in expected.iter().zip(&actual).enumerate() {
        assert!(
            (e - a).abs() < 1e-5,
            "gated_residual mismatch at {i}: expected {e}, got {a}"
        );
    }
}

/// Compile + run a single-output graph on CPU, loading each named input, and
/// return the output as a `Vec<f32>`. Used to compare a native fused op with
/// its `unfuse` decomposition (the path every non-CPU backend takes).
#[cfg(test)]
fn run_graph_cpu(g: &Graph, inputs: &[(&str, &[f32])], out_len: usize) -> Vec<f32> {
    let plan = rlx_opt::memory::plan_memory(g);
    let mut arena = crate::arena::Arena::from_plan(plan);
    let sched = compile_thunks(g, &arena);
    // Materialize Op::Constant data into the arena (the runtime's loader does
    // this in production; e.g. the decomposition's gamma=ones / beta=zeros).
    for n in g.nodes() {
        if let Op::Constant { data } = &n.op {
            let off = arena.byte_offset(n.id);
            let buf = arena.raw_buf_mut();
            unsafe {
                std::ptr::copy_nonoverlapping(data.as_ptr(), buf.as_mut_ptr().add(off), data.len());
            }
        }
    }
    for (name, data) in inputs {
        let id = g
            .nodes()
            .iter()
            .find(|n| matches!(&n.op, Op::Input { name: nm } if nm.as_str() == *name))
            .unwrap_or_else(|| panic!("input {name} not found"))
            .id;
        let off = arena.byte_offset(id);
        let buf = arena.raw_buf_mut();
        unsafe {
            let dst = buf.as_mut_ptr().add(off) as *mut f32;
            for (i, &v) in data.iter().enumerate() {
                *dst.add(i) = v;
            }
        }
    }
    execute_thunks(&sched, arena.raw_buf_mut());
    let ooff = arena.byte_offset(g.outputs[0]);
    unsafe {
        let p = arena.raw_buf().as_ptr().add(ooff) as *const f32;
        (0..out_len).map(|i| *p.add(i)).collect()
    }
}

/// The `unfuse` decomposition of `Op::AdaLayerNorm` (norm → mul(1+scale) →
/// add(shift)) — the path every non-CPU backend runs — must match the native
/// fused kernel bit-for-bit-close.
#[test]
fn ada_layer_norm_decompose_matches_native() {
    use rlx_ir::infer::GraphExt;
    use rlx_ir::op::AdaNormKind;
    let f = DType::F32;
    let (bch, s, d) = (2usize, 5usize, 8usize);
    let eps = 1e-5f32;

    let mut seed: u32 = 0x0bad_c0de;
    let mut rand = || {
        seed ^= seed << 13;
        seed ^= seed >> 17;
        seed ^= seed << 5;
        (seed as f32 / u32::MAX as f32) - 0.5
    };
    let x: Vec<f32> = (0..bch * s * d).map(|_| rand()).collect();
    let scale: Vec<f32> = (0..bch * d).map(|_| rand()).collect();
    let shift: Vec<f32> = (0..bch * d).map(|_| rand()).collect();

    for &ln in &[true, false] {
        let norm = if ln {
            AdaNormKind::LayerNorm
        } else {
            AdaNormKind::RmsNorm
        };
        let build = || {
            let mut g = Graph::new("ada");
            let xn = g.input("x", Shape::new(&[bch, s, d], f));
            let scn = g.input("scale", Shape::new(&[bch, 1, d], f));
            let shn = g.input("shift", Shape::new(&[bch, 1, d], f));
            let out = g.ada_layer_norm(xn, scn, shn, norm, eps);
            g.set_outputs(vec![out]);
            g
        };
        let inputs: &[(&str, &[f32])] = &[("x", &x), ("scale", &scale), ("shift", &shift)];

        let native = run_graph_cpu(&build(), inputs, bch * s * d);
        // Mirror a non-CPU backend: unfuse to primitives, then legalize the
        // broadcasts the decomposition introduces (the real backend pipeline
        // runs both before lowering).
        let decomposed = rlx_opt::rlx_compile::legalize_broadcast::run(
            rlx_opt::rlx_fusion::unfuse::unfuse_dit_modulation(build()),
        );
        assert!(
            !decomposed
                .nodes()
                .iter()
                .any(|n| matches!(n.op, Op::AdaLayerNorm { .. })),
            "unfuse left an AdaLayerNorm node"
        );
        let decomp = run_graph_cpu(&decomposed, inputs, bch * s * d);

        for (i, (nv, dv)) in native.iter().zip(&decomp).enumerate() {
            assert!(
                (nv - dv).abs() < 1e-4,
                "ada ln={ln} native vs decompose mismatch at {i}: {nv} vs {dv}"
            );
        }
    }
}

/// The `unfuse` decomposition of `Op::GatedResidual` (mul(gate,y) → add(x))
/// must match the native fused kernel.
#[test]
fn gated_residual_decompose_matches_native() {
    use rlx_ir::infer::GraphExt;
    let f = DType::F32;
    let (bch, s, d) = (2usize, 4usize, 6usize);

    let mut seed: u32 = 0xfeed_face;
    let mut rand = || {
        seed ^= seed << 13;
        seed ^= seed >> 17;
        seed ^= seed << 5;
        (seed as f32 / u32::MAX as f32) - 0.5
    };
    let x: Vec<f32> = (0..bch * s * d).map(|_| rand()).collect();
    let y: Vec<f32> = (0..bch * s * d).map(|_| rand()).collect();
    let gate: Vec<f32> = (0..bch * d).map(|_| rand()).collect();

    let build = || {
        let mut g = Graph::new("gated");
        let xn = g.input("x", Shape::new(&[bch, s, d], f));
        let yn = g.input("y", Shape::new(&[bch, s, d], f));
        let gn = g.input("gate", Shape::new(&[bch, 1, d], f));
        let out = g.gated_residual(xn, yn, gn);
        g.set_outputs(vec![out]);
        g
    };
    let inputs: &[(&str, &[f32])] = &[("x", &x), ("y", &y), ("gate", &gate)];

    let native = run_graph_cpu(&build(), inputs, bch * s * d);
    let decomposed = rlx_opt::rlx_compile::legalize_broadcast::run(
        rlx_opt::rlx_fusion::unfuse::unfuse_dit_modulation(build()),
    );
    assert!(
        !decomposed
            .nodes()
            .iter()
            .any(|n| matches!(n.op, Op::GatedResidual)),
        "unfuse left a GatedResidual node"
    );
    let decomp = run_graph_cpu(&decomposed, inputs, bch * s * d);

    for (i, (nv, dv)) in native.iter().zip(&decomp).enumerate() {
        assert!(
            (nv - dv).abs() < 1e-5,
            "gated_residual native vs decompose mismatch at {i}: {nv} vs {dv}"
        );
    }
}