moeflux 0.1.0-pre.2

Pure-Rust streaming-experts MoE inference on Metal. Forked from flash-moe; only the Metal kernels remain from upstream.
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
//! Differential test harness for the RIIR port.
//!
//! Two implementations of [`DiffBackend`]:
//!
//! - **`CBackend`** wraps the existing C-via-`moeflux-sys` path
//!   ([`moeflux::Ctx`]).
//! - **`RsBackend`** wraps the new pure-Rust path ([`moeflux::riir::RsCtx`]).
//!   Phase 0: every method panics. Phase 4 onwards: real impl.
//!
//! Phase 0+ tests run identical inputs through both and compare
//! outputs. Tolerances account for Metal MoE atomic-op nondeterminism
//! (a known issue, not a porting bug):
//!
//! - argmax must match exactly
//! - top-K (K=20) Jaccard ≥ 0.95
//! - full-vector cosine similarity ≥ 0.99
//!
//! `#[ignore]` on every test that touches a real model — needs the
//! ~18 GB of artifacts mounted.
//!
//! ## End-to-end logits are NOT a useful diff oracle
//!
//! Empirically (Phase 0 finding): the C path is non-deterministic
//! across `memory_clear` for the same prompt. Two identical
//! `eval_prompt` calls on one Ctx, with `memory_clear` between,
//! produce logit vectors with cosine sim ≈ 0.65–0.76 and top-20
//! Jaccard ≈ 0.10–0.18 — well below the floors above. Argmax
//! matches some prompts and not others; trajectory match works
//! only because greedy decoding lands in attractors regardless of
//! starting state.
//!
//! Conclusion: the Rust port cannot be diff-tested at the
//! end-to-end-logits boundary against C. The real diff strategy
//! starting Phase 3 will be **intermediate-tensor checkpoints** —
//! both backends will expose hooks to dump per-layer outputs, and
//! comparison happens layer-by-layer where Metal nondeterminism
//! has had less chance to accumulate.
//!
//! ## Phase 0 contents
//!
//! - The trait + C impl + Rust stub + comparison helpers.
//! - One scaffold-validation test (`harness_loads`) that opens the C
//!   backend, prints model metadata, runs a single prefill, and
//!   confirms the helpers don't crash. No equality assertion.
//!
//! Phase 1+ adds tests that run `CBackend` vs `RsBackend` for each
//! ported subsystem, with the per-layer hooks landing in Phase 3.
//!
//! ```bash
//! cargo test -p moeflux \
//!     --features "model-qwen3-6-35b-a3b" \
//!     --test diff_oracle --release \
//!     -- --ignored --nocapture --test-threads=1
//! ```

#![cfg(target_os = "macos")]

use std::path::{Path, PathBuf};

mod common;
use common::c_backend::Ctx;
use moeflux::riir::RsCtx;

// ---------------------------------------------------------------------------
// Trait + impls
// ---------------------------------------------------------------------------

/// Common behavior the harness exercises across both backends.
///
/// Methods mirror [`moeflux::Ctx`]'s public API 1:1 — the diff
/// harness treats this surface as the boundary at which behavior
/// must agree. Each impl forwards to its underlying ctx; the
/// abstraction is purely a witness for trait-generic test code.
pub trait DiffBackend {
    fn open(
        weights: &Path,
        manifest: &Path,
        vocab: &Path,
        experts_dir: &Path,
        experts_per_tok: u32,
        use_2bit: bool,
    ) -> Self;

    fn n_vocab(&self) -> usize;
    fn n_ctx(&self) -> usize;
    fn eos(&self) -> i32;
    fn model_name(&self) -> &'static str;

    /// Embed a single token. Returns a `HIDDEN_DIM`-long f32 vector.
    /// First per-kernel diff point landed in Phase 3.
    fn embed(&self, token_id: i32) -> Vec<f32>;

    /// CPU RMSNorm against the BF16 weight tensor `weight_name`.
    /// Returns a `HIDDEN_DIM`-long f32 vector.
    fn rms_norm_cpu(&self, weight_name: &str, x: &[f32]) -> Vec<f32>;

    /// Apply rotary position embedding to Q and K at `pos`. Returns
    /// `(q_out, k_out)`; inputs are not mutated.
    fn apply_rotary_emb(
        &self,
        pos: i32,
        q: &[f32],
        k: &[f32],
    ) -> (Vec<f32>, Vec<f32>);

    /// Per-head CPU RMSNorm against the bf16 weight tensor
    /// `weight_name` (length `head_dim`). Returns the
    /// `num_heads * head_dim`-long output; the input is not mutated.
    fn rms_norm_per_head_cpu(
        &self,
        weight_name: &str,
        num_heads: usize,
        head_dim: usize,
        x: &[f32],
    ) -> Vec<f32>;

    /// CPU scaled dot-product attention with sigmoid-gated output for
    /// one query position against `kv_len` cached positions. Returns
    /// the `num_attn_heads * head_dim`-long gated attention output.
    fn sdpa_cpu(
        &self,
        kv_len: i32,
        q: &[f32],
        q_gate: &[f32],
        k_cache: &[f32],
        v_cache: &[f32],
    ) -> Vec<f32>;

    /// CPU LM head matvec. `x` is `HIDDEN_DIM` floats; the returned
    /// vector is `VOCAB_SIZE` floats (raw logits).
    fn lm_head_cpu(&self, x: &[f32]) -> Vec<f32>;

    /// MoE router: softmax → top-K → normalize. Takes the raw gate
    /// logits, returns `(indices, weights)` parallel arrays of length
    /// `k`. `scores` is consumed as input; the C path mutates it in
    /// place but the trait surface hands over an owned copy each call.
    fn moe_router_cpu(&self, scores: Vec<f32>, k: usize) -> (Vec<i32>, Vec<f32>);

    /// Depthwise 1D conv step + SiLU. `weight_name` is a bf16 tensor
    /// of length `channels * kernel_size`. Returns `channels` floats.
    fn conv1d_step_cpu(
        &self,
        weight_name: &str,
        channels: usize,
        kernel_size: usize,
        conv_state: &[f32],
        new_input: &[f32],
    ) -> Vec<f32>;

    /// Bare CPU RMSNorm (no weight). Returns `x.len()` floats.
    fn rms_norm_bare_cpu(&self, eps: f32, x: &[f32]) -> Vec<f32>;

    /// CPU RMSNormGated. Returns `x.len()` floats.
    fn rms_norm_gated_cpu(
        &self,
        weight_name: &str,
        eps: f32,
        x: &[f32],
        z: &[f32],
    ) -> Vec<f32>;

    /// Gated-delta-net recurrence step. Returns the post-step
    /// `(ssm_state, out_values)` pair — input state is consumed; the
    /// trait surface clones it per call so the harness can run both
    /// backends from identical starting states.
    #[allow(clippy::too_many_arguments)]
    fn gated_delta_recurrence_cpu(
        &self,
        layer_idx: usize,
        alpha: &[f32],
        beta: &[f32],
        q: &[f32],
        k: &[f32],
        v: &[f32],
        v_heads: usize,
        k_heads: usize,
        key_dim: usize,
        value_dim: usize,
        ssm_state_in: Vec<f32>,
    ) -> (Vec<f32>, Vec<f32>);

    /// Read one expert's `EXPERT_SIZE`-byte 4-bit blob from disk
    /// (slice 9c). Returns the raw on-disk bytes.
    fn load_expert_bytes(&self, layer_idx: i32, expert_idx: i32) -> Vec<u8>;

    /// GPU RMSNorm with bf16 weights (slice 9e). `x` is HIDDEN_DIM
    /// floats; `weight_bf16` is HIDDEN_DIM × 2 bytes (typically the
    /// raw `model.norm.weight` mmap region). Returns HIDDEN_DIM floats.
    fn gpu_rms_norm_fused(
        &mut self,
        x: &[f32],
        weight_bf16: &[u8],
    ) -> Vec<f32>;

    /// Single-expert GPU FFN forward (slice 9a). `expert_data` is one
    /// expert's `EXPERT_SIZE`-byte 4-bit blob; `h_post` is HIDDEN_DIM
    /// floats. Returns the HIDDEN_DIM-float expert output. Takes
    /// `&mut self` because the Rust backend builds the Metal device
    /// lazily on first GPU call.
    fn gpu_expert_forward(
        &mut self,
        expert_data: &[u8],
        h_post: &[f32],
    ) -> Vec<f32>;

    /// Batched K-expert FFN forward + GPU combine (slice 9b).
    /// `expert_data` is `actual_k * EXPERT_SIZE` bytes (K blobs in slot
    /// order). Returns the HIDDEN_DIM-float post-combine hidden state.
    #[allow(clippy::too_many_arguments)]
    fn gpu_batched_experts_forward(
        &mut self,
        actual_k: i32,
        expert_data: &[u8],
        h_post: &[f32],
        h_mid: &[f32],
        shared_out: &[f32],
        expert_weights: &[f32],
        shared_gate_score: f32,
    ) -> Vec<f32>;

    /// `attn_scores_batched` (slice 5d-7a). Returns `[num_heads * seq_len]`
    /// scaled per-head Q · K^T scores (stride-tight).
    #[allow(clippy::too_many_arguments)]
    fn attn_scores_batched(
        &mut self,
        num_heads: u32,
        num_kv_heads: u32,
        head_dim: u32,
        seq_len: u32,
        q: &[f32],
        k_cache: &[f32],
        scale: f32,
    ) -> Vec<f32>;

    /// `attn_softmax_batched` (slice 5d-7a). Per-head softmax over
    /// `[0, seq_len)`. Input is `[num_heads * seq_len]` raw scores;
    /// output is the same shape, post-softmax.
    fn attn_softmax_batched(
        &mut self,
        num_heads: u32,
        seq_len: u32,
        scores_in: &[f32],
    ) -> Vec<f32>;

    /// `attn_values_batched` (slice 5d-7a). Returns `[num_heads *
    /// head_dim]` per-head value aggregation.
    #[allow(clippy::too_many_arguments)]
    fn attn_values_batched(
        &mut self,
        num_heads: u32,
        num_kv_heads: u32,
        head_dim: u32,
        seq_len: u32,
        scores: &[f32],
        v_cache: &[f32],
    ) -> Vec<f32>;

    /// `sigmoid_gate` (slice 5d-7a). Returns `[dim]` gated values
    /// (`x_in[i] * sigmoid(gate[i])`). Caller passes the pre-gate
    /// values in `x_in`; the trait surface clones to the in/out buffer
    /// internally.
    fn sigmoid_gate(
        &mut self,
        dim: u32,
        gate: &[f32],
        x_in: &[f32],
    ) -> Vec<f32>;

    /// Slice 4e — begin a deferred K-expert dispatch (commits async,
    /// no readback). Pair with [`Self::complete_deferred_experts`] or
    /// [`Self::discard_deferred_experts`].
    #[allow(clippy::too_many_arguments)]
    fn begin_deferred_experts(
        &mut self,
        actual_k: i32,
        expert_data: &[u8],
        h_post: &[f32],
        h_mid: &[f32],
        shared_out: &[f32],
        expert_weights: &[f32],
        shared_gate_score: f32,
    );

    /// Slice 4e — wait for the deferred dispatch and read back the
    /// post-combine hidden state. Returns HIDDEN_DIM floats; an
    /// all-zero vector if no deferred dispatch was active (matches the
    /// C-side no-op semantics).
    fn complete_deferred_experts(&mut self) -> Vec<f32>;

    /// Slice 4e — wait for the deferred dispatch and clear state
    /// without readback. Used in production for prefill tokens whose
    /// hidden state is overwritten by the next token's embedding.
    fn discard_deferred_experts(&mut self);

    /// Phase 4 layer-boundary diff checkpoint. Runs one layer's
    /// forward starting from `hidden_in` and returns the post-layer
    /// HIDDEN_DIM state. Drives the layer's per-layer state in place
    /// (callers are expected to `memory_clear` between independent
    /// trials so the KV / recurrence start state matches across
    /// backends). Tests land in 4c (linear-attn) / 4d (full-attn);
    /// the trait method is here in 4b so both backend impls can be
    /// wired ahead of the kernel landing.
    fn layer_forward_dump(
        &mut self,
        layer_idx: i32,
        pos: i32,
        hidden_in: &[f32],
    ) -> Vec<f32>;

    /// Prefill `tokens` at `start_pos`. Returns the n_vocab-length
    /// logit vector for the position immediately after the last
    /// token in `tokens`.
    fn eval_prompt(&mut self, tokens: &[i32], start_pos: usize) -> Vec<f32>;

    /// Decode a single token at `pos`. Returns the next-token logit
    /// vector.
    fn eval_token(&mut self, token: i32, pos: usize) -> Vec<f32>;

    fn memory_clear(&mut self);
    fn memory_seq_rm(&mut self, p0: i32, p1: i32) -> bool;
    fn memory_seq_pos_max(&self) -> i32;
}

/// C-via-`moeflux-sys` impl. Thin wrapper around [`moeflux::Ctx`].
/// Field is public so tests in this file can call inherent `Ctx`
/// methods that aren't on the [`DiffBackend`] trait (e.g.
/// state_save / state_load checks in later phases).
pub struct CBackend(pub Ctx);

impl DiffBackend for CBackend {
    fn open(
        weights: &Path,
        manifest: &Path,
        vocab: &Path,
        experts_dir: &Path,
        experts_per_tok: u32,
        use_2bit: bool,
    ) -> Self {
        Self(
            Ctx::open(
                weights,
                manifest,
                vocab,
                experts_dir,
                experts_per_tok,
                use_2bit,
            )
            .expect("CBackend Ctx::open"),
        )
    }

    fn n_vocab(&self) -> usize {
        self.0.n_vocab()
    }
    fn n_ctx(&self) -> usize {
        self.0.n_ctx()
    }
    fn eos(&self) -> i32 {
        self.0.eos()
    }
    fn model_name(&self) -> &'static str {
        self.0.model_name()
    }

    fn embed(&self, token_id: i32) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0.embed(token_id, &mut out).expect("CBackend embed");
        out
    }

    fn rms_norm_cpu(&self, weight_name: &str, x: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .rms_norm_cpu(weight_name, x, &mut out)
            .expect("CBackend rms_norm_cpu");
        out
    }

    fn apply_rotary_emb(
        &self,
        pos: i32,
        q: &[f32],
        k: &[f32],
    ) -> (Vec<f32>, Vec<f32>) {
        let mut q_out = q.to_vec();
        let mut k_out = k.to_vec();
        self.0
            .apply_rotary_emb(pos, &mut q_out, &mut k_out)
            .expect("CBackend apply_rotary_emb");
        (q_out, k_out)
    }

    fn rms_norm_per_head_cpu(
        &self,
        weight_name: &str,
        num_heads: usize,
        head_dim: usize,
        x: &[f32],
    ) -> Vec<f32> {
        let mut out = x.to_vec();
        self.0
            .rms_norm_per_head_cpu(weight_name, num_heads, head_dim, &mut out)
            .expect("CBackend rms_norm_per_head_cpu");
        out
    }

    fn sdpa_cpu(
        &self,
        kv_len: i32,
        q: &[f32],
        q_gate: &[f32],
        k_cache: &[f32],
        v_cache: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; q.len()];
        self.0
            .sdpa_cpu(kv_len, q, q_gate, k_cache, v_cache, &mut out)
            .expect("CBackend sdpa_cpu");
        out
    }

    fn lm_head_cpu(&self, x: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; self.0.n_vocab()];
        self.0
            .lm_head_cpu(x, &mut out)
            .expect("CBackend lm_head_cpu");
        out
    }

    fn moe_router_cpu(&self, scores: Vec<f32>, k: usize) -> (Vec<i32>, Vec<f32>) {
        let mut s = scores;
        let mut idx = vec![0i32; k];
        let mut w = vec![0.0f32; k];
        self.0
            .moe_router_cpu(&mut s, k, &mut idx, &mut w)
            .expect("CBackend moe_router_cpu");
        (idx, w)
    }

    fn conv1d_step_cpu(
        &self,
        weight_name: &str,
        channels: usize,
        kernel_size: usize,
        conv_state: &[f32],
        new_input: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; channels];
        self.0
            .conv1d_step_cpu(
                weight_name,
                channels,
                kernel_size,
                conv_state,
                new_input,
                &mut out,
            )
            .expect("CBackend conv1d_step_cpu");
        out
    }

    fn rms_norm_bare_cpu(&self, eps: f32, x: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; x.len()];
        self.0
            .rms_norm_bare_cpu(eps, x, &mut out)
            .expect("CBackend rms_norm_bare_cpu");
        out
    }

    fn rms_norm_gated_cpu(
        &self,
        weight_name: &str,
        eps: f32,
        x: &[f32],
        z: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; x.len()];
        self.0
            .rms_norm_gated_cpu(weight_name, eps, x, z, &mut out)
            .expect("CBackend rms_norm_gated_cpu");
        out
    }

    fn gated_delta_recurrence_cpu(
        &self,
        layer_idx: usize,
        alpha: &[f32],
        beta: &[f32],
        q: &[f32],
        k: &[f32],
        v: &[f32],
        v_heads: usize,
        k_heads: usize,
        key_dim: usize,
        value_dim: usize,
        ssm_state_in: Vec<f32>,
    ) -> (Vec<f32>, Vec<f32>) {
        let mut state = ssm_state_in;
        let mut out = vec![0.0f32; v_heads * value_dim];
        self.0
            .gated_delta_recurrence_cpu(
                layer_idx,
                alpha,
                beta,
                q,
                k,
                v,
                v_heads,
                k_heads,
                key_dim,
                value_dim,
                &mut state,
                &mut out,
            )
            .expect("CBackend gated_delta_recurrence_cpu");
        (state, out)
    }

    fn load_expert_bytes(&self, layer_idx: i32, expert_idx: i32) -> Vec<u8> {
        let mut out = vec![0u8; moeflux::riir::VARIANT.expert_size_4bit()];
        self.0
            .load_expert_bytes(layer_idx, expert_idx, &mut out)
            .expect("CBackend load_expert_bytes");
        out
    }

    fn gpu_rms_norm_fused(
        &mut self,
        x: &[f32],
        weight_bf16: &[u8],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .gpu_rms_norm_fused(x, weight_bf16, &mut out)
            .expect("CBackend gpu_rms_norm_fused");
        out
    }

    fn gpu_expert_forward(
        &mut self,
        expert_data: &[u8],
        h_post: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .gpu_expert_forward(expert_data, h_post, &mut out)
            .expect("CBackend gpu_expert_forward");
        out
    }

    fn gpu_batched_experts_forward(
        &mut self,
        actual_k: i32,
        expert_data: &[u8],
        h_post: &[f32],
        h_mid: &[f32],
        shared_out: &[f32],
        expert_weights: &[f32],
        shared_gate_score: f32,
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .gpu_batched_experts_forward(
                actual_k,
                expert_data,
                h_post,
                h_mid,
                shared_out,
                expert_weights,
                shared_gate_score,
                &mut out,
            )
            .expect("CBackend gpu_batched_experts_forward");
        out
    }

    fn attn_scores_batched(
        &mut self,
        num_heads: u32,
        num_kv_heads: u32,
        head_dim: u32,
        seq_len: u32,
        q: &[f32],
        k_cache: &[f32],
        scale: f32,
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; (num_heads * seq_len) as usize];
        self.0
            .attn_scores_batched(
                num_heads as i32,
                num_kv_heads as i32,
                head_dim as i32,
                seq_len as i32,
                q,
                k_cache,
                scale,
                &mut out,
            )
            .expect("CBackend attn_scores_batched");
        out
    }

    fn attn_softmax_batched(
        &mut self,
        num_heads: u32,
        seq_len: u32,
        scores_in: &[f32],
    ) -> Vec<f32> {
        let mut out = scores_in.to_vec();
        self.0
            .attn_softmax_batched(num_heads as i32, seq_len as i32, &mut out)
            .expect("CBackend attn_softmax_batched");
        out
    }

    fn attn_values_batched(
        &mut self,
        num_heads: u32,
        num_kv_heads: u32,
        head_dim: u32,
        seq_len: u32,
        scores: &[f32],
        v_cache: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; (num_heads * head_dim) as usize];
        self.0
            .attn_values_batched(
                num_heads as i32,
                num_kv_heads as i32,
                head_dim as i32,
                seq_len as i32,
                scores,
                v_cache,
                &mut out,
            )
            .expect("CBackend attn_values_batched");
        out
    }

    fn sigmoid_gate(
        &mut self,
        dim: u32,
        gate: &[f32],
        x_in: &[f32],
    ) -> Vec<f32> {
        let mut out = x_in.to_vec();
        self.0
            .sigmoid_gate(dim as i32, gate, &mut out)
            .expect("CBackend sigmoid_gate");
        out
    }

    fn begin_deferred_experts(
        &mut self,
        actual_k: i32,
        expert_data: &[u8],
        h_post: &[f32],
        h_mid: &[f32],
        shared_out: &[f32],
        expert_weights: &[f32],
        shared_gate_score: f32,
    ) {
        self.0
            .begin_deferred_experts(
                actual_k,
                expert_data,
                h_post,
                h_mid,
                shared_out,
                expert_weights,
                shared_gate_score,
            )
            .expect("CBackend begin_deferred_experts");
    }

    fn complete_deferred_experts(&mut self) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .complete_deferred_experts(&mut out)
            .expect("CBackend complete_deferred_experts");
        out
    }

    fn discard_deferred_experts(&mut self) {
        self.0
            .discard_deferred_experts()
            .expect("CBackend discard_deferred_experts");
    }

    fn layer_forward_dump(
        &mut self,
        layer_idx: i32,
        pos: i32,
        hidden_in: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .layer_forward_dump(layer_idx, pos, hidden_in, &mut out)
            .expect("CBackend layer_forward_dump");
        out
    }

    fn eval_prompt(&mut self, tokens: &[i32], start_pos: usize) -> Vec<f32> {
        let mut logits = vec![0.0f32; self.0.n_vocab()];
        self.0
            .eval_prompt(tokens, start_pos, 0, &mut logits)
            .expect("CBackend eval_prompt");
        logits
    }

    fn eval_token(&mut self, token: i32, pos: usize) -> Vec<f32> {
        let mut logits = vec![0.0f32; self.0.n_vocab()];
        self.0
            .eval_token(token, pos, 0, &mut logits)
            .expect("CBackend eval_token");
        logits
    }

    fn memory_clear(&mut self) {
        self.0.memory_clear()
    }
    fn memory_seq_rm(&mut self, p0: i32, p1: i32) -> bool {
        self.0.memory_seq_rm(0, p0, p1)
    }
    fn memory_seq_pos_max(&self) -> i32 {
        self.0.memory_seq_pos_max(0)
    }
}

/// Pure-Rust impl. Phase 3: methods become real as their kernels are
/// ported (embedding landed; the rest still `todo!()`).
pub struct RsBackend(RsCtx);

impl DiffBackend for RsBackend {
    fn open(
        weights: &Path,
        manifest: &Path,
        vocab: &Path,
        experts_dir: &Path,
        experts_per_tok: u32,
        use_2bit: bool,
    ) -> Self {
        Self(
            RsCtx::open(
                weights,
                manifest,
                vocab,
                experts_dir,
                experts_per_tok,
                use_2bit,
            )
            .expect("RsBackend RsCtx::open"),
        )
    }

    fn n_vocab(&self) -> usize {
        self.0.n_vocab()
    }
    fn n_ctx(&self) -> usize {
        self.0.n_ctx()
    }
    fn eos(&self) -> i32 {
        self.0.eos()
    }
    fn model_name(&self) -> &'static str {
        self.0.model_name()
    }

    fn embed(&self, token_id: i32) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0.embed(token_id, &mut out).expect("RsBackend embed");
        out
    }

    fn rms_norm_cpu(&self, weight_name: &str, x: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .rms_norm_cpu(weight_name, x, &mut out)
            .expect("RsBackend rms_norm_cpu");
        out
    }

    fn apply_rotary_emb(
        &self,
        pos: i32,
        q: &[f32],
        k: &[f32],
    ) -> (Vec<f32>, Vec<f32>) {
        let mut q_out = q.to_vec();
        let mut k_out = k.to_vec();
        self.0
            .apply_rotary_emb(pos, &mut q_out, &mut k_out)
            .expect("RsBackend apply_rotary_emb");
        (q_out, k_out)
    }

    fn rms_norm_per_head_cpu(
        &self,
        weight_name: &str,
        num_heads: usize,
        head_dim: usize,
        x: &[f32],
    ) -> Vec<f32> {
        let mut out = x.to_vec();
        self.0
            .rms_norm_per_head_cpu(weight_name, num_heads, head_dim, &mut out)
            .expect("RsBackend rms_norm_per_head_cpu");
        out
    }

    fn sdpa_cpu(
        &self,
        kv_len: i32,
        q: &[f32],
        q_gate: &[f32],
        k_cache: &[f32],
        v_cache: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; q.len()];
        self.0
            .sdpa_cpu(kv_len, q, q_gate, k_cache, v_cache, &mut out)
            .expect("RsBackend sdpa_cpu");
        out
    }

    fn lm_head_cpu(&self, x: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; self.0.n_vocab()];
        self.0
            .lm_head_cpu(x, &mut out)
            .expect("RsBackend lm_head_cpu");
        out
    }

    fn moe_router_cpu(&self, scores: Vec<f32>, k: usize) -> (Vec<i32>, Vec<f32>) {
        let mut s = scores;
        let mut idx = vec![0i32; k];
        let mut w = vec![0.0f32; k];
        self.0
            .moe_router_cpu(&mut s, k, &mut idx, &mut w)
            .expect("RsBackend moe_router_cpu");
        (idx, w)
    }

    fn conv1d_step_cpu(
        &self,
        weight_name: &str,
        channels: usize,
        kernel_size: usize,
        conv_state: &[f32],
        new_input: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; channels];
        self.0
            .conv1d_step_cpu(
                weight_name,
                channels,
                kernel_size,
                conv_state,
                new_input,
                &mut out,
            )
            .expect("RsBackend conv1d_step_cpu");
        out
    }

    fn rms_norm_bare_cpu(&self, eps: f32, x: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; x.len()];
        self.0
            .rms_norm_bare_cpu(eps, x, &mut out)
            .expect("RsBackend rms_norm_bare_cpu");
        out
    }

    fn rms_norm_gated_cpu(
        &self,
        weight_name: &str,
        eps: f32,
        x: &[f32],
        z: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; x.len()];
        self.0
            .rms_norm_gated_cpu(weight_name, eps, x, z, &mut out)
            .expect("RsBackend rms_norm_gated_cpu");
        out
    }

    fn gated_delta_recurrence_cpu(
        &self,
        layer_idx: usize,
        alpha: &[f32],
        beta: &[f32],
        q: &[f32],
        k: &[f32],
        v: &[f32],
        v_heads: usize,
        k_heads: usize,
        key_dim: usize,
        value_dim: usize,
        ssm_state_in: Vec<f32>,
    ) -> (Vec<f32>, Vec<f32>) {
        let mut state = ssm_state_in;
        let mut out = vec![0.0f32; v_heads * value_dim];
        self.0
            .gated_delta_recurrence_cpu(
                layer_idx,
                alpha,
                beta,
                q,
                k,
                v,
                v_heads,
                k_heads,
                key_dim,
                value_dim,
                &mut state,
                &mut out,
            )
            .expect("RsBackend gated_delta_recurrence_cpu");
        (state, out)
    }

    fn load_expert_bytes(&self, layer_idx: i32, expert_idx: i32) -> Vec<u8> {
        let mut out = vec![0u8; moeflux::riir::VARIANT.expert_size_4bit()];
        self.0
            .load_expert_bytes(
                layer_idx as usize,
                expert_idx as usize,
                &mut out,
            )
            .expect("RsBackend load_expert_bytes");
        out
    }

    fn gpu_rms_norm_fused(
        &mut self,
        x: &[f32],
        weight_bf16: &[u8],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .gpu_rms_norm_fused(x, weight_bf16, &mut out)
            .expect("RsBackend gpu_rms_norm_fused");
        out
    }

    fn gpu_expert_forward(
        &mut self,
        expert_data: &[u8],
        h_post: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .gpu_expert_forward(expert_data, h_post, &mut out)
            .expect("RsBackend gpu_expert_forward");
        out
    }

    fn gpu_batched_experts_forward(
        &mut self,
        actual_k: i32,
        expert_data: &[u8],
        h_post: &[f32],
        h_mid: &[f32],
        shared_out: &[f32],
        expert_weights: &[f32],
        shared_gate_score: f32,
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .gpu_batched_experts_forward(
                actual_k,
                expert_data,
                h_post,
                h_mid,
                shared_out,
                expert_weights,
                shared_gate_score,
                &mut out,
            )
            .expect("RsBackend gpu_batched_experts_forward");
        out
    }

    fn attn_scores_batched(
        &mut self,
        num_heads: u32,
        num_kv_heads: u32,
        head_dim: u32,
        seq_len: u32,
        q: &[f32],
        k_cache: &[f32],
        scale: f32,
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; (num_heads * seq_len) as usize];
        self.0
            .attn_scores_batched(
                num_heads, num_kv_heads, head_dim, seq_len, q, k_cache,
                scale, &mut out,
            )
            .expect("RsBackend attn_scores_batched");
        out
    }

    fn attn_softmax_batched(
        &mut self,
        num_heads: u32,
        seq_len: u32,
        scores_in: &[f32],
    ) -> Vec<f32> {
        let mut out = scores_in.to_vec();
        self.0
            .attn_softmax_batched(num_heads, seq_len, &mut out)
            .expect("RsBackend attn_softmax_batched");
        out
    }

    fn attn_values_batched(
        &mut self,
        num_heads: u32,
        num_kv_heads: u32,
        head_dim: u32,
        seq_len: u32,
        scores: &[f32],
        v_cache: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; (num_heads * head_dim) as usize];
        self.0
            .attn_values_batched(
                num_heads, num_kv_heads, head_dim, seq_len, scores, v_cache,
                &mut out,
            )
            .expect("RsBackend attn_values_batched");
        out
    }

    fn sigmoid_gate(
        &mut self,
        dim: u32,
        gate: &[f32],
        x_in: &[f32],
    ) -> Vec<f32> {
        let mut out = x_in.to_vec();
        self.0
            .sigmoid_gate(dim, gate, &mut out)
            .expect("RsBackend sigmoid_gate");
        out
    }

    fn begin_deferred_experts(
        &mut self,
        actual_k: i32,
        expert_data: &[u8],
        h_post: &[f32],
        h_mid: &[f32],
        shared_out: &[f32],
        expert_weights: &[f32],
        shared_gate_score: f32,
    ) {
        // layer_idx = -1 mirrors the C hook (synthetic / no real layer).
        self.0
            .begin_deferred_experts(
                actual_k,
                expert_data,
                h_post,
                h_mid,
                shared_out,
                expert_weights,
                shared_gate_score,
                -1,
            )
            .expect("RsBackend begin_deferred_experts");
    }

    fn complete_deferred_experts(&mut self) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .complete_deferred_experts(&mut out)
            .expect("RsBackend complete_deferred_experts");
        out
    }

    fn discard_deferred_experts(&mut self) {
        self.0.discard_deferred_experts();
    }

    fn layer_forward_dump(
        &mut self,
        layer_idx: i32,
        pos: i32,
        hidden_in: &[f32],
    ) -> Vec<f32> {
        let mut out = vec![0.0f32; moeflux::riir::VARIANT.hidden_dim];
        self.0
            .layer_forward_dump(layer_idx, pos, hidden_in, &mut out)
            .expect("RsBackend layer_forward_dump");
        out
    }

    fn eval_prompt(&mut self, tokens: &[i32], start_pos: usize) -> Vec<f32> {
        let mut logits = vec![0.0f32; self.0.n_vocab()];
        self.0
            .eval_prompt(tokens, start_pos, 0, &mut logits)
            .expect("RsBackend eval_prompt");
        logits
    }

    fn eval_token(&mut self, token: i32, pos: usize) -> Vec<f32> {
        let mut logits = vec![0.0f32; self.0.n_vocab()];
        self.0
            .eval_token(token, pos, 0, &mut logits)
            .expect("RsBackend eval_token");
        logits
    }

    fn memory_clear(&mut self) {
        self.0.memory_clear()
    }
    fn memory_seq_rm(&mut self, p0: i32, p1: i32) -> bool {
        self.0.memory_seq_rm(0, p0, p1)
    }
    fn memory_seq_pos_max(&self) -> i32 {
        self.0.memory_seq_pos_max(0)
    }
}

// ---------------------------------------------------------------------------
// Comparison helpers
// ---------------------------------------------------------------------------

/// Argmax (id of largest logit). Ties broken by lowest id.
pub fn argmax(logits: &[f32]) -> i32 {
    let mut best_id = 0i32;
    let mut best_v = f32::NEG_INFINITY;
    for (i, &v) in logits.iter().enumerate() {
        if v > best_v {
            best_v = v;
            best_id = i as i32;
        }
    }
    best_id
}

/// Top-K ids by descending logit, ties broken by ascending id.
pub fn topk(logits: &[f32], k: usize) -> Vec<i32> {
    let mut idx: Vec<(i32, f32)> = logits
        .iter()
        .enumerate()
        .map(|(i, &v)| (i as i32, v))
        .collect();
    idx.sort_by(|a, b| {
        b.1.partial_cmp(&a.1)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.0.cmp(&b.0))
    });
    idx.truncate(k);
    idx.into_iter().map(|(i, _)| i).collect()
}

/// Jaccard set overlap of two id lists.
pub fn jaccard(a: &[i32], b: &[i32]) -> f32 {
    use std::collections::HashSet;
    let sa: HashSet<i32> = a.iter().copied().collect();
    let sb: HashSet<i32> = b.iter().copied().collect();
    let inter = sa.intersection(&sb).count() as f32;
    let union = sa.union(&sb).count() as f32;
    if union == 0.0 { 1.0 } else { inter / union }
}

/// Cosine similarity over the full logit vector. Robust to scale
/// differences; catches both directional and magnitude drift up to
/// a global multiplicative factor.
pub fn cosine_sim(a: &[f32], b: &[f32]) -> f32 {
    assert_eq!(a.len(), b.len(), "cosine_sim: length mismatch");
    let mut dot = 0.0f64;
    let mut na = 0.0f64;
    let mut nb = 0.0f64;
    for (&x, &y) in a.iter().zip(b.iter()) {
        let xf = x as f64;
        let yf = y as f64;
        dot += xf * yf;
        na += xf * xf;
        nb += yf * yf;
    }
    let denom = (na * nb).sqrt();
    if denom == 0.0 { 1.0 } else { (dot / denom) as f32 }
}

/// Tolerances applied at every diff-check site. Conservative defaults
/// — Metal MoE atomic-op nondeterminism is the dominant noise source
/// and stays well below these floors empirically.
pub const TOPK_K: usize = 20;
pub const TOPK_JACCARD_MIN: f32 = 0.95;
pub const COSINE_SIM_MIN: f32 = 0.99;

/// Full diff check on one logit vector. Asserts argmax match,
/// top-K Jaccard floor, and cosine-sim floor; logs all three.
pub fn assert_logits_close(label: &str, c: &[f32], rs: &[f32]) {
    let c_arg = argmax(c);
    let rs_arg = argmax(rs);
    let c_top = topk(c, TOPK_K);
    let rs_top = topk(rs, TOPK_K);
    let jac = jaccard(&c_top, &rs_top);
    let cos = cosine_sim(c, rs);

    eprintln!(
        "[diff:{label}] argmax c={c_arg} rs={rs_arg} \
         top-{TOPK_K} jaccard={jac:.4} cosine={cos:.5}"
    );

    assert_eq!(
        c_arg, rs_arg,
        "[diff:{label}] argmax mismatch (c={c_arg} rs={rs_arg})"
    );
    assert!(
        jac >= TOPK_JACCARD_MIN,
        "[diff:{label}] top-{TOPK_K} jaccard {jac:.4} below {TOPK_JACCARD_MIN}"
    );
    assert!(
        cos >= COSINE_SIM_MIN,
        "[diff:{label}] cosine sim {cos:.5} below {COSINE_SIM_MIN}"
    );
}

// ---------------------------------------------------------------------------
// Path resolution (env-var override, mirrors smoke.rs)
// ---------------------------------------------------------------------------

fn artifacts_dir() -> PathBuf {
    let default =
        "/Volumes/Temp Backup/models/moeflux/qwen3-6-35b-a3b-artifacts";
    PathBuf::from(
        std::env::var("MOEFLUX_SMOKE_ARTIFACTS").unwrap_or(default.into()),
    )
}

fn root_dir() -> PathBuf {
    let default =
        "/Volumes/Temp Backup/models/moeflux/qwen3-6-35b-a3b-root";
    PathBuf::from(std::env::var("MOEFLUX_SMOKE_ROOT").unwrap_or(default.into()))
}

/// Open a backend with the standard A3B artifacts layout. Used by
/// every test in the harness so the path resolution lives in one
/// place.
pub fn open_backend<B: DiffBackend>() -> B {
    let art = artifacts_dir();
    let root = root_dir();
    B::open(
        &art.join("model_weights.bin"),
        &art.join("model_weights.json"),
        &art.join("vocab.bin"),
        &root,
        /* experts_per_tok */ 4,
        /* use_2bit */ false,
    )
}

// ---------------------------------------------------------------------------
// Phase 0 sanity test — validates the harness itself
// ---------------------------------------------------------------------------

/// Phase 0 scaffold-validation test. Opens the C backend, runs a
/// single prefill, and exercises the comparison helpers (against
/// itself — the only way to get a 1.0 cosine / Jaccard with a
/// non-deterministic backend is to compare logits to themselves).
///
/// Does not assert any equality between *different* C calls. See
/// the file-level docs for why end-to-end logits aren't a useful
/// oracle: the C path is non-deterministic across `memory_clear`,
/// and both `mf_free_model + Ctx::open` and `memory_clear` leave
/// process-global state we don't control. The real diff strategy
/// (Phase 3+) compares intermediate tensors at layer boundaries.
/// Smoke-test the Rust `WeightFile` against the real A3B artifacts.
/// Loads the manifest + mmap, asserts tensor count matches what the
/// C path's `[manifest]` log line reports (1397 tensors for A3B),
/// and that a couple of well-known tensors are present with the
/// expected dtype.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn weight_file_loads_a3b() {
    let art = artifacts_dir();
    let wf = moeflux::riir::WeightFile::open(
        &art.join("model_weights.bin"),
        &art.join("model_weights.json"),
    )
    .expect("WeightFile::open");
    eprintln!(
        "[diff:weight_file] {} tensors in {:.2} GB",
        wf.len(),
        wf.file_size() as f64 / 1e9,
    );

    // 1397 is the value the C `[manifest]` log prints for A3B.
    assert_eq!(wf.len(), 1397, "tensor count drifted from C");

    // The token-embedding tensor exists in every Qwen MoE export.
    let embed = wf
        .tensor_info("model.embed_tokens.weight")
        .expect("model.embed_tokens.weight");
    assert!(!embed.dtype.is_empty(), "embed_tokens dtype empty");
    eprintln!(
        "[diff:weight_file] embed_tokens dtype={} shape={:?} bits={} size={}",
        embed.dtype, embed.shape, embed.bits, embed.size,
    );
    let bytes = wf
        .tensor_bytes("model.embed_tokens.weight")
        .expect("embed bytes");
    assert_eq!(bytes.len() as u64, embed.size);
}

/// Cross-check that the pure-Rust `riir::VARIANT` shape constants
/// agree with the C runtime values for the same Cargo feature.
/// Catches drift between `model_variant.h` and `riir/variants.rs`.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn variants_match_c() {
    let c: CBackend = open_backend();
    common::c_backend::assert_matches_c(&c.0);
    eprintln!(
        "[diff:variants] {} n_vocab={} n_ctx={} eos={}",
        c.model_name(),
        c.n_vocab(),
        c.n_ctx(),
        c.eos(),
    );
}

/// ULP-bounded diff for the RoPE kernel (Phase 3, slice 3).
///
/// Not bit-exact — see `riir/rope.rs` module docs. Two compiler
/// choices compound: (1) Apple clang at `-O3` auto-vectorizes the
/// scalar `cosf`/`sinf` calls through Apple's libm vector variants,
/// while Rust extern-`"C"` calls don't vectorize; (2) clang with
/// `-ffp-contract=on` fuses the rotation's `q0*cos_a - q1*sin_a`
/// into FMA instructions, which Rust's plain `*` / `-` do not.
///
/// Both are compiler-choice artifacts, not porting bugs. We set the
/// threshold to 128 ULPs — well above the observed ~30 ULP drift
/// from FMA-vs-non-FMA but still tight enough to flag any real
/// algorithmic bug (which would produce thousands of ULPs of drift,
/// or NaN/inf, or sign flips).
///
/// Relative-error perspective: 128 ULPs at f32-near-1.0 ≈ 1.5e-5,
/// far below the noise floor of the surrounding 4-bit-quantized
/// weights and bf16 scales the rest of the model uses.
const MAX_ULP_DRIFT: u32 = 128;

/// Distance between two `f32` values measured in ULPs (units in last
/// place). Same-sign only; sign disagreement returns u32::MAX so it
/// fails any reasonable bound.
fn ulp_diff(a: f32, b: f32) -> u32 {
    if a.to_bits() == b.to_bits() {
        return 0;
    }
    if a.is_nan() || b.is_nan() {
        return u32::MAX;
    }
    if a.is_sign_negative() != b.is_sign_negative() {
        return u32::MAX;
    }
    let ai = a.to_bits();
    let bi = b.to_bits();
    if ai > bi { ai - bi } else { bi - ai }
}

#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn rope_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let head_dim = VARIANT.head_dim;
    let q_len = VARIANT.num_attn_heads * head_dim;
    let k_len = VARIANT.num_kv_heads * head_dim;

    let q_in: Vec<f32> = (0..q_len)
        .map(|i| ((i as f32) * 0.013).sin() * 0.7 + 0.1)
        .collect();
    let k_in: Vec<f32> = (0..k_len)
        .map(|i| ((i as f32) * 0.019).cos() * 0.5 - 0.2)
        .collect();

    let positions: [i32; 5] = [0, 1, 17, 1024, 65535];
    for &pos in &positions {
        let (c_q, c_k) = c.apply_rotary_emb(pos, &q_in, &k_in);
        let (rs_q, rs_k) = rs.apply_rotary_emb(pos, &q_in, &k_in);

        let q_max_ulp = c_q
            .iter()
            .zip(rs_q.iter())
            .map(|(&a, &b)| ulp_diff(a, b))
            .max()
            .unwrap_or(0);
        let k_max_ulp = c_k
            .iter()
            .zip(rs_k.iter())
            .map(|(&a, &b)| ulp_diff(a, b))
            .max()
            .unwrap_or(0);
        let q_diff_count = c_q
            .iter()
            .zip(rs_q.iter())
            .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
            .count();
        let k_diff_count = c_k
            .iter()
            .zip(rs_k.iter())
            .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
            .count();

        eprintln!(
            "[diff:rope pos={pos}] Q max_ulp={q_max_ulp} ({}/{} differ); \
             K max_ulp={k_max_ulp} ({}/{} differ)",
            q_diff_count,
            c_q.len(),
            k_diff_count,
            c_k.len(),
        );

        assert!(
            q_max_ulp <= MAX_ULP_DRIFT,
            "[diff:rope pos={pos}] Q max ULP drift {q_max_ulp} > {MAX_ULP_DRIFT}"
        );
        assert!(
            k_max_ulp <= MAX_ULP_DRIFT,
            "[diff:rope pos={pos}] K max ULP drift {k_max_ulp} > {MAX_ULP_DRIFT}"
        );
    }
}

/// Bit-exact diff for the CPU RMSNorm kernel (Phase 3, slice 2).
///
/// Composes on top of slice 1: feed the embedding output of several
/// token IDs through RMSNorm and compare bit-for-bit against the C
/// path. Three weight tensors exercised:
///
/// - `model.norm.weight` (the final RMSNorm before LM head)
/// - `model.layers.0.input_layernorm.weight` (per-layer attention
///   input norm)
/// - `model.layers.0.post_attention_layernorm.weight` (per-layer MLP
///   input norm)
///
/// All three are BF16 weight tensors of length `HIDDEN_DIM`. CPU
/// RMSNorm is deterministic on a given machine, so we expect every
/// output element to be byte-identical between C and Rust.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn rms_norm_cpu_bit_exact_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let token_ids: [i32; 4] = [0, 1, VARIANT.eos_token_1, VARIANT.vocab_size as i32 - 1];
    let weight_names: [&str; 3] = [
        "model.norm.weight",
        "model.layers.0.input_layernorm.weight",
        "model.layers.0.post_attention_layernorm.weight",
    ];

    for &tok in &token_ids {
        let x = c.embed(tok);
        for w_name in &weight_names {
            let c_out = c.rms_norm_cpu(w_name, &x);
            let rs_out = rs.rms_norm_cpu(w_name, &x);

            let diffs: Vec<(usize, f32, f32)> = c_out
                .iter()
                .zip(rs_out.iter())
                .enumerate()
                .filter_map(|(i, (&a, &b))| {
                    if a.to_bits() != b.to_bits() {
                        Some((i, a, b))
                    } else {
                        None
                    }
                })
                .collect();

            if !diffs.is_empty() {
                let first = &diffs[0];
                panic!(
                    "[diff:rms_norm_cpu token={tok} w={w_name}] {} of {} elements differ; \
                     first at index {} (c={} rs={})",
                    diffs.len(),
                    c_out.len(),
                    first.0,
                    first.1,
                    first.2,
                );
            }

            eprintln!(
                "[diff:rms_norm_cpu token={tok} w={w_name}] {} elements bit-equal; \
                 first 4: {:?}",
                c_out.len(),
                &c_out[..4],
            );
        }
    }
}

/// ULP-bounded diff for the SDPA core (Phase 3, slice 5).
///
/// `cpu_sdpa` does scaled dot-product attention + sigmoid gating in
/// one pass: per-head GQA dot product Q·K, scale, softmax, weighted
/// sum of V, then `out *= sigmoid(q_gate)`. Two libm calls per output
/// element (`expf` in softmax, `expf` in sigmoid) put it firmly in
/// ULP-bounded territory — same compiler-choice considerations as RoPE
/// (auto-vectorized libm vector variants on the C side, scalar libm
/// from Rust extern `"C"` calls), but compounded across more
/// reductions and more transcendental calls per element.
///
/// Synthetic Q/K/V buffers at three `kv_len` points to characterize
/// how drift scales with cache length — the load-bearing assertion
/// here is "Rust output and C output have the same shape" (high
/// cosine similarity, small max-abs-diff relative to the magnitude of
/// the output) rather than "every element matches to N ULPs," because
/// the compounded transcendental calls easily push individual
/// elements past any tight ULP bound.
///
/// Cosine ≥ 0.9999 catches porting bugs (sign flips, GQA mis-grouping,
/// off-by-one indexing all collapse it well below this), and max-abs
/// drift / max-abs output ≤ 1e-3 catches localized blow-ups while
/// staying well above the per-element FMA-vs-non-FMA noise floor.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn sdpa_cpu_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let head_dim = VARIANT.head_dim;
    let num_attn_heads = VARIANT.num_attn_heads;
    let num_kv_heads = VARIANT.num_kv_heads;
    let q_dim = num_attn_heads * head_dim;
    let kv_dim = num_kv_heads * head_dim;

    // Synthetic per-position vectors. Magnitudes loosely match
    // post-RMSNorm + post-RoPE statistics observed in practice.
    let q: Vec<f32> = (0..q_dim)
        .map(|i| ((i as f32) * 0.011).sin() * 0.6 + 0.05)
        .collect();
    let q_gate: Vec<f32> = (0..q_dim)
        .map(|i| ((i as f32) * 0.007).cos() * 1.2 - 0.1)
        .collect();

    // Probe at small / medium / longer cache to see how drift scales.
    for &kv_len in &[1i32, 8, 64, 512] {
        let kv_len_u = kv_len as usize;
        let kv_total = kv_len_u * kv_dim;
        let k_cache: Vec<f32> = (0..kv_total)
            .map(|i| ((i as f32) * 0.013).sin() * 0.5 + 0.02)
            .collect();
        let v_cache: Vec<f32> = (0..kv_total)
            .map(|i| ((i as f32) * 0.017).cos() * 0.4 - 0.05)
            .collect();

        let c_out = c.sdpa_cpu(kv_len, &q, &q_gate, &k_cache, &v_cache);
        let rs_out = rs.sdpa_cpu(kv_len, &q, &q_gate, &k_cache, &v_cache);

        let max_ulp = c_out
            .iter()
            .zip(rs_out.iter())
            .map(|(&a, &b)| ulp_diff(a, b))
            .max()
            .unwrap_or(0);
        let diff_count = c_out
            .iter()
            .zip(rs_out.iter())
            .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
            .count();
        let max_abs_diff = c_out
            .iter()
            .zip(rs_out.iter())
            .map(|(&a, &b)| (a - b).abs())
            .fold(0.0f32, f32::max);
        let max_abs_out = c_out
            .iter()
            .map(|&a| a.abs())
            .fold(0.0f32, f32::max);
        let cos = cosine_sim(&c_out, &rs_out);

        eprintln!(
            "[diff:sdpa kv_len={kv_len}] cosine={cos:.6} max_abs_diff={max_abs_diff:.3e} \
             max_abs_out={max_abs_out:.3e} max_ulp={max_ulp} ({}/{} differ)",
            diff_count,
            c_out.len(),
        );

        assert!(
            cos >= 0.9999,
            "[diff:sdpa kv_len={kv_len}] cosine sim {cos:.6} below 0.9999"
        );
        assert!(
            max_abs_diff <= 1e-3 * max_abs_out.max(1e-6),
            "[diff:sdpa kv_len={kv_len}] max abs diff {max_abs_diff:.3e} \
             > 1e-3 * max abs out ({max_abs_out:.3e})"
        );
    }
}

/// Bit-exact diff for the per-head Q/K RMSNorm kernel (Phase 3, slice 4).
///
/// The per-head variant fires inside `full_attention_forward` after the
/// QKV projection — each Q head's `head_dim`-long slice (and each K
/// head's slice) gets RMS-normed independently against a shared
/// `head_dim`-long bf16 weight. The arithmetic is the same shape as
/// the whole-vector `cpu_rms_norm` (sequential sum-of-squares,
/// `1/sqrt(.)`, multiply-by-bf16-weight), so we expect bit-exact
/// agreement on the same hardware.
///
/// Two weight tensors exercised — Q and K norms for layer 0 (the only
/// full-attention layer in the first interval; both are bf16 of length
/// `HEAD_DIM`). Layer 0's norms are guaranteed present whether the
/// model variant places its first full-attn layer at index 0 or later,
/// since these tensors exist for every full-attention layer.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn rms_norm_per_head_cpu_bit_exact_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let head_dim = VARIANT.head_dim;
    let num_attn_heads = VARIANT.num_attn_heads;
    let num_kv_heads = VARIANT.num_kv_heads;

    // Find the first full-attention layer index. The variant's
    // FULL_ATTN_INTERVAL determines this; layer i is full-attn iff
    // (i+1) % FULL_ATTN_INTERVAL == 0. For Qwen3 MoE this is layer 3
    // (interval 4) — i.e. the 4th, 8th, ... layers.
    let mut fa_layer: Option<usize> = None;
    for i in 0..VARIANT.num_layers {
        if (i + 1) % VARIANT.full_attn_interval == 0 {
            fa_layer = Some(i);
            break;
        }
    }
    let fa_layer = fa_layer.expect("at least one full-attention layer");
    let q_norm_name =
        format!("model.layers.{fa_layer}.self_attn.q_norm.weight");
    let k_norm_name =
        format!("model.layers.{fa_layer}.self_attn.k_norm.weight");

    // Synthetic per-head input vectors — large enough to exercise the
    // sum-of-squares reduction across all heads, with non-trivial
    // magnitudes so the inv_rms term is interesting.
    let q_in: Vec<f32> = (0..num_attn_heads * head_dim)
        .map(|i| ((i as f32) * 0.011).sin() * 0.6 + 0.05)
        .collect();
    let k_in: Vec<f32> = (0..num_kv_heads * head_dim)
        .map(|i| ((i as f32) * 0.023).cos() * 0.4 - 0.1)
        .collect();

    for (label, w_name, num_heads, x_in) in [
        ("Q", q_norm_name.as_str(), num_attn_heads, &q_in),
        ("K", k_norm_name.as_str(), num_kv_heads, &k_in),
    ] {
        let c_out = c.rms_norm_per_head_cpu(w_name, num_heads, head_dim, x_in);
        let rs_out = rs.rms_norm_per_head_cpu(w_name, num_heads, head_dim, x_in);

        let diffs: Vec<(usize, f32, f32)> = c_out
            .iter()
            .zip(rs_out.iter())
            .enumerate()
            .filter_map(|(i, (&a, &b))| {
                if a.to_bits() != b.to_bits() {
                    Some((i, a, b))
                } else {
                    None
                }
            })
            .collect();

        if !diffs.is_empty() {
            let first = &diffs[0];
            panic!(
                "[diff:rms_norm_per_head_cpu {label} layer={fa_layer}] {} of {} elements differ; \
                 first at index {} (c={} rs={})",
                diffs.len(),
                c_out.len(),
                first.0,
                first.1,
                first.2,
            );
        }

        eprintln!(
            "[diff:rms_norm_per_head_cpu {label} layer={fa_layer} \
             num_heads={num_heads} head_dim={head_dim}] {} elements bit-equal; \
             first 4: {:?}",
            c_out.len(),
            &c_out[..4],
        );
    }
}

/// Bit-exact diff for the embedding kernel (Phase 3, slice 1).
///
/// The embedding lookup is fully deterministic CPU code on both
/// sides — quantized 4-bit dequant + bf16-via-bit-shift. Outputs
/// must match to the last bit. Running both backends against the
/// same mmap'd weight blob, anything but byte-equal output indicates
/// a porting bug.
///
/// Picks 8 token IDs spanning the vocabulary's interesting points:
/// 0 (BOS in most setups), 1, the canonical EOS, the secondary EOS,
/// the think-start / think-end specials, a mid-vocabulary id, and
/// `vocab_size - 1`. Out-of-range ids are tested separately for the
/// error path.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn embed_bit_exact_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let vocab = VARIANT.vocab_size as i32;
    let token_ids: [i32; 8] = [
        0,
        1,
        VARIANT.eos_token_1,
        VARIANT.eos_token_2,
        VARIANT.think_start_token,
        VARIANT.think_end_token,
        vocab / 2,
        vocab - 1,
    ];

    for &tok in &token_ids {
        let c_emb = c.embed(tok);
        let rs_emb = rs.embed(tok);
        assert_eq!(
            c_emb.len(),
            VARIANT.hidden_dim,
            "[diff:embed token={tok}] C output length mismatch"
        );
        assert_eq!(
            rs_emb.len(),
            VARIANT.hidden_dim,
            "[diff:embed token={tok}] Rust output length mismatch"
        );

        let diffs: Vec<(usize, f32, f32)> = c_emb
            .iter()
            .zip(rs_emb.iter())
            .enumerate()
            .filter_map(|(i, (&a, &b))| {
                if a.to_bits() != b.to_bits() {
                    Some((i, a, b))
                } else {
                    None
                }
            })
            .collect();

        if !diffs.is_empty() {
            let first = &diffs[0];
            panic!(
                "[diff:embed token={tok}] {} of {} elements differ; \
                 first at index {} (c={} rs={})",
                diffs.len(),
                c_emb.len(),
                first.0,
                first.1,
                first.2,
            );
        }

        eprintln!(
            "[diff:embed token={tok}] {} elements bit-equal; first 4: {:?}",
            c_emb.len(),
            &c_emb[..4],
        );
    }
}

/// Bit-exact diff for the LM head matvec (Phase 3, slice 6).
///
/// Symmetric to the embedding kernel: 4-bit dequant + per-group bf16
/// scale/bias, but as a fused matvec rather than a single-row lookup.
/// `mf_lm_head_cpu` routes through `cpu_dequant_matvec` regardless of
/// Metal availability, so both backends do deterministic CPU work
/// against the same mmap'd weight blob.
///
/// Two synthetic hidden vectors are run through the matvec — a
/// trig-modulated wave (the same shape used by RoPE / SDPA tests) and
/// a hidden state derived from the embedding-then-RMSNorm pipeline of
/// a real token, so we exercise both adversarial and realistic input
/// magnitudes. Bit-exactness is the target; the lazy-mode floor is
/// "no diffs at all," and any drift falls back to the same per-element
/// reporting the embedding test uses.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn lm_head_cpu_bit_exact_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let hidden_dim = VARIANT.hidden_dim;

    // Input 1: synthetic trig-modulated hidden vector, magnitudes
    // similar to post-norm hidden states.
    let x_synth: Vec<f32> = (0..hidden_dim)
        .map(|i| ((i as f32) * 0.011).sin() * 0.6 + 0.05)
        .collect();

    // Input 2: realistic hidden derived from embedding(EOS) → final norm.
    // Composes on top of slices 1 + 2, so a regression here is more
    // likely to be in the LM head than upstream.
    let emb = c.embed(VARIANT.eos_token_1);
    let x_real = c.rms_norm_cpu("model.norm.weight", &emb);

    for (label, x) in [("synth", &x_synth), ("real", &x_real)] {
        let c_out = c.lm_head_cpu(x);
        let rs_out = rs.lm_head_cpu(x);

        assert_eq!(c_out.len(), VARIANT.vocab_size, "C output len");
        assert_eq!(rs_out.len(), VARIANT.vocab_size, "Rust output len");

        let diffs: Vec<(usize, f32, f32)> = c_out
            .iter()
            .zip(rs_out.iter())
            .enumerate()
            .filter_map(|(i, (&a, &b))| {
                if a.to_bits() != b.to_bits() {
                    Some((i, a, b))
                } else {
                    None
                }
            })
            .collect();

        if !diffs.is_empty() {
            let max_ulp = c_out
                .iter()
                .zip(rs_out.iter())
                .map(|(&a, &b)| ulp_diff(a, b))
                .max()
                .unwrap_or(0);
            let max_abs_diff = c_out
                .iter()
                .zip(rs_out.iter())
                .map(|(&a, &b)| (a - b).abs())
                .fold(0.0f32, f32::max);
            let max_abs_out = c_out
                .iter()
                .map(|&a| a.abs())
                .fold(0.0f32, f32::max);
            let cos = cosine_sim(&c_out, &rs_out);
            let first = &diffs[0];
            panic!(
                "[diff:lm_head {label}] {} of {} elements differ; \
                 max_ulp={max_ulp} max_abs_diff={max_abs_diff:.3e} \
                 max_abs_out={max_abs_out:.3e} cosine={cos:.6}; \
                 first at index {} (c={} rs={})",
                diffs.len(),
                c_out.len(),
                first.0,
                first.1,
                first.2,
            );
        }

        eprintln!(
            "[diff:lm_head {label}] {} elements bit-equal; \
             argmax={} first 4: {:?}",
            c_out.len(),
            argmax(&c_out),
            &c_out[..4],
        );
    }
}

/// ULP-bounded diff for the MoE router (Phase 3, slice 7).
///
/// Pipeline: softmax → top-K → normalize. The softmax's per-element
/// `expf` is the only ULP source — Apple clang `-O3` auto-vectorizes
/// scalar `expf` calls into Apple libm's `vexpf`, while Rust extern
/// `"C"` calls don't, so we expect single-digit ULP drift on the
/// softmaxed scores. The selected expert *index set* should be
/// identical across both sides — top-K selection is deterministic
/// once you have identical inputs, and the softmax ULP gap is
/// orders of magnitude below the score separation that would change
/// which experts are picked.
///
/// Two synthetic gate-score patterns:
///
/// 1. **clear-winner**: NUM_EXPERTS scores with K large bumps
///    several orders of magnitude above the noise floor. The set of
///    top-K indices must match exactly.
/// 2. **mild-spread**: scores drawn from a smooth trig sweep. The
///    set match is still expected (gaps still much wider than ULP
///    drift) but stresses tighter gaps in the top-K cutoff zone.
///
/// Weights compared after canonicalizing slot order by index — the
/// C selection-sort produces a slot ordering that depends on the
/// historical replacement order, which is itself input-dependent
/// but identical across our two backends since both walk the score
/// array in the same order.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn moe_router_cpu_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let n_experts = VARIANT.num_experts;
    let k = VARIANT.num_experts_per_tok;
    assert!(n_experts >= k && k >= 1);

    // Pattern 1: clear-winner. Smooth low-magnitude background plus K
    // large bumps placed at deterministic indices.
    let mut clear: Vec<f32> = (0..n_experts)
        .map(|i| ((i as f32) * 0.011).sin() * 0.01 + 0.0)
        .collect();
    let bump_indices: Vec<usize> =
        (0..k).map(|i| (i * (n_experts / k.max(1))) % n_experts).collect();
    for (slot, &idx) in bump_indices.iter().enumerate() {
        clear[idx] = 5.0 + slot as f32 * 0.5;
    }

    // Pattern 2: mild-spread. All scores within a narrower band so
    // the top-K cutoff is closer to the noise floor.
    let spread: Vec<f32> = (0..n_experts)
        .map(|i| ((i as f32) * 0.013).cos() * 0.7 + ((i as f32) * 0.041).sin() * 0.3)
        .collect();

    for (label, scores) in [("clear", &clear), ("spread", &spread)] {
        let (c_idx, c_w) = c.moe_router_cpu(scores.clone(), k);
        let (rs_idx, rs_w) = rs.moe_router_cpu(scores.clone(), k);

        // Set equality on indices.
        let mut c_sorted = c_idx.clone();
        let mut rs_sorted = rs_idx.clone();
        c_sorted.sort();
        rs_sorted.sort();
        assert_eq!(
            c_sorted, rs_sorted,
            "[diff:moe_router {label}] index set mismatch (c={c_idx:?} rs={rs_idx:?})"
        );

        // Map C/Rust slot → score for canonical comparison by index.
        let c_pairs: Vec<(i32, f32)> =
            c_idx.iter().copied().zip(c_w.iter().copied()).collect();
        let rs_pairs: Vec<(i32, f32)> =
            rs_idx.iter().copied().zip(rs_w.iter().copied()).collect();
        let mut c_by_idx: std::collections::HashMap<i32, f32> = c_pairs.into_iter().collect();
        let mut rs_by_idx: std::collections::HashMap<i32, f32> = rs_pairs.into_iter().collect();

        let mut max_ulp = 0u32;
        let mut max_abs_diff = 0.0f32;
        for &idx in &c_sorted {
            let cw = c_by_idx.remove(&idx).unwrap();
            let rw = rs_by_idx.remove(&idx).unwrap();
            max_ulp = max_ulp.max(ulp_diff(cw, rw));
            max_abs_diff = max_abs_diff.max((cw - rw).abs());
        }
        let weight_sum_c: f32 = c_w.iter().sum();
        let weight_sum_rs: f32 = rs_w.iter().sum();

        eprintln!(
            "[diff:moe_router {label} n={n_experts} k={k}] \
             max_ulp={max_ulp} max_abs_diff={max_abs_diff:.3e} \
             c_sum={weight_sum_c:.6} rs_sum={weight_sum_rs:.6}"
        );

        // ULP bound: same regime as RoPE. Single libm call per element
        // in softmax, bounded per call; normalization is one further
        // sum + divide on K floats.
        assert!(
            max_ulp <= MAX_ULP_DRIFT,
            "[diff:moe_router {label}] max ULP drift {max_ulp} > {MAX_ULP_DRIFT}"
        );
        assert!(
            (weight_sum_c - 1.0).abs() < 1e-5,
            "[diff:moe_router {label}] C weights don't sum to 1 ({weight_sum_c})"
        );
        assert!(
            (weight_sum_rs - 1.0).abs() < 1e-5,
            "[diff:moe_router {label}] Rust weights don't sum to 1 ({weight_sum_rs})"
        );
    }
}

/// Bit-exact diff for bare RMSNorm (Phase 3, slice 8a-1).
///
/// Used inside `linear_attention_forward` to RMS-normalize each head
/// of Q and K (with no learned weight tensor — just a plain
/// normalization). Same arithmetic shape as the existing weighted
/// `cpu_rms_norm`, just without the bf16-multiply step. CPU,
/// deterministic, bit-exact territory.
///
/// Probe shape: a `LINEAR_KEY_DIM`-long head, since that's the
/// production callsite. Mid-magnitude trig input.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn rms_norm_bare_cpu_bit_exact_c_vs_rust() {
    use moeflux::riir::variants::Variant;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let dim = Variant::LINEAR_KEY_DIM;
    let x: Vec<f32> = (0..dim)
        .map(|i| ((i as f32) * 0.011).sin() * 0.6 + 0.05)
        .collect();
    let eps = 1e-6f32;

    let c_out = c.rms_norm_bare_cpu(eps, &x);
    let rs_out = rs.rms_norm_bare_cpu(eps, &x);

    let diffs: Vec<(usize, f32, f32)> = c_out
        .iter()
        .zip(rs_out.iter())
        .enumerate()
        .filter_map(|(i, (&a, &b))| {
            if a.to_bits() != b.to_bits() {
                Some((i, a, b))
            } else {
                None
            }
        })
        .collect();

    if !diffs.is_empty() {
        let first = &diffs[0];
        panic!(
            "[diff:rms_norm_bare] {} of {} elements differ; \
             first at index {} (c={} rs={})",
            diffs.len(),
            c_out.len(),
            first.0,
            first.1,
            first.2,
        );
    }

    eprintln!(
        "[diff:rms_norm_bare dim={dim}] {} elements bit-equal; first 4: {:?}",
        c_out.len(),
        &c_out[..4],
    );
}

/// ULP-bounded diff for the conv1d step + SiLU (Phase 3, slice 8a-2).
///
/// Used inside `linear_attention_forward` to do the depthwise 1D conv
/// over the linear-attention (Q|K|V) channels with the previous
/// `(kernel_size-1)` time-steps of state. Tested against layer-0's
/// real `conv1d.weight` tensor so the bf16 decode path is exercised.
///
/// The dot-product half is bit-exact (matched via `mul_add` to clang's
/// FMA contraction) but the SiLU tail introduces one `expf` per
/// channel — same compiler-choice ULP territory as the rest of the
/// libm-bearing kernels. Tolerance: ULP-bounded with the same
/// `MAX_ULP_DRIFT = 128` budget RoPE uses.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn conv1d_step_cpu_close_c_vs_rust() {
    use moeflux::riir::variants::Variant;
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let channels = VARIANT.linear_conv_dim();
    let kernel_size = Variant::CONV_KERNEL_SIZE;
    let weight_name = "model.layers.0.linear_attn.conv1d.weight";

    // (kernel_size-1) past time-steps × channels values.
    let conv_state: Vec<f32> = (0..(kernel_size - 1) * channels)
        .map(|i| ((i as f32) * 0.013).sin() * 0.4 + 0.02)
        .collect();
    let new_input: Vec<f32> = (0..channels)
        .map(|i| ((i as f32) * 0.019).cos() * 0.5 - 0.1)
        .collect();

    let c_out =
        c.conv1d_step_cpu(weight_name, channels, kernel_size, &conv_state, &new_input);
    let rs_out =
        rs.conv1d_step_cpu(weight_name, channels, kernel_size, &conv_state, &new_input);

    let max_ulp = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(&a, &b)| ulp_diff(a, b))
        .max()
        .unwrap_or(0);
    let diff_count = c_out
        .iter()
        .zip(rs_out.iter())
        .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
        .count();
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(&a, &b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let max_abs_out =
        c_out.iter().map(|&a| a.abs()).fold(0.0f32, f32::max);

    eprintln!(
        "[diff:conv1d_step channels={channels} kernel={kernel_size}] \
         max_ulp={max_ulp} max_abs_diff={max_abs_diff:.3e} \
         max_abs_out={max_abs_out:.3e} ({diff_count}/{} differ)",
        c_out.len(),
    );

    assert!(
        max_ulp <= MAX_ULP_DRIFT,
        "[diff:conv1d_step] max ULP drift {max_ulp} > {MAX_ULP_DRIFT}"
    );
}

/// ULP-bounded diff for RMSNormGated (Phase 3, slice 8a-3).
///
/// Used inside `linear_attention_forward` to apply `rms_norm × silu × weight`
/// to each per-head output of the gate-delta-net recurrence. Tested
/// against layer-0's real `linear_attn.norm.weight` tensor.
///
/// One libm `expf` per element via SiLU, plus the bf16 weight decode
/// the existing weighted RMSNorm already exercises. Same ULP budget
/// as the other libm-bearing kernels.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn rms_norm_gated_cpu_close_c_vs_rust() {
    use moeflux::riir::variants::Variant;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let dim = Variant::LINEAR_VALUE_DIM;
    let weight_name = "model.layers.0.linear_attn.norm.weight";
    let eps = 1e-6f32;

    let x: Vec<f32> = (0..dim)
        .map(|i| ((i as f32) * 0.011).sin() * 0.6 + 0.05)
        .collect();
    let z: Vec<f32> = (0..dim)
        .map(|i| ((i as f32) * 0.017).cos() * 1.2 - 0.1)
        .collect();

    let c_out = c.rms_norm_gated_cpu(weight_name, eps, &x, &z);
    let rs_out = rs.rms_norm_gated_cpu(weight_name, eps, &x, &z);

    let max_ulp = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(&a, &b)| ulp_diff(a, b))
        .max()
        .unwrap_or(0);
    let diff_count = c_out
        .iter()
        .zip(rs_out.iter())
        .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
        .count();
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(&a, &b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let max_abs_out =
        c_out.iter().map(|&a| a.abs()).fold(0.0f32, f32::max);

    eprintln!(
        "[diff:rms_norm_gated dim={dim}] max_ulp={max_ulp} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         ({diff_count}/{} differ)",
        c_out.len(),
    );

    assert!(
        max_ulp <= MAX_ULP_DRIFT,
        "[diff:rms_norm_gated] max ULP drift {max_ulp} > {MAX_ULP_DRIFT}"
    );
}

/// ULP-bounded diff for the gated-delta-net recurrence (Phase 3, slice 8b).
///
/// The novel kernel inside `linear_attention_forward`. Arithmetic
/// shape per v-head:
///
///   g       = exp(-exp(A_log) * softplus(alpha + dt_bias))
///   b_gate  = sigmoid(beta)
///   S      *= g
///   for vi:
///     kv_mem = Σ_ki S[vi,ki] * k[ki]
///     delta  = (v[vi] - kv_mem) * b_gate
///     S[vi]+= k * delta
///   for vi:
///     out[vi] = Σ_ki S[vi,ki] * q[ki]
///
/// Three FMA-shaped contractions in the per-vi inner loops; all use
/// `mul_add` on the Rust side to match clang's AArch64 codegen
/// (per the LM head finding). The per-head precomputation has libm
/// `expf`/`logf`/`sigmoid` calls — same scalar-libm regime as the
/// other linear-attn primitives.
///
/// Probe shape: layer 0 (linear-attn under FULL_ATTN_INTERVAL=4), one
/// step from a zero initial state. Tests both the post-step state
/// (the in-place mutation) and the per-head output values.
///
/// Compares both `ssm_state` and `out_values` element-wise. Tolerance:
/// ULP-bounded with the shared `MAX_ULP_DRIFT = 128` budget; if it
/// lands tighter (bit-exact, like the 8a primitives), the eprintln
/// will say so.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn gated_delta_recurrence_cpu_close_c_vs_rust() {
    use moeflux::riir::variants::Variant;
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let v_heads = VARIANT.linear_num_v_heads;
    let k_heads = VARIANT.linear_num_k_heads;
    let key_dim = Variant::LINEAR_KEY_DIM;
    let value_dim = Variant::LINEAR_VALUE_DIM;
    let layer_idx = 0usize; // layer 0 is linear-attn (full_attn_interval=4)

    // Synthetic per-step inputs, magnitudes matching post-conv-and-bare-norm
    // statistics. alpha/beta land near zero so softplus and sigmoid have
    // non-degenerate working ranges.
    let alpha: Vec<f32> = (0..v_heads)
        .map(|i| ((i as f32) * 0.013).sin() * 0.3)
        .collect();
    let beta: Vec<f32> = (0..v_heads)
        .map(|i| ((i as f32) * 0.017).cos() * 0.5)
        .collect();
    let q: Vec<f32> = (0..k_heads * key_dim)
        .map(|i| ((i as f32) * 0.011).sin() * 0.4 + 0.05)
        .collect();
    let k_in: Vec<f32> = (0..k_heads * key_dim)
        .map(|i| ((i as f32) * 0.019).cos() * 0.5 - 0.1)
        .collect();
    let v_in: Vec<f32> = (0..v_heads * value_dim)
        .map(|i| ((i as f32) * 0.023).sin() * 0.6 + 0.02)
        .collect();
    let ssm_state_in: Vec<f32> = vec![0.0f32; v_heads * value_dim * key_dim];

    let (c_state, c_out) = c.gated_delta_recurrence_cpu(
        layer_idx, &alpha, &beta, &q, &k_in, &v_in,
        v_heads, k_heads, key_dim, value_dim, ssm_state_in.clone(),
    );
    let (rs_state, rs_out) = rs.gated_delta_recurrence_cpu(
        layer_idx, &alpha, &beta, &q, &k_in, &v_in,
        v_heads, k_heads, key_dim, value_dim, ssm_state_in,
    );

    let state_max_ulp = c_state
        .iter()
        .zip(rs_state.iter())
        .map(|(&a, &b)| ulp_diff(a, b))
        .max()
        .unwrap_or(0);
    let state_diff_count = c_state
        .iter()
        .zip(rs_state.iter())
        .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
        .count();
    let out_max_ulp = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(&a, &b)| ulp_diff(a, b))
        .max()
        .unwrap_or(0);
    let out_diff_count = c_out
        .iter()
        .zip(rs_out.iter())
        .filter(|&(&a, &b)| a.to_bits() != b.to_bits())
        .count();
    let out_max_abs = c_out
        .iter()
        .map(|&a| a.abs())
        .fold(0.0f32, f32::max);
    let out_max_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(&a, &b)| (a - b).abs())
        .fold(0.0f32, f32::max);

    eprintln!(
        "[diff:gated_delta_recurrence layer={layer_idx} v_heads={v_heads} \
         k_heads={k_heads} key_dim={key_dim} value_dim={value_dim}] \
         state max_ulp={state_max_ulp} ({}/{} differ); \
         out max_ulp={out_max_ulp} max_abs_diff={:.3e} max_abs_out={:.3e} \
         ({}/{} differ)",
        state_diff_count,
        c_state.len(),
        out_max_diff,
        out_max_abs,
        out_diff_count,
        c_out.len(),
    );

    assert!(
        state_max_ulp <= MAX_ULP_DRIFT,
        "[diff:gated_delta_recurrence] state max ULP drift \
         {state_max_ulp} > {MAX_ULP_DRIFT}"
    );
    assert!(
        out_max_ulp <= MAX_ULP_DRIFT,
        "[diff:gated_delta_recurrence] out max ULP drift \
         {out_max_ulp} > {MAX_ULP_DRIFT}"
    );
}

/// Phase 3 slice 9a — single-expert GPU FFN forward.
///
/// Both backends consume identical synthetic bytes (PRNG-seeded 4-bit
/// weights with BF16 0x3C00 scales / 0 biases per `expert_forward::synth`)
/// and run the same four Metal pipelines (`dequant_matvec_4bit_v3` ×3
/// + `swiglu_fused`). First GPU kernel under diff — Metal SIMD-reduce
/// ordering is not specified to be deterministic across pipeline-state
/// recompiles, so the tolerance regime is cosine/Jaccard rather than
/// bit-exact / ULP-bounded.
///
/// Empirically tighter floors than the end-to-end `COSINE_SIM_MIN`
/// because there's only one stage of nondeterminism stacked here, not
/// 60 layers' worth.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn gpu_expert_forward_close_c_vs_rust() {
    use moeflux::riir::expert_forward::synth;
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let expert_data = synth::expert_data_seeded();
    let h_post = synth::h_post_seeded();
    assert_eq!(expert_data.len(), VARIANT.expert_size_4bit());
    assert_eq!(h_post.len(), VARIANT.hidden_dim);

    let c_out = c.gpu_expert_forward(&expert_data, &h_post);
    let rs_out = rs.gpu_expert_forward(&expert_data, &h_post);
    assert_eq!(c_out.len(), VARIANT.hidden_dim);
    assert_eq!(rs_out.len(), VARIANT.hidden_dim);

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_out = c_out
        .iter()
        .chain(rs_out.iter())
        .map(|x| x.abs())
        .fold(0.0f32, f32::max);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = if max_abs_out > 0.0 {
        max_abs_diff / max_abs_out
    } else {
        0.0
    };

    eprintln!(
        "[diff:gpu_expert_forward] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         relative={rel:.3e}"
    );

    // Sanity — outputs must be finite and not all-zero. If either side
    // bombs we've got something more than nondeterminism going on.
    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:gpu_expert_forward] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:gpu_expert_forward] Rust output has NaN/Inf"
    );
    assert!(
        c_out.iter().any(|&x| x != 0.0),
        "[diff:gpu_expert_forward] C output is all zero"
    );
    assert!(
        rs_out.iter().any(|&x| x != 0.0),
        "[diff:gpu_expert_forward] Rust output is all zero"
    );

    // Tolerances: cosine 0.9999 floor (one stage of Metal SIMD-reduce
    // nondeterminism); max_abs_diff scaled to 1e-3 of max output to
    // accept reorder-induced drift on small-magnitude entries.
    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:gpu_expert_forward] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:gpu_expert_forward] relative max_abs_diff {rel:.3e} \
         above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 3 slice 9e — GPU RMSNorm fused chain.
///
/// `rms_norm_sum_sq` is the first kernel in the diff suite using
/// **threadgroup-shared memory across SIMD groups** (256 threads
/// reduce to 1 scalar via simd_sum + 32-element shared array +
/// second-stage simd_sum). If Metal nondeterminism is going to
/// engage, this is the most plausible spot in the slices ported so
/// far.
///
/// Test pattern: load real `model.norm.weight` bytes via the C side's
/// existing wrapper (the Rust port hasn't published the weight file
/// over its public API surface; we read from the C-side ctx since
/// both ctxs were opened over the same artifacts). Run the chain on
/// the same x on both backends; compare.
///
/// Empirical floors: cosine ≥ 0.9999, rel ≤ 1e-3 (the GPU "atomic-op
/// tolerance" envelope). If both kernels turn out to also be
/// deterministic-per-PSO (likely — `simd_sum` is documented as such,
/// the threadgroup-shared write/read is barrier-fenced), this lands
/// bit-exact like 9a/9b.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn gpu_rms_norm_fused_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    // Load `model.norm.weight` as raw bf16 bytes via the Rust
    // weight-file wrapper (which both backends opened over the same
    // artifacts). Only the bytes are needed; same on both sides.
    let art = artifacts_dir();
    let wf = moeflux::riir::WeightFile::open(
        &art.join("model_weights.bin"),
        &art.join("model_weights.json"),
    )
    .expect("WeightFile::open");
    let weight = wf
        .tensor_bytes("model.norm.weight")
        .expect("model.norm.weight present in manifest");
    assert_eq!(weight.len(), VARIANT.hidden_dim * 2);

    // Synthetic x: not symmetric around zero so sum_sq is meaningful.
    let x: Vec<f32> = (0..VARIANT.hidden_dim)
        .map(|i| (i as f32 * 0.013).sin() * 0.5 + 0.1)
        .collect();

    let c_out = c.gpu_rms_norm_fused(&x, weight);
    let rs_out = rs.gpu_rms_norm_fused(&x, weight);
    assert_eq!(c_out.len(), VARIANT.hidden_dim);
    assert_eq!(rs_out.len(), VARIANT.hidden_dim);

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_out = c_out
        .iter()
        .chain(rs_out.iter())
        .map(|x| x.abs())
        .fold(0.0f32, f32::max);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = if max_abs_out > 0.0 {
        max_abs_diff / max_abs_out
    } else {
        0.0
    };

    eprintln!(
        "[diff:gpu_rms_norm_fused] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         relative={rel:.3e}"
    );

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:gpu_rms_norm_fused] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:gpu_rms_norm_fused] Rust output has NaN/Inf"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:gpu_rms_norm_fused] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:gpu_rms_norm_fused] relative max_abs_diff {rel:.3e} \
         above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 3 slice 9c — expert blob I/O.
///
/// Reads a few (layer, expert) pairs through both backends and
/// asserts byte-for-byte equality. The C path uses
/// `pread(ctx->layer_fds[layer_idx], …)`; the Rust path uses
/// `File::read_at(self.layers[layer_idx], …)`. Both end up issuing
/// a `pread64` against the same file at the same offset, so the
/// expected outcome is bit-exact.
///
/// Fixed sample of probe pairs — covers a full-attn layer (idx 3,
/// `(i+1) % 4 == 0`), a linear-attn layer (idx 0), and a couple of
/// mid-stack layers. Expert indices 0, 7, 255 stress the
/// first-block / mid-block / last-block byte regions of the file.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn load_expert_bytes_byte_exact_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let c: CBackend = open_backend();
    let rs: RsBackend = open_backend();

    let v = VARIANT;
    let probes: &[(i32, i32)] = &[
        (0, 0),
        (0, 7),
        (3, 0),
        (3, 255),
        ((v.num_layers / 2) as i32, 42),
        ((v.num_layers - 1) as i32, (v.num_experts - 1) as i32),
    ];

    for &(layer, expert) in probes {
        let c_bytes = c.load_expert_bytes(layer, expert);
        let rs_bytes = rs.load_expert_bytes(layer, expert);
        assert_eq!(c_bytes.len(), v.expert_size_4bit());
        assert_eq!(rs_bytes.len(), v.expert_size_4bit());

        let first_diff =
            c_bytes.iter().zip(rs_bytes.iter()).position(|(a, b)| a != b);
        eprintln!(
            "[diff:load_expert_bytes layer={layer} expert={expert}] \
             {} bytes; first_diff={first_diff:?}",
            c_bytes.len(),
        );

        assert!(
            first_diff.is_none(),
            "[diff:load_expert_bytes layer={layer} expert={expert}] \
             byte mismatch at offset {first_diff:?} \
             (c=0x{:02x} rs=0x{:02x})",
            first_diff.map(|i| c_bytes[i]).unwrap_or(0),
            first_diff.map(|i| rs_bytes[i]).unwrap_or(0),
        );
    }
}

/// Phase 3 slice 9b — batched K-expert FFN + GPU combine.
///
/// K=4 synthetic experts (distinct PRNG seeds per slot), normalized
/// random weights, deterministic h_post / h_mid / shared_out, and
/// `shared_gate_score = -1.0` so `sigmoid(-1) ≈ 0.269` brings a
/// non-trivial fraction of `shared_out` into the combine.
///
/// Both backends consume identical bytes; the only difference is the
/// host-side encoding path (which buffers, which encoders, which
/// dispatch helper). `weighted_sum`/`moe_combine_residual` per-thread
/// loops have no atomic ops, so empirically this *might* land
/// bit-exact like 9a — but the cosine ≥ 0.9999 / rel ≤ 1e-3 floors
/// stay loose to absorb any genuine SIMD-reduce nondeterminism that
/// would surface here before it matters in 9c+.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn gpu_batched_experts_forward_close_c_vs_rust() {
    use moeflux::riir::expert_forward::synth;
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let k: usize = 4;
    let expert_data = synth::k_expert_data_seeded(k);
    let h_post = synth::h_post_seeded();
    let h_mid = synth::h_mid_seeded();
    let shared_out = synth::shared_out_seeded();
    let weights = synth::expert_weights_seeded(k);
    let shared_gate_score: f32 = -1.0;

    assert_eq!(expert_data.len(), k * VARIANT.expert_size_4bit());
    assert_eq!(weights.len(), k);
    let weight_sum: f32 = weights.iter().sum();
    assert!(
        (weight_sum - 1.0).abs() < 1e-5,
        "synth weights don't sum to 1: {weight_sum}"
    );

    let c_out = c.gpu_batched_experts_forward(
        k as i32,
        &expert_data,
        &h_post,
        &h_mid,
        &shared_out,
        &weights,
        shared_gate_score,
    );
    let rs_out = rs.gpu_batched_experts_forward(
        k as i32,
        &expert_data,
        &h_post,
        &h_mid,
        &shared_out,
        &weights,
        shared_gate_score,
    );
    assert_eq!(c_out.len(), VARIANT.hidden_dim);
    assert_eq!(rs_out.len(), VARIANT.hidden_dim);

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_out = c_out
        .iter()
        .chain(rs_out.iter())
        .map(|x| x.abs())
        .fold(0.0f32, f32::max);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = if max_abs_out > 0.0 {
        max_abs_diff / max_abs_out
    } else {
        0.0
    };

    eprintln!(
        "[diff:gpu_batched_experts_forward k={k}] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         relative={rel:.3e}"
    );

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:gpu_batched_experts_forward] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:gpu_batched_experts_forward] Rust output has NaN/Inf"
    );
    assert!(
        c_out.iter().any(|&x| x != 0.0),
        "[diff:gpu_batched_experts_forward] C output is all zero"
    );
    assert!(
        rs_out.iter().any(|&x| x != 0.0),
        "[diff:gpu_batched_experts_forward] Rust output is all zero"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:gpu_batched_experts_forward] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:gpu_batched_experts_forward] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

// ---------------------------------------------------------------------------
// Slice 5d-7a — per-kernel diff coverage for GPU full-attention
// ---------------------------------------------------------------------------
//
// Synthetic deterministic inputs against the same per-kernel
// tolerance regime as slices 9a / 9b / 9e (cosine ≥ 0.9999,
// rel_max_abs_diff ≤ 1e-3). The four kernels have only SIMD or
// threadgroup-shared reductions (no atomics), so empirical
// expectation is bit-exact per-PSO; the floor is defensive.

/// Generate `n` deterministic floats from a low-discrepancy sequence
/// shifted by a per-test seed. Avoids per-test PRNG plumbing while
/// keeping the inputs non-symmetric (so reductions are meaningful).
fn synth_floats(seed: u32, n: usize, scale: f32) -> Vec<f32> {
    (0..n)
        .map(|i| {
            let phase = (seed as f32 * 0.13) + (i as f32 * 0.017);
            phase.sin() * scale + (phase * 1.7).cos() * (scale * 0.5)
        })
        .collect()
}

/// `attn_scores_batched` (slice 5d-7a). Synthetic Q + K, varying
/// `seq_len`. Stride-tight output. Empirically bit-exact per-PSO; the
/// cosine/rel floors are defensive.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn attn_scores_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let v = VARIANT;
    let num_heads = v.num_attn_heads as u32;
    let num_kv_heads = v.num_kv_heads as u32;
    let head_dim = v.head_dim as u32;
    let kv_dim = num_kv_heads * head_dim;
    let scale = 1.0 / (head_dim as f32).sqrt();

    for &seq_len in &[32u32, 64, 128, 512] {
        let q = synth_floats(seq_len, (num_heads * head_dim) as usize, 0.4);
        let k_cache =
            synth_floats(seq_len + 1, (seq_len * kv_dim) as usize, 0.3);

        let c_out = c.attn_scores_batched(
            num_heads, num_kv_heads, head_dim, seq_len, &q, &k_cache, scale,
        );
        let rs_out = rs.attn_scores_batched(
            num_heads, num_kv_heads, head_dim, seq_len, &q, &k_cache, scale,
        );
        assert_eq!(c_out.len(), (num_heads * seq_len) as usize);
        assert_eq!(rs_out.len(), c_out.len());

        let cos = cosine_sim(&c_out, &rs_out);
        let max_abs_out = c_out
            .iter()
            .chain(rs_out.iter())
            .map(|x| x.abs())
            .fold(0.0f32, f32::max);
        let max_abs_diff = c_out
            .iter()
            .zip(rs_out.iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0f32, f32::max);
        let rel = if max_abs_out > 0.0 {
            max_abs_diff / max_abs_out
        } else {
            0.0
        };

        eprintln!(
            "[diff:attn_scores seq_len={seq_len}] cosine={cos:.7} \
             max_abs_diff={max_abs_diff:.3e} \
             max_abs_out={max_abs_out:.3e} relative={rel:.3e}"
        );

        assert!(
            c_out.iter().all(|x| x.is_finite()),
            "[diff:attn_scores seq_len={seq_len}] C output has NaN/Inf"
        );
        assert!(
            rs_out.iter().all(|x| x.is_finite()),
            "[diff:attn_scores seq_len={seq_len}] Rust output has NaN/Inf"
        );

        const COSINE_FLOOR: f32 = 0.9999;
        const REL_DIFF_FLOOR: f32 = 1e-3;
        assert!(
            cos >= COSINE_FLOOR,
            "[diff:attn_scores seq_len={seq_len}] cosine {cos:.7} \
             below {COSINE_FLOOR}"
        );
        assert!(
            rel <= REL_DIFF_FLOOR,
            "[diff:attn_scores seq_len={seq_len}] relative max_abs_diff \
             {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
        );
    }
}

/// `attn_softmax_batched` (slice 5d-7a). Synthetic per-row logits,
/// varying `seq_len`. Three-pass softmax with two SIMD reductions —
/// empirically bit-exact per-PSO.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn attn_softmax_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let v = VARIANT;
    let num_heads = v.num_attn_heads as u32;

    for &seq_len in &[32u32, 64, 128, 512] {
        let scores =
            synth_floats(seq_len * 7, (num_heads * seq_len) as usize, 1.5);

        let c_out = c.attn_softmax_batched(num_heads, seq_len, &scores);
        let rs_out = rs.attn_softmax_batched(num_heads, seq_len, &scores);
        assert_eq!(c_out.len(), (num_heads * seq_len) as usize);

        // Per-row softmax sums should be ~1.
        for h in 0..num_heads as usize {
            let row = &c_out[h * seq_len as usize..(h + 1) * seq_len as usize];
            let sum: f32 = row.iter().sum();
            assert!(
                (sum - 1.0).abs() < 1e-3,
                "[diff:attn_softmax seq_len={seq_len}] row {h} sum {sum} \
                 not ~1"
            );
        }

        let cos = cosine_sim(&c_out, &rs_out);
        let max_abs_out = c_out
            .iter()
            .chain(rs_out.iter())
            .map(|x| x.abs())
            .fold(0.0f32, f32::max);
        let max_abs_diff = c_out
            .iter()
            .zip(rs_out.iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0f32, f32::max);
        let rel = if max_abs_out > 0.0 {
            max_abs_diff / max_abs_out
        } else {
            0.0
        };

        eprintln!(
            "[diff:attn_softmax seq_len={seq_len}] cosine={cos:.7} \
             max_abs_diff={max_abs_diff:.3e} \
             max_abs_out={max_abs_out:.3e} relative={rel:.3e}"
        );

        assert!(
            c_out.iter().all(|x| x.is_finite()),
            "[diff:attn_softmax seq_len={seq_len}] C output has NaN/Inf"
        );
        assert!(
            rs_out.iter().all(|x| x.is_finite()),
            "[diff:attn_softmax seq_len={seq_len}] Rust output has NaN/Inf"
        );

        const COSINE_FLOOR: f32 = 0.9999;
        const REL_DIFF_FLOOR: f32 = 1e-3;
        assert!(
            cos >= COSINE_FLOOR,
            "[diff:attn_softmax seq_len={seq_len}] cosine {cos:.7} \
             below {COSINE_FLOOR}"
        );
        assert!(
            rel <= REL_DIFF_FLOOR,
            "[diff:attn_softmax seq_len={seq_len}] relative max_abs_diff \
             {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
        );
    }
}

/// `attn_values_batched` (slice 5d-7a). Synthetic post-softmax probs +
/// V, varying `seq_len`. Per-thread inner loop over `seq_len` — no
/// reductions; bit-exact per-PSO.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn attn_values_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let v = VARIANT;
    let num_heads = v.num_attn_heads as u32;
    let num_kv_heads = v.num_kv_heads as u32;
    let head_dim = v.head_dim as u32;
    let kv_dim = num_kv_heads * head_dim;

    for &seq_len in &[32u32, 64, 128, 512] {
        // Build a valid softmax by exp-then-normalize per row.
        let raw = synth_floats(seq_len + 11, (num_heads * seq_len) as usize, 1.0);
        let mut scores = vec![0.0f32; raw.len()];
        for h in 0..num_heads as usize {
            let row_start = h * seq_len as usize;
            let row = &raw[row_start..row_start + seq_len as usize];
            let max = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
            let exps: Vec<f32> =
                row.iter().map(|&x| (x - max).exp()).collect();
            let sum: f32 = exps.iter().sum();
            for i in 0..seq_len as usize {
                scores[row_start + i] = exps[i] / sum;
            }
        }
        let v_cache =
            synth_floats(seq_len + 13, (seq_len * kv_dim) as usize, 0.5);

        let c_out = c.attn_values_batched(
            num_heads, num_kv_heads, head_dim, seq_len, &scores, &v_cache,
        );
        let rs_out = rs.attn_values_batched(
            num_heads, num_kv_heads, head_dim, seq_len, &scores, &v_cache,
        );
        assert_eq!(c_out.len(), (num_heads * head_dim) as usize);
        assert_eq!(rs_out.len(), c_out.len());

        let cos = cosine_sim(&c_out, &rs_out);
        let max_abs_out = c_out
            .iter()
            .chain(rs_out.iter())
            .map(|x| x.abs())
            .fold(0.0f32, f32::max);
        let max_abs_diff = c_out
            .iter()
            .zip(rs_out.iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0f32, f32::max);
        let rel = if max_abs_out > 0.0 {
            max_abs_diff / max_abs_out
        } else {
            0.0
        };

        eprintln!(
            "[diff:attn_values seq_len={seq_len}] cosine={cos:.7} \
             max_abs_diff={max_abs_diff:.3e} \
             max_abs_out={max_abs_out:.3e} relative={rel:.3e}"
        );

        assert!(
            c_out.iter().all(|x| x.is_finite()),
            "[diff:attn_values seq_len={seq_len}] C output has NaN/Inf"
        );
        assert!(
            rs_out.iter().all(|x| x.is_finite()),
            "[diff:attn_values seq_len={seq_len}] Rust output has NaN/Inf"
        );

        const COSINE_FLOOR: f32 = 0.9999;
        const REL_DIFF_FLOOR: f32 = 1e-3;
        assert!(
            cos >= COSINE_FLOOR,
            "[diff:attn_values seq_len={seq_len}] cosine {cos:.7} \
             below {COSINE_FLOOR}"
        );
        assert!(
            rel <= REL_DIFF_FLOOR,
            "[diff:attn_values seq_len={seq_len}] relative max_abs_diff \
             {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
        );
    }
}

/// `sigmoid_gate` (slice 5d-7a). Per-thread elementwise — no
/// reductions, no atomics. Expected bit-exact.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn sigmoid_gate_close_c_vs_rust() {
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let v = VARIANT;
    let dim = (v.num_attn_heads * v.head_dim) as u32;
    let x = synth_floats(101, dim as usize, 0.7);
    let gate = synth_floats(202, dim as usize, 1.2);

    let c_out = c.sigmoid_gate(dim, &gate, &x);
    let rs_out = rs.sigmoid_gate(dim, &gate, &x);
    assert_eq!(c_out.len(), dim as usize);
    assert_eq!(rs_out.len(), dim as usize);

    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_out = c_out
        .iter()
        .chain(rs_out.iter())
        .map(|x| x.abs())
        .fold(0.0f32, f32::max);

    eprintln!(
        "[diff:sigmoid_gate] cosine={cos:.7} max_abs_diff={max_abs_diff:.3e} \
         max_abs_out={max_abs_out:.3e}"
    );

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:sigmoid_gate] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:sigmoid_gate] Rust output has NaN/Inf"
    );

    // Bit-exact expected (no reductions, no atomics — `sigmoid_gate`
    // is a pure per-thread elementwise op). Floors held loose to absorb
    // any libm-vs-MSL exp/sigmoid drift we haven't characterized; if
    // observed in practice we'll tighten.
    let first_diff = c_out.iter().zip(rs_out.iter()).position(|(a, b)| a != b);
    if let Some(i) = first_diff {
        eprintln!(
            "[diff:sigmoid_gate] first non-bit-exact at i={i}: \
             c={} rs={}",
            c_out[i], rs_out[i]
        );
    }
    assert_eq!(
        max_abs_diff, 0.0,
        "[diff:sigmoid_gate] expected bit-exact, got max_abs_diff {max_abs_diff:.3e}"
    );
}

/// Phase 4e: paired begin → complete via the deferred-experts state
/// machine, C path vs Rust port. Same kernels as 9b
/// (`gpu_batched_experts_forward`) split across an async commit and
/// a separate wait + readback. Confirms the begin/complete pair
/// produces the same final hidden state as the synchronous
/// single-call path.
///
/// Same tolerance regime as 9b (cosine ≥ 0.9999, rel ≤ 1e-3 — likely
/// bit-exact in practice; the underlying kernels are unchanged).
/// `layer_idx = -1` on both sides (synthetic dispatch — see the C
/// hook's invariant in `mf_begin_deferred_experts`).
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn deferred_experts_begin_complete_close_c_vs_rust() {
    use moeflux::riir::expert_forward::synth;
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let k: usize = 4;
    let expert_data = synth::k_expert_data_seeded(k);
    let h_post = synth::h_post_seeded();
    let h_mid = synth::h_mid_seeded();
    let shared_out = synth::shared_out_seeded();
    let weights = synth::expert_weights_seeded(k);
    let shared_gate_score: f32 = -1.0;

    assert_eq!(expert_data.len(), k * VARIANT.expert_size_4bit());
    assert_eq!(weights.len(), k);

    c.begin_deferred_experts(
        k as i32, &expert_data, &h_post, &h_mid, &shared_out, &weights,
        shared_gate_score,
    );
    let c_out = c.complete_deferred_experts();

    rs.begin_deferred_experts(
        k as i32, &expert_data, &h_post, &h_mid, &shared_out, &weights,
        shared_gate_score,
    );
    let rs_out = rs.complete_deferred_experts();

    assert_eq!(c_out.len(), VARIANT.hidden_dim);
    assert_eq!(rs_out.len(), VARIANT.hidden_dim);

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_out = c_out
        .iter()
        .chain(rs_out.iter())
        .map(|x| x.abs())
        .fold(0.0f32, f32::max);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = if max_abs_out > 0.0 {
        max_abs_diff / max_abs_out
    } else {
        0.0
    };

    eprintln!(
        "[diff:deferred_experts_begin_complete k={k}] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         relative={rel:.3e}"
    );

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:deferred_experts_begin_complete] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:deferred_experts_begin_complete] Rust output has NaN/Inf"
    );
    assert!(
        c_out.iter().any(|&x| x != 0.0),
        "[diff:deferred_experts_begin_complete] C output is all zero"
    );
    assert!(
        rs_out.iter().any(|&x| x != 0.0),
        "[diff:deferred_experts_begin_complete] Rust output is all zero"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:deferred_experts_begin_complete] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:deferred_experts_begin_complete] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 4e: discard semantics. Asserts that on each backend, a
/// `discard` between two begins doesn't taint the second dispatch's
/// output — i.e. the wait-then-clear actually clears state, and the
/// next begin starts from a clean slate. Performs the discard cycle
/// on both backends and compares the second dispatch's hidden state
/// across C vs Rust.
///
/// The first (discarded) dispatch uses K=2 with one set of synthetic
/// inputs; the second (kept) dispatch uses K=4 with a different set.
/// The cross-backend comparison confirms both impls handle the
/// discard-then-begin sequence identically.
#[test]
#[ignore = "long running; needs Metal device + moeflux artifacts"]
fn deferred_experts_discard_clears_state_c_vs_rust() {
    use moeflux::riir::expert_forward::synth;
    use moeflux::riir::VARIANT;

    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    // First dispatch (will be discarded): K=2.
    let k1: usize = 2;
    let data1 = synth::k_expert_data_seeded(k1);
    let h_post1 = synth::h_post_seeded();
    let h_mid1 = synth::h_mid_seeded();
    let shared_out1 = synth::shared_out_seeded();
    let weights1 = synth::expert_weights_seeded(k1);

    // Second dispatch (will be completed and compared): K=4 with a
    // different set of inputs derived by reseeding through K.
    let k2: usize = 4;
    let data2 = synth::k_expert_data_seeded(k2);
    let h_post2 = synth::h_post_seeded();
    let h_mid2 = synth::h_mid_seeded();
    let shared_out2 = synth::shared_out_seeded();
    let weights2 = synth::expert_weights_seeded(k2);

    // C side.
    c.begin_deferred_experts(
        k1 as i32, &data1, &h_post1, &h_mid1, &shared_out1, &weights1, -1.0,
    );
    c.discard_deferred_experts();
    c.begin_deferred_experts(
        k2 as i32, &data2, &h_post2, &h_mid2, &shared_out2, &weights2, -1.0,
    );
    let c_out = c.complete_deferred_experts();

    // Rust side.
    rs.begin_deferred_experts(
        k1 as i32, &data1, &h_post1, &h_mid1, &shared_out1, &weights1, -1.0,
    );
    rs.discard_deferred_experts();
    rs.begin_deferred_experts(
        k2 as i32, &data2, &h_post2, &h_mid2, &shared_out2, &weights2, -1.0,
    );
    let rs_out = rs.complete_deferred_experts();

    assert_eq!(c_out.len(), VARIANT.hidden_dim);
    assert_eq!(rs_out.len(), VARIANT.hidden_dim);

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_out = c_out
        .iter()
        .chain(rs_out.iter())
        .map(|x| x.abs())
        .fold(0.0f32, f32::max);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = if max_abs_out > 0.0 {
        max_abs_diff / max_abs_out
    } else {
        0.0
    };

    eprintln!(
        "[diff:deferred_experts_discard k1={k1} k2={k2}] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         relative={rel:.3e}"
    );

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:deferred_experts_discard] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:deferred_experts_discard] Rust output has NaN/Inf"
    );
    assert!(
        c_out.iter().any(|&x| x != 0.0),
        "[diff:deferred_experts_discard] C output is all zero"
    );
    assert!(
        rs_out.iter().any(|&x| x != 0.0),
        "[diff:deferred_experts_discard] Rust output is all zero"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:deferred_experts_discard] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:deferred_experts_discard] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 4c: end-to-end linear-attention layer forward, C path vs
/// Rust port, via the dump hook. Token 1 → embedding → layer 0
/// (linear-attn) on both sides; cosine ≥ 0.9999 / max_abs_diff /
/// max_abs_out ≤ 1e-3 floors per the strategy doc's Phase 3+ tolerance
/// regime. The numerical signal that 4c was building toward.
///
/// Both sides reset their per-layer state via `memory_clear` before
/// the call so the recurrence starts empty. The C side uses CPU
/// rms_norm for the input norm + GPU upload to `buf_input`; the Rust
/// side does GPU rms_norm directly. They differ on reduction order
/// (CPU sequential vs GPU parallel simd_sum + threadgroup-shared
/// second stage); per Phase 9e and the strategy doc that's at most
/// ULP-bounded drift on the norm output, which composes through the
/// rest of the pipeline staying inside the cosine floor.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn layer_forward_dump_close_c_vs_rust() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();
    let hidden_dim = moeflux::riir::VARIANT.hidden_dim;

    c.memory_clear();
    rs.memory_clear();

    // Embed token 1 on the C side and use that as input on both. (We
    // could embed on each side, but `embed` is bit-exact across them
    // per slice 1, so a single source keeps the test focused on the
    // layer forward.)
    let hidden_in = c.embed(1);
    assert_eq!(hidden_in.len(), hidden_dim);

    let layer_idx = 0i32; // linear-attn (full_attn_interval = 4)
    let pos = 0i32;

    let c_out = c.layer_forward_dump(layer_idx, pos, &hidden_in);
    let rs_out = rs.layer_forward_dump(layer_idx, pos, &hidden_in);
    assert_eq!(c_out.len(), hidden_dim);
    assert_eq!(rs_out.len(), hidden_dim);

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump] Rust output has NaN/Inf"
    );

    // Magnitude check — output isn't trivially all-zero.
    let max_abs_out =
        c_out.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    assert!(
        max_abs_out > 1e-6,
        "[diff:layer_forward_dump] C output magnitude {max_abs_out:.3e} \
         too small — production path likely no-op'd (cross-Ctx layer_cache?)"
    );

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = max_abs_diff / max_abs_out.max(f32::EPSILON);

    eprintln!(
        "[diff:layer_forward_dump layer=0] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         rel={rel:.3e}"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:layer_forward_dump] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:layer_forward_dump] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 4f-4: CPU-combine path matches the C side. Forces the Rust
/// port to take the `gpu_combine = false` branch (CMD3 omits
/// `moe_combine_residual`; the K per-expert outputs are read back to
/// host and combined CPU-side per `infer.m:4106..4129`). The C side
/// always picks `gpu_combine = true` for layer 0 with all pipelines
/// available — but the **arithmetic** of CPU combine is identical
/// (`hidden = h_mid + Σ weights[k] × out[k] + sigmoid(gate) ×
/// shared_out`), so the two paths must agree at the cosine floor.
///
/// Catches porting drift in the CPU-combine code path itself
/// (cpu_vec_madd / cpu_sigmoid_scalar / final fold) — the GPU-combine
/// path is exercised by every other layer-forward diff test, so this
/// is the only test that hits the CPU branch.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn layer_forward_dump_close_c_vs_rust_cpu_combine() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();
    let hidden_dim = moeflux::riir::VARIANT.hidden_dim;

    c.memory_clear();
    rs.memory_clear();

    let hidden_in = c.embed(1);
    assert_eq!(hidden_in.len(), hidden_dim);

    let layer_idx = 0i32;
    let pos = 0i32;

    let c_out = c.layer_forward_dump(layer_idx, pos, &hidden_in);
    let mut rs_out = vec![0.0f32; hidden_dim];
    rs.0.layer_forward_dump_with_gpu_combine(
        layer_idx,
        pos,
        &hidden_in,
        &mut rs_out,
        /* gpu_combine = */ false,
    )
    .expect("RsBackend layer_forward_dump_with_gpu_combine");

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_cpu_combine] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_cpu_combine] Rust output has NaN/Inf"
    );

    let max_abs_out =
        c_out.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    assert!(
        max_abs_out > 1e-6,
        "[diff:layer_forward_dump_cpu_combine] C output magnitude \
         {max_abs_out:.3e} too small"
    );

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = max_abs_diff / max_abs_out.max(f32::EPSILON);

    eprintln!(
        "[diff:layer_forward_dump_cpu_combine layer=0] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         rel={rel:.3e}"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:layer_forward_dump_cpu_combine] cosine {cos:.7} below \
         {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:layer_forward_dump_cpu_combine] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 4f-3 parity: five back-to-back `layer_forward_dump` calls
/// on the Rust side must all succeed without leaking a deferred-
/// experts dispatch across calls. After slice 4f-3,
/// `post_attention_tail` leaves an in-flight K-expert dispatch in
/// `RsCtx::deferred` instead of reading back inline.
/// `RsCtx::layer_forward_dump` reconstitutes the synchronous single-
/// step contract by draining the dispatch into `linear_buffers.input`
/// post-call, with a defensive `discard_deferred_experts_in` bracket
/// pre-call to guard against stale state.
///
/// Failure modes this test catches:
/// - **Missing post-call drain**: iteration 2+ would see a `Some`
///   deferred slot from iter 1 and hit
///   `DeferredError::AlreadyActive` → `RsError::EvalFailed`.
/// - **Missing pre-call discard**: a buggy caller leaving stale
///   state would propagate the same way.
/// - **Drain wrote into wrong buffer**: outputs would be all-zero or
///   NaN, caught by the finite + magnitude assertions.
///
/// Numerical equivalence across iterations IS asserted: with
/// `memory_clear` between calls (which slice 4f-3 extended to also
/// reset GPU-side linear-attn recurrence), each iteration starts
/// from the same state. Per-PSO Metal determinism (slice 9 finding)
/// means the outputs must be byte-identical.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn layer_forward_dump_back_to_back_no_deferred_leak() {
    let mut rs: RsBackend = open_backend();
    let hidden_dim = moeflux::riir::VARIANT.hidden_dim;

    let hidden_in = rs.embed(1);
    assert_eq!(hidden_in.len(), hidden_dim);

    let layer_idx = 0i32; // linear-attn
    let pos = 0i32;
    let n_iters = 5usize;

    let mut outs: Vec<Vec<f32>> = Vec::with_capacity(n_iters);
    for i in 0..n_iters {
        // memory_clear resets both host LayerState and GPU recurrence
        // (per slice 4f-3's RsCtx::memory_clear extension), so each
        // iteration starts from the same state. Without the GPU
        // reset, iterations 1..N would see stale conv_state /
        // delta_state from iter 0 and diverge.
        rs.memory_clear();
        let out = rs.layer_forward_dump(layer_idx, pos, &hidden_in);
        assert_eq!(out.len(), hidden_dim, "iter {i}: output length");
        assert!(
            out.iter().all(|x| x.is_finite()),
            "iter {i}: output has NaN/Inf — likely stale deferred state"
        );
        let max_abs = out.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
        assert!(
            max_abs > 1e-6,
            "iter {i}: output magnitude {max_abs:.3e} too small — drain \
             likely reading from wrong buffer or hitting AlreadyActive"
        );
        outs.push(out);
    }

    // All five outputs must be byte-identical: same layer, same
    // input, fully-reset state between calls. Drift here implies
    // either the deferred bracketing is reading from a buffer that
    // wasn't drained, or memory_clear failed to reset some piece of
    // recurrence.
    for i in 1..n_iters {
        let drift_max = outs[0]
            .iter()
            .zip(outs[i].iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0f32, f32::max);
        assert_eq!(
            drift_max, 0.0,
            "iter 0 vs iter {i} differ by max_abs_diff={drift_max:.3e} — \
             deferred-experts state leaked across calls or memory_clear \
             did not reset all recurrence"
        );
    }
    eprintln!(
        "[diff:layer_forward_dump_back_to_back] {n_iters} iterations \
         bit-identical (max_abs_diff=0)"
    );
}

/// Phase 4d: end-to-end **full-attention** layer forward, C path vs
/// Rust port, via the dump hook. Companion to the linear-attn test
/// above. Same floors / shape; the only differences are
/// `layer_idx = 3` (first full-attn layer when
/// `full_attn_interval == 4`) and the eprintln tag.
///
/// The Rust path swaps the linear-attn pipeline (4 batched
/// projections + 5 fused GPU kernels) for the full-attn pipeline
/// (3 batched projections + per-head Q/K rms_norm + RoPE + KV append
/// + SDPA), then hands off to the same shared `post_attention_tail`
/// the linear-attn forward uses. So if 4c was green and 4d is red,
/// the bug is somewhere in the swapped attention pipeline — not the
/// shared tail.
///
/// `memory_clear` runs on both sides before the call so the KV cache
/// starts at `len = 0` and the test runs at `pos = 0`. After the
/// call `kv.len = 1`.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn layer_forward_dump_close_c_vs_rust_full_attn() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();
    let hidden_dim = moeflux::riir::VARIANT.hidden_dim;

    c.memory_clear();
    rs.memory_clear();

    let hidden_in = c.embed(1);
    assert_eq!(hidden_in.len(), hidden_dim);

    let layer_idx = 3i32; // first full-attn layer (full_attn_interval = 4)
    let pos = 0i32;

    let c_out = c.layer_forward_dump(layer_idx, pos, &hidden_in);
    let rs_out = rs.layer_forward_dump(layer_idx, pos, &hidden_in);
    assert_eq!(c_out.len(), hidden_dim);
    assert_eq!(rs_out.len(), hidden_dim);

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_full] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_full] Rust output has NaN/Inf"
    );

    let max_abs_out =
        c_out.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    assert!(
        max_abs_out > 1e-6,
        "[diff:layer_forward_dump_full] C output magnitude {max_abs_out:.3e} \
         too small — production path likely no-op'd (cross-Ctx layer_cache?)"
    );

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = max_abs_diff / max_abs_out.max(f32::EPSILON);

    eprintln!(
        "[diff:layer_forward_dump layer=3 (full-attn)] cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_out={max_abs_out:.3e} \
         rel={rel:.3e}"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:layer_forward_dump_full] cosine {cos:.7} below {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:layer_forward_dump_full] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Slice 5d-7b: full-attention layer forward at `kv_len ≥ 32` —
/// exercises the GPU SDPA fast path on both backends. The
/// `layer_forward_dump_close_c_vs_rust_full_attn` sibling above runs
/// at `pos = 0` (kv_len = 1 after append), which is below the gate
/// (`kv_len >= 32`); this test prefills the KV cache so the test
/// call lands on the gate predicate and the 4 GPU attn kernels run
/// inside CMD2.
///
/// Both backends share the same gate predicate (`kv_len >= 32 && <
/// GPU_KV_SEQ`); both will run GPU SDPA on the test call, so the
/// comparison stays at the same tolerance regime as the existing
/// full-attn dump test.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn layer_forward_dump_close_c_vs_rust_full_attn_gpu_path() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();
    let hidden_dim = moeflux::riir::VARIANT.hidden_dim;

    c.memory_clear();
    rs.memory_clear();

    let layer_idx = 3i32; // first full-attn layer (full_attn_interval = 4)

    // Prefill: call layer_forward_dump at pos=0..31 to fill layer 3's
    // KV cache to length 32 on both backends. Distinct token per
    // position so each entry is non-trivial.
    for pos in 0i32..32 {
        let hidden_in = c.embed(1 + pos);
        let _c_drain = c.layer_forward_dump(layer_idx, pos, &hidden_in);
        let _rs_drain = rs.layer_forward_dump(layer_idx, pos, &hidden_in);
    }

    // Test call: pos=32 → kv_len becomes 33 after append, satisfying
    // the GPU-path gate (`kv_len >= 32`). The 4 attn kernels fire on
    // both backends.
    let pos = 32i32;
    let hidden_in = c.embed(1 + pos);
    let c_out = c.layer_forward_dump(layer_idx, pos, &hidden_in);
    let rs_out = rs.layer_forward_dump(layer_idx, pos, &hidden_in);
    assert_eq!(c_out.len(), hidden_dim);
    assert_eq!(rs_out.len(), hidden_dim);

    assert!(
        c_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_full_gpu] C output has NaN/Inf"
    );
    assert!(
        rs_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_full_gpu] Rust output has NaN/Inf"
    );

    let max_abs_out =
        c_out.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    assert!(
        max_abs_out > 1e-6,
        "[diff:layer_forward_dump_full_gpu] C output magnitude \
         {max_abs_out:.3e} too small — GPU path likely no-op'd"
    );

    let cos = cosine_sim(&c_out, &rs_out);
    let max_abs_diff = c_out
        .iter()
        .zip(rs_out.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = max_abs_diff / max_abs_out.max(f32::EPSILON);

    eprintln!(
        "[diff:layer_forward_dump layer=3 (full-attn, GPU SDPA at kv_len=33)] \
         cosine={cos:.7} max_abs_diff={max_abs_diff:.3e} \
         max_abs_out={max_abs_out:.3e} rel={rel:.3e}"
    );

    const COSINE_FLOOR: f32 = 0.9999;
    const REL_DIFF_FLOOR: f32 = 1e-3;
    assert!(
        cos >= COSINE_FLOOR,
        "[diff:layer_forward_dump_full_gpu] cosine {cos:.7} below \
         {COSINE_FLOOR}"
    );
    assert!(
        rel <= REL_DIFF_FLOOR,
        "[diff:layer_forward_dump_full_gpu] relative max_abs_diff \
         {rel:.3e} above {REL_DIFF_FLOOR:.3e}"
    );
}

/// Phase 4b sanity: the C-side `mf_layer_forward_dump` hook is
/// callable and returns finite output. The numerical-correctness
/// signal lands in 4c when `RsCtx::layer_forward_dump` exists and
/// the diff oracle compares per-layer outputs head-on.
///
/// Permissive on purpose: 4b discovered a third cross-Ctx state bug
/// in addition to the two captured during the bisect. The C side has
/// a process-global `layer_cache` (host-side weight-pointer cache,
/// `infer.m:~3960`) that's populated on first call to
/// `fused_layer_forward` from whichever ctx ran first. When that ctx
/// is freed and a later test opens a fresh ctx, the cache's
/// `layer_cache_built` flag stays 1 so the cache is never rebuilt —
/// its pointers now reference freed memory. On this M2 Max with
/// these tests run serially, those pages typically come back zeroed,
/// making `fused_layer_forward` for the second ctx an effective
/// no-op (`hidden_out == hidden_in`). This is the same bug class as
/// the documented `g_deferred` cross-Ctx NaN finding; the Phase 7
/// fix lifts both into Ctx-owned state.
///
/// FIXME(riir): `layer_cache` cross-Ctx state pollution. Phase 7 fix
/// alongside the typed-`memory_seq_rm` work. Recorded in the
/// drama_llama in-repo `blallama_session_state_pollution.md`.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn layer_forward_dump_c_self_sanity() {
    let mut c: CBackend = open_backend();
    let hidden_dim = moeflux::riir::VARIANT.hidden_dim;

    c.memory_clear();
    let hidden_in = c.embed(/* token_id */ 1);
    assert_eq!(hidden_in.len(), hidden_dim);

    let hidden_out = c.layer_forward_dump(/* layer_idx */ 0, /* pos */ 0, &hidden_in);
    assert_eq!(hidden_out.len(), hidden_dim);

    // The only assertion we can make order-independently — finite
    // output. NaN/Inf would indicate uninitialized state being read or
    // a corrupted weight tensor.
    assert!(
        hidden_out.iter().all(|x| x.is_finite()),
        "[diff:layer_forward_dump_c] hidden_out contains NaN/Inf"
    );

    eprintln!(
        "[diff:layer_forward_dump_c] layer=0 hidden_dim={hidden_dim} \
         first 4 in={:?} out={:?}",
        &hidden_in[..4],
        &hidden_out[..4],
    );
}

/// Phase 4a: validate the Rust port's `memory_*` ops against the C
/// path on fresh state. End-to-end forward isn't ported yet, so the
/// diff is structural — empty-state queries and truncation arguments
/// must produce matching `pos_max` readings on both sides.
///
/// When 4f lands and `eval_prompt` is real, this test grows a
/// "prefill, truncate, compare pos_max" body that exercises a
/// non-empty cache. Today it's a structural-equivalence guard against
/// the layer-state allocation drifting out of sync with the C side.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn memory_ops_match_c_on_empty_state() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    eprintln!(
        "[diff:memory_ops] model={} num_layers reachable via VARIANT",
        c.model_name(),
    );

    // Fresh ctx: pos_max equals 0 on both sides for every supported
    // variant (each has at least one full-attn layer, so the -1 sentinel
    // never fires).
    assert_eq!(c.memory_seq_pos_max(), rs.memory_seq_pos_max());
    assert_eq!(c.memory_seq_pos_max(), 0);

    // memory_clear is a no-op on empty state and must stay matched.
    c.memory_clear();
    rs.memory_clear();
    assert_eq!(c.memory_seq_pos_max(), rs.memory_seq_pos_max());

    // Several truncation argument shapes — empty state stays empty in
    // every case, but exercises the (p0, p1) argument plumbing on both
    // sides.
    for (p0, p1) in [(0, -1), (5, 10), (-1, -1), (100, 50), (0, 0)] {
        let c_ok = c.memory_seq_rm(p0, p1);
        let rs_ok = rs.memory_seq_rm(p0, p1);
        assert_eq!(
            c_ok, rs_ok,
            "[diff:memory_ops] memory_seq_rm({p0}, {p1}) return mismatch \
             (c={c_ok} rs={rs_ok})"
        );
        assert_eq!(
            c.memory_seq_pos_max(),
            rs.memory_seq_pos_max(),
            "[diff:memory_ops] pos_max mismatch after memory_seq_rm({p0}, {p1})"
        );
    }

    eprintln!("[diff:memory_ops] structural equivalence on empty state: OK");
}

#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn harness_loads() {
    let mut c: CBackend = open_backend();
    eprintln!(
        "[diff:scaffold] model={} n_vocab={} n_ctx={} eos={}",
        c.model_name(),
        c.n_vocab(),
        c.n_ctx(),
        c.eos(),
    );

    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let logits = c.eval_prompt(&prompt, 0);
    assert_eq!(logits.len(), c.n_vocab());

    let arg = argmax(&logits);
    let top = topk(&logits, TOPK_K);
    let self_jac = jaccard(&top, &top);
    let self_cos = cosine_sim(&logits, &logits);
    eprintln!(
        "[diff:scaffold] argmax={arg} top-{TOPK_K}={top:?} \
         self-jaccard={self_jac:.4} self-cosine={self_cos:.5}"
    );

    // Sanity: comparing a vector against itself must hit 1.0 exactly
    // (within float). If these fail, the helpers are broken.
    assert!((self_jac - 1.0).abs() < 1e-6, "self-jaccard != 1.0");
    assert!((self_cos - 1.0).abs() < 1e-4, "self-cosine != 1.0");
}

// ---------------------------------------------------------------------------
// Phase 4f-6 — end-to-end eval_prompt / eval_token diff
// ---------------------------------------------------------------------------
//
// The file-level "end-to-end logits NOT useful" note (lines 21..37)
// is about *intra-Ctx* `memory_clear`-between calls — that path
// reveals C's lossy `memory_clear` semantic and produces cosine
// 0.65..0.76 for two C runs of the same prompt. The fresh-Ctx-per-
// test pattern below sidesteps that: each backend gets its own
// freshly-opened Ctx, runs one eval_prompt / eval_token, and we
// compare logits across backends. Both paths are deterministic given
// fresh state (Metal kernels are bit-exact per-PSO per the slice 9
// finding); the only float drift is CPU swiglu / sigmoid in the
// shared post-attention tail, which is identical word-by-word
// between C and Rust.
//
// Floor: cosine ≥ 0.9999 + top-1 argmax match. If 0.9999 fails on
// real runs, drop to 0.999 + Jaccard@20 ≥ 0.95 with a FIXME(riir):
// note pinpointing the bisect-by-layer finding.

const E2E_COSINE_FLOOR: f32 = 0.9999;

fn assert_e2e_logits_close(label: &str, c_logits: &[f32], rs_logits: &[f32]) {
    assert_eq!(c_logits.len(), rs_logits.len(), "[{label}] logits length");
    assert!(
        c_logits.iter().all(|x| x.is_finite()),
        "[{label}] C logits contain NaN/Inf"
    );
    assert!(
        rs_logits.iter().all(|x| x.is_finite()),
        "[{label}] Rust logits contain NaN/Inf"
    );

    let c_arg = argmax(c_logits);
    let rs_arg = argmax(rs_logits);
    let cos = cosine_sim(c_logits, rs_logits);
    let max_abs_c =
        c_logits.iter().map(|x| x.abs()).fold(0.0f32, f32::max);
    let max_abs_diff = c_logits
        .iter()
        .zip(rs_logits.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let rel = max_abs_diff / max_abs_c.max(f32::EPSILON);
    let c_top = topk(c_logits, TOPK_K);
    let rs_top = topk(rs_logits, TOPK_K);
    let jac = jaccard(&c_top, &rs_top);

    eprintln!(
        "[diff:{label}] argmax c={c_arg} rs={rs_arg} cosine={cos:.7} \
         max_abs_diff={max_abs_diff:.3e} max_abs_c={max_abs_c:.3e} \
         rel={rel:.3e} top-{TOPK_K} jaccard={jac:.4}"
    );

    assert_eq!(
        c_arg, rs_arg,
        "[{label}] argmax mismatch (c={c_arg} rs={rs_arg})"
    );
    assert!(
        cos >= E2E_COSINE_FLOOR,
        "[{label}] cosine {cos:.7} below {E2E_COSINE_FLOOR}"
    );
}

/// One-token decode against a 4-token synthetic prefill. Both
/// backends open fresh, prefill `[1, 200, 600, 1100]` via
/// `eval_prompt` (state-update only on the first 3 tokens, emit on
/// the 4th — the per-step contract `mf_eval_prompt` advertises),
/// then run `eval_token(7)` at `pos = 4` and compare logits.
///
/// Exercises both code paths in slice 4f-5: the prefix loop in
/// `eval_prompt` (no-emit step_internal) and the single-step
/// `eval_token`. Catches positional bugs (e.g. dropped `pos`),
/// state-update vs emit divergence, and the final norm + lm_head
/// path that only runs on the emitting step.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn eval_token_matches_c_single_step() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    // Prefill 4 synthetic tokens. eval_prompt emits logits for the
    // 4th; we discard them — they're a separate diff from the one
    // this test asserts.
    let prefill: [i32; 4] = [1, 200, 600, 1100];
    let _c_prefill_logits = c.eval_prompt(&prefill, 0);
    let _rs_prefill_logits = rs.eval_prompt(&prefill, 0);

    // Decode one more token at the next position.
    let next_token = 7i32;
    let next_pos = prefill.len();
    let c_logits = c.eval_token(next_token, next_pos);
    let rs_logits = rs.eval_token(next_token, next_pos);

    assert_e2e_logits_close(
        "eval_token_after_4tok_prefill",
        &c_logits,
        &rs_logits,
    );
}

// ---------------------------------------------------------------------------
// Phase 4g — state_save / state_load
// ---------------------------------------------------------------------------

/// `state_size()` on Rust must match `state_size()` on C after the
/// same prefill. The header is fixed-size and shape-driven; the body
/// scales with KV length on full-attn layers (15 of 40 on A3B) and
/// is fixed-size on linear-attn layers (45 of 40 on A3B). If sizes
/// disagree it means the wire-format math diverged from C.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn state_size_matches_c_after_prefill() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let _ = c.eval_prompt(&prompt, 0);
    let _ = rs.eval_prompt(&prompt, 0);

    let c_size = c.0.state_size();
    let rs_size = rs.0.state_size();

    eprintln!(
        "[diff:state_size_after_4tok] c={c_size} rs={rs_size}"
    );
    assert_eq!(
        c_size, rs_size,
        "state_size mismatch: c={c_size} rs={rs_size}"
    );

    // Sanity: should be > header bytes; KV grows with len.
    assert!(c_size > 32, "state_size {c_size} suspiciously small");
}

/// Rust↔Rust round-trip: prefill → save → memory_clear → load →
/// eval_token → compare to a fresh Rust eval that prefills + eval_
/// tokens without the save/load cycle. Both should produce
/// bit-identical logits since save/load preserves all per-layer
/// state and per-PSO Metal kernels are deterministic.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn state_round_trip_rust() {
    // Reference: fresh Ctx, prefill + eval_token without save/load.
    let mut rs_ref: RsBackend = open_backend();
    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let next_token = 7i32;
    let next_pos = prompt.len();
    let _ = rs_ref.eval_prompt(&prompt, 0);
    let ref_logits = rs_ref.eval_token(next_token, next_pos);

    // Test path: fresh Ctx, prefill, save, memory_clear, load,
    // eval_token. Should match `ref_logits` exactly.
    let mut rs: RsBackend = open_backend();
    let _ = rs.eval_prompt(&prompt, 0);

    let snap_size = rs.0.state_size();
    let mut snap = vec![0u8; snap_size];
    let written = rs.0.state_save(&mut snap).expect("Rust state_save");
    assert_eq!(written, snap_size, "state_save wrote unexpected length");

    rs.memory_clear();
    rs.0.state_load(&snap).expect("Rust state_load");

    let test_logits = rs.eval_token(next_token, next_pos);

    assert_eq!(test_logits.len(), ref_logits.len());
    let drift_max = ref_logits
        .iter()
        .zip(test_logits.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let cos = cosine_sim(&ref_logits, &test_logits);
    eprintln!(
        "[diff:state_round_trip_rust] snap_bytes={snap_size} \
         max_abs_diff={drift_max:.3e} cosine={cos:.7}"
    );
    assert_eq!(
        argmax(&ref_logits),
        argmax(&test_logits),
        "round-trip changed argmax"
    );
    assert!(
        cos >= 0.9999,
        "round-trip cosine {cos:.7} below 0.9999"
    );
}

/// Wire compat (Rust → C): Rust prefills, saves; a fresh C Ctx
/// loads the snapshot and decodes one more token. The resulting
/// logits must match Rust's direct-eval continuation at the same
/// position. Confirms the Rust port writes bytes the C side can
/// read.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn state_load_c_from_rust_save() {
    let mut rs: RsBackend = open_backend();
    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let next_token = 7i32;
    let next_pos = prompt.len();

    let _ = rs.eval_prompt(&prompt, 0);

    let snap_size = rs.0.state_size();
    let mut snap = vec![0u8; snap_size];
    rs.0.state_save(&mut snap).expect("Rust state_save");

    // Reference: Rust direct continuation.
    let rs_logits = rs.eval_token(next_token, next_pos);

    // Test: fresh C Ctx, load Rust snapshot, eval_token.
    let mut c: CBackend = open_backend();
    c.memory_clear();
    c.0.state_load(&snap).expect("C state_load(rust_snap)");
    let mut c_logits = vec![0.0f32; c.0.n_vocab()];
    c.0
        .eval_token(next_token, next_pos, 0, &mut c_logits)
        .expect("C eval_token after Rust state_load");

    assert_e2e_logits_close(
        "state_load_c_from_rust_save",
        &c_logits,
        &rs_logits,
    );
}

/// Wire compat (C → Rust): C prefills, saves; a fresh Rust Ctx
/// loads the snapshot and decodes one more token. The resulting
/// logits must match C's direct-eval continuation. Confirms the
/// Rust port reads C-produced snapshot bytes correctly.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn state_load_rust_from_c_save() {
    let mut c: CBackend = open_backend();
    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let next_token = 7i32;
    let next_pos = prompt.len();

    let _ = c.eval_prompt(&prompt, 0);

    let snap_size = c.0.state_size();
    let mut snap = vec![0u8; snap_size];
    c.0.state_save(&mut snap).expect("C state_save");

    // Reference: C direct continuation.
    let mut c_logits = vec![0.0f32; c.0.n_vocab()];
    c.0
        .eval_token(next_token, next_pos, 0, &mut c_logits)
        .expect("C eval_token reference");

    // Test: fresh Rust Ctx, load C snapshot, eval_token.
    let mut rs: RsBackend = open_backend();
    rs.memory_clear();
    rs.0.state_load(&snap).expect("Rust state_load(c_snap)");
    let rs_logits = rs.eval_token(next_token, next_pos);

    assert_e2e_logits_close(
        "state_load_rust_from_c_save",
        &c_logits,
        &rs_logits,
    );
}

/// Multi-token prefill via `eval_prompt`. Both backends open fresh,
/// run `eval_prompt` over `[1..=8]`, compare last-token logits.
///
/// Catches positional bugs in the prefill loop (each step advances
/// `pos` by 1; if step_internal mishandles the position the per-
/// layer KV append in full_attn_layer_forward writes to the wrong
/// row and the final logits diverge).
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn eval_prompt_matches_c_multi_token() {
    let mut c: CBackend = open_backend();
    let mut rs: RsBackend = open_backend();

    let prompt: [i32; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
    let c_logits = c.eval_prompt(&prompt, 0);
    let rs_logits = rs.eval_prompt(&prompt, 0);

    assert_e2e_logits_close(
        "eval_prompt_8tok",
        &c_logits,
        &rs_logits,
    );
}

// ---------------------------------------------------------------------------
// Phase 5d-6b — speculative-prefetch correctness
// ---------------------------------------------------------------------------

/// The prefetch hit path (normal flow) and the all-miss path
/// (predictions cleared between every token) must produce
/// **bit-identical** logits. Per-PSO Metal kernels are deterministic
/// (slice 9 finding); the only difference between the two paths is
/// which buffer (`data_prefetch[slot]` vs `data_synced[slot]`) the
/// expert weights came from. Both buffers should hold identical
/// bytes for the same expert.
///
/// Catches: any bug where `data_prefetch[slot]` ends up loaded with
/// the wrong expert, or where the encoder binds the wrong buffer
/// for a given `SlotSource`.
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn prefetch_hit_miss_equivalence_rust() {
    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let next_token = 7i32;
    let next_pos = prompt.len();

    // Reference: normal eval with prefetch hits where they apply.
    let mut rs_normal: RsBackend = open_backend();
    let _ = rs_normal.eval_prompt(&prompt, 0);
    let normal_logits = rs_normal.eval_token(next_token, next_pos);

    // Test: same prompt+token, but clear prefetch predictions just
    // before the token-decode. With no predictions, every layer
    // takes the all-miss (sync-pread into data_synced) path.
    let mut rs_miss: RsBackend = open_backend();
    let _ = rs_miss.eval_prompt(&prompt, 0);
    rs_miss.0.clear_prefetch_predictions();
    let miss_logits = rs_miss.eval_token(next_token, next_pos);

    assert_eq!(normal_logits.len(), miss_logits.len());
    let drift_max = normal_logits
        .iter()
        .zip(miss_logits.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let cos = cosine_sim(&normal_logits, &miss_logits);
    eprintln!(
        "[diff:prefetch_hit_miss_equivalence] \
         max_abs_diff={drift_max:.3e} cosine={cos:.7} \
         argmax(normal)={a} argmax(miss)={b}",
        a = argmax(&normal_logits),
        b = argmax(&miss_logits),
    );
    assert_eq!(
        argmax(&normal_logits),
        argmax(&miss_logits),
        "prefetch hit and all-miss paths produced different argmax"
    );
    assert_eq!(
        drift_max, 0.0,
        "prefetch hit and all-miss paths should be bit-identical, \
         got drift {drift_max:.3e}"
    );
}

/// `step → memory_clear → step` must produce the same logits as a
/// fresh-Ctx `step → step`. Catches: prefetch state leaking across
/// `memory_clear` (stale predictions, in-flight prefetch not
/// drained, last_token_indices not cleared).
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn memory_clear_cancels_prefetch_no_leak() {
    let prompt_a: [i32; 4] = [1, 200, 600, 1100];
    let prompt_b: [i32; 4] = [2, 300, 700, 1200];
    let next_token = 7i32;
    let next_pos = prompt_b.len();

    // Reference: fresh ctx, eval prompt_b only, get next-token logits.
    let mut rs_ref: RsBackend = open_backend();
    let _ = rs_ref.eval_prompt(&prompt_b, 0);
    let ref_logits = rs_ref.eval_token(next_token, next_pos);

    // Test: same ctx, eval prompt_a, memory_clear, eval prompt_b,
    // get next-token logits. Should match ref_logits.
    let mut rs: RsBackend = open_backend();
    let _ = rs.eval_prompt(&prompt_a, 0);
    rs.memory_clear();
    let _ = rs.eval_prompt(&prompt_b, 0);
    let test_logits = rs.eval_token(next_token, next_pos);

    assert_eq!(test_logits.len(), ref_logits.len());
    let drift_max = ref_logits
        .iter()
        .zip(test_logits.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let cos = cosine_sim(&ref_logits, &test_logits);
    eprintln!(
        "[diff:memory_clear_cancels_prefetch] \
         max_abs_diff={drift_max:.3e} cosine={cos:.7}"
    );
    assert_eq!(
        argmax(&ref_logits),
        argmax(&test_logits),
        "memory_clear leaked prefetch state across reset"
    );
    assert!(
        cos >= 0.9999,
        "memory_clear leak: cosine {cos:.7} below 0.9999"
    );
}

/// Two consecutive `eval_token` calls with `clear_prefetch_predictions`
/// between them must produce the same logits as a fresh ctx running
/// the same sequence with no prefetch state at all. Catches: stale
/// `data_synced[slot]` bytes from token N polluting token N+1's
/// dispatch (would only happen if the parallel pread or the slot-
/// reuse contract were broken).
#[test]
#[ignore = "long running; needs moeflux artifacts"]
fn slot_reuse_race_regression_rust() {
    let prompt: [i32; 4] = [1, 200, 600, 1100];
    let token_t1 = 7i32;
    let token_t2 = 42i32;
    let pos_t1 = prompt.len();
    let pos_t2 = pos_t1 + 1;

    // Reference: fresh ctx per token, no prefetch state ever exists.
    let mut rs_ref1: RsBackend = open_backend();
    let _ = rs_ref1.eval_prompt(&prompt, 0);
    let _ = rs_ref1.eval_token(token_t1, pos_t1);
    let ref_t2 = rs_ref1.eval_token(token_t2, pos_t2);

    // Test: same ctx through both tokens, but clear predictions
    // before each call. Should match ref_t2.
    let mut rs: RsBackend = open_backend();
    let _ = rs.eval_prompt(&prompt, 0);
    rs.0.clear_prefetch_predictions();
    let _ = rs.eval_token(token_t1, pos_t1);
    rs.0.clear_prefetch_predictions();
    let test_t2 = rs.eval_token(token_t2, pos_t2);

    let drift_max = ref_t2
        .iter()
        .zip(test_t2.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0f32, f32::max);
    let cos = cosine_sim(&ref_t2, &test_t2);
    eprintln!(
        "[diff:slot_reuse_race_regression] \
         max_abs_diff={drift_max:.3e} cosine={cos:.7}"
    );
    assert_eq!(
        argmax(&ref_t2),
        argmax(&test_t2),
        "slot-reuse race: argmax changed across consecutive evals"
    );
    assert!(
        cos >= 0.9999,
        "slot-reuse race regression: cosine {cos:.7} below 0.9999"
    );
}