ramvamp-core 0.1.1

Runtime for streaming fine-grained MoE experts from NVMe: packed format, io_uring reads, LFU expert cache, CPU kernels, KV cache, generation loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
//! Chunked, layer-major prefill.
//!
//! Token-major prefill *is* decode: one [`forward_token`](super::forward_token)
//! per prompt token, each one re-reading `top_k` experts on all 48 layers. A
//! 4K prompt therefore reads ~1,097 MB of expert weights **per token** and
//! ~4.5 TB in total. This module runs the shape `docs/architecture.md`
//! specifies instead: a bounded chunk of up to
//! [`DEFAULT_PREFILL_CHUNK`] positions is carried through the model together,
//! and each layer's expert file is streamed once, front to back, with every
//! expert computed against **all** of the chunk's rows routed to it.
//!
//! Expert bytes drop from `top_k` blobs per token per layer to one pass over
//! the layer file per *chunk* — ~34 MB/token at a 512-token chunk instead of
//! ~1,097 MB — and each weight row is reused across the ~32 rows a 512-row
//! chunk routes to a given expert instead of being restreamed per row.
//!
//! # The one thing that is schedule-sensitive
//!
//! **Logits must be byte-identical to the token-major path.** `scripts/
//! bitident.py` compares with zero tolerance. Prefill is allowed to change
//! *which* experts are read and *when*; it is not allowed to change the
//! arithmetic or its order.
//!
//! Exactly one site cares. The per-row MoE reduction accumulates in f32 in
//! **top-k order** (descending router probability, ties to the lowest expert
//! id), and f32 addition is not associative. The sweep hands experts back in
//! ascending **blob** order, which is a different order. So expert outputs are
//! staged per `[row][slot_in_topk]` and reduced afterwards, in top-k order,
//! exactly as `forward_token` reduces its own staging buffer. Accumulating on
//! arrival would move bits; [`reduce_experts`] is the function that does not.
//!
//! Everything else is order-agnostic by construction:
//!
//! - A given `(weight_row, activation_row)` dot product is a fixed sequence of
//!   f32 operations whatever the outer loop order is, so
//!   [`gemv_q8_k_batched`] is bit-identical to `gemv_q8_k_rows` per element
//!   (its own docs pin that), and [`crate::threads::shard_range`] is a pure
//!   function, so the pool fan-out is bit-neutral.
//! - RMSNorm, RoPE, softmax, SwiGLU, `vec_add` and both activation
//!   quantizers are per row with no cross-row coupling.
//! - [`attention_at_in`] is bit-identical to `decode_attention` against a cache
//!   truncated to the same length, which is what lets a chunk's whole K/V be
//!   appended before any of its rows attend. Rows are independent of each
//!   other too, so [`scatter_attention`] may split them across shards by cost
//!   rather than by count without moving a bit.
//!
//! # Layer-major, and why the K/V goes in first
//!
//! ```text
//! embed all R rows
//! for layer in 0..n_layers:
//!     norm/quantize/Q,K,V for all R rows      (batched GEMV, n_acts = R)
//!     QK-RMSNorm + RoPE per row at start + r
//!     append ALL R rows' K/V to kv[layer]     <-- the inversion
//!     attention_at_in(row r, positions = start + r + 1)   (fanned out)
//!     o_proj, residual, ffn norm, router, top-k for all R rows
//!     sweep the layer once; per expert, compute its routed rows in one batch
//!     reduce each row's staging in top-k order
//! final norm + lm_head for the LAST row only
//!     (plus, when scoring, the scored rows a block at a time)
//! ```
//!
//! Appending the whole chunk's K/V before attending is the point: it is one
//! pass over the layer instead of R, and the causal mask that makes it correct
//! is [`attention_at_in`]'s `positions` argument. Mid-layer the KV cache is
//! legitimately **ragged** — layer `L` holds `start + R` positions while layer
//! `L + 1` still holds `start` — so [`crate::kv::KvCache::seq_len`] reports
//! [`KvError::RaggedLayers`](crate::kv::KvError::RaggedLayers) until the chunk
//! finishes. That is why this path cannot reuse `forward_token`'s position
//! gate, and why nothing here weakens it: the token-major path still needs it.
//!
//! # Memory
//!
//! Every batched buffer is carved from the [`PrefillSession`] scratch span,
//! which is the head of the idle expert-slot slab. Nothing is allocated: the
//! documented headroom under `memory.max=3G` is ~111 MiB, so a heap buffer
//! here would be a budget event even though the slab itself is ~1,438 MiB.
//! See [`scratch_bytes`] for the arithmetic and [`Carver`] for the typed
//! sub-allocator that hands the span out.
//!
//! # A/B
//!
//! [`PrefillMode`] keeps both paths in one binary, defaulting to the sweep.
//! This exists so the strongest available test can be written: the sweep and
//! the token-major loop must produce byte-identical logits for the same
//! prompt, which `sweep_and_token_major_agree_bit_for_bit` asserts across
//! several chunk sizes and prompt lengths.

use std::marker::PhantomData;
use std::mem::{align_of, size_of};
use std::ops::Range;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::format::{ArchInfo, ExpertsLayout};
use crate::io::{PrefillSession, SweepConfig, SweepExpert, SweepPlan};
use crate::kernels::KernelError;
use crate::kernels::attention::{
    AttentionError, attention_at_in, scratch_len as attention_scratch_len,
};
use crate::kernels::primitives::{
    rmsnorm, rmsnorm_in_place, rope_neox_heads, softmax, swiglu_combine,
};
use crate::kernels::quants::{
    BlockQ8_0, BlockQ8K, QuantFormat, quantize_row_q8_0, quantize_row_q8_k,
};
use crate::kernels::{gemv_q8_0_batched, gemv_q8_k_batched};
use crate::kv::{KvCache, KvError};
use crate::threads::ComputePool;

use super::forward::{ForwardError, ForwardState, dot_f32, pool_gemv_q8_k, record, taken};
use super::weights::Model;

/// Positions carried through the model together by default.
///
/// Total prefill expert bytes are `ceil(prompt / chunk) * 17.55 GB`, so wider
/// is strictly better for I/O and the only cost is staging, which scales
/// linearly at 64 KiB/row (`top_k * hidden * 4` at the v0 dims). 512 is the
/// documented starting point; the 128/256/512/1024 sweep is a planned
/// experiment, which is why this is a dial and not a constant in the driver.
pub const DEFAULT_PREFILL_CHUNK: usize = 512;

/// Which prefill path [`prefill_prompt`] takes.
///
/// Both are retained on purpose: keeping them in one binary is what makes the
/// bit-identity test possible (see the module docs).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PrefillMode {
    /// Chunked layer-major sweep. One pass over each layer's expert file per
    /// chunk, cache bypassed. The default.
    #[default]
    Sweep,
    /// One [`forward_token`](super::forward_token) per prompt token through
    /// the decode cache — the phase-5 behaviour, kept for A/B.
    TokenMajor,
}

/// Runtime dials for the prefill pass.
///
/// Held on [`ForwardState`] rather than on
/// [`RuntimeConfig`](super::RuntimeConfig): the latter's fields are
/// constructed positionally by the CLI, which a different lane owns, so
/// growing it would break that crate's build. Set these with
/// [`ForwardState::set_prefill_config`]; [`PrefillConfig::from_env`] is the
/// override that is reachable without any CLI change at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PrefillConfig {
    /// Which path to take. Defaults to [`PrefillMode::Sweep`].
    pub mode: PrefillMode,
    /// Positions per chunk. Defaults to [`DEFAULT_PREFILL_CHUNK`]. Clamped
    /// down when the slot slab cannot hold that chunk's staging; see
    /// [`plan_arena`].
    pub chunk: usize,
    /// Experts one sweep window read covers.
    pub experts_per_window: u32,
    /// Sweep windows kept in flight.
    pub windows_in_flight: u32,
}

impl Default for PrefillConfig {
    fn default() -> Self {
        let sweep = SweepConfig::default();
        Self {
            mode: PrefillMode::default(),
            chunk: DEFAULT_PREFILL_CHUNK,
            experts_per_window: sweep.experts_per_window,
            windows_in_flight: sweep.windows_in_flight,
        }
    }
}

impl PrefillConfig {
    /// The default, with `RAMVAMP_PREFILL` and `RAMVAMP_PREFILL_CHUNK`
    /// applied when they are set and parse.
    ///
    /// `RAMVAMP_PREFILL` takes `sweep` or `token-major` (`token` and
    /// `token_major` are accepted too); `RAMVAMP_PREFILL_CHUNK` takes a
    /// positive integer. Anything else is ignored with a warning rather than
    /// failing a load: this is a diagnostic dial, and a typo in an
    /// environment variable is not a reason to refuse to run a model.
    ///
    /// [`ForwardState`] seeds itself from this, so the two dials are
    /// reachable today without touching the CLI.
    #[must_use]
    pub fn from_env() -> Self {
        let mut config = Self::default();
        if let Ok(raw) = std::env::var("RAMVAMP_PREFILL") {
            match raw.trim().to_ascii_lowercase().as_str() {
                "sweep" => config.mode = PrefillMode::Sweep,
                "token" | "token-major" | "token_major" => config.mode = PrefillMode::TokenMajor,
                other => tracing::warn!(value = other, "ignoring unknown RAMVAMP_PREFILL"),
            }
        }
        if let Ok(raw) = std::env::var("RAMVAMP_PREFILL_CHUNK") {
            match raw.trim().parse::<usize>() {
                Ok(chunk) if chunk > 0 => config.chunk = chunk,
                _ => tracing::warn!(value = raw, "ignoring unusable RAMVAMP_PREFILL_CHUNK"),
            }
        }
        config
    }

    /// The sweep dials alone.
    #[must_use]
    pub fn sweep_config(self) -> SweepConfig {
        SweepConfig {
            experts_per_window: self.experts_per_window,
            windows_in_flight: self.windows_in_flight,
        }
    }

    /// Reject a degenerate dial before it reaches the driver.
    ///
    /// **All three dials, one refusal point.** Every field here is `pub`, so
    /// every field is caller-supplied, and each used to be refused somewhere
    /// else: the chunk here, `experts_per_window == 0` silently coerced to 1
    /// by `plan_arena`, and an oversized `windows_in_flight` only inside
    /// `PrefillSession::begin`, several hundred lines and one arena plan
    /// later. The sweep dials are delegated to [`SweepConfig::validate`],
    /// which owns their bounds, so the two cannot drift apart.
    ///
    /// # Errors
    ///
    /// [`ForwardError::InvalidPrefillChunk`] for a zero chunk;
    /// [`ForwardError::Sweep`] with
    /// [`SweepError::BadDials`](crate::io::SweepError::BadDials) for a zero
    /// `experts_per_window`, a zero `windows_in_flight`, or more windows in
    /// flight than `MAX_WINDOWS_IN_FLIGHT`.
    pub fn validate(self) -> Result<Self, ForwardError> {
        if self.chunk == 0 {
            return Err(ForwardError::InvalidPrefillChunk { chunk: self.chunk });
        }
        self.sweep_config().validate()?;
        Ok(self)
    }
}

// ---------------------------------------------------------------------------
// Where the wall time went
// ---------------------------------------------------------------------------

/// One phase of a prefill pass, as charged by [`PhaseClock`].
///
/// Deliberately coarse. The point is to tell the two candidate causes of a
/// compute-bound prefill apart — serial per-row attention against activation
/// thrash in the batched expert GEMV — not to attribute every instruction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Phase {
    /// The causal attention over the KV cache: `attention_at_in` per row on
    /// the sweep, `decode_attention` per token on the token-major path. Both
    /// are fanned out across the compute pool, so this is wall time, not core
    /// time.
    Attention,
    /// GEMVs against resident weights: Q/K/V, `o_proj` and `lm_head`.
    Projections,
    /// Routing: the f32 router matvec, the softmax over every expert and the
    /// top-k selection. Its own phase because, unlike the projections, it
    /// never reaches the compute pool on the token-major path.
    Router,
    /// Expert arithmetic: gate/up, SwiGLU, the intermediate quantization and
    /// down, for every routed expert. Excludes waiting for its bytes.
    ExpertCompute,
    /// Getting expert bytes in front of that arithmetic.
    ExpertIo,
    /// Everything per-row and cheap per element: RMSNorms, RoPE, activation
    /// quantization, transposes, KV appends, residual adds, the routing
    /// bookkeeping and the top-k reduction.
    Elementwise,
}

/// Where one [`prefill_prompt`] call's wall time went.
///
/// EXP-016 left prefill compute-bound: at a 512-token chunk expert reads fell
/// from 82,233 to 768 windows while wall time only fell 2.45x. Two causes were
/// proposed, attention (quadratic in prompt length, serial per row) and the
/// batched expert GEMV (whose activation side streams ~75 KB past every weight
/// row), and the counters that existed could not tell them apart.
///
/// EXP-017 answered it with these timers, and refuted the GEMV half: at 512
/// tokens attention is 61.3% of prefill and expert compute is 19.1%, the
/// batched GEMV having cut expert compute 3.27x against token-major. Expert
/// I/O is down to 1.7%, so non-I/O work is 98.3% of a swept prefill, not the
/// ~93% the 2.45x ratio implied. At 1891 tokens attention reaches 85.2%.
///
/// # What sums to what
///
/// [`PrefillTiming::total`] is the wall time of the whole `prefill_prompt`
/// call. The six phase fields are **disjoint** spans inside it, charged by
/// [`PhaseClock`] at region boundaries rather than opened and closed
/// independently, so [`accounted`](PrefillTiming::accounted) cannot exceed
/// `total` and [`other`](PrefillTiming::other) closes the sum exactly.
///
/// `other` is not noise. It is the arena plan, `begin_prefill`/`session
/// finish`, the per-block scratch carves, and the chunk loop's own
/// scaffolding — real work that is simply none of the six, made visible
/// instead of being folded into whichever phase happened to be open.
///
/// # I/O wait is not measured twice
///
/// [`PrefillTiming::expert_io`] spans the calls that put expert bytes in front
/// of the arithmetic: `split`, `next_expert` and `finish` on the sweep,
/// `begin_layer`, `await_misses` and `end_layer` on the token-major path. The
/// *blocked on the drive* subset of that is already counted by the streamer,
/// as [`StreamStats::sweep_io_wait`](crate::io::StreamStats::sweep_io_wait)
/// and [`StreamStats::io_wait`](crate::io::StreamStats::io_wait) respectively,
/// and nothing here re-times it. `expert_io - sweep_io_wait` is the sweep's
/// own window bookkeeping; reading the two side by side is the point, which is
/// why the CLI prints them together.
///
/// # Lifetime
///
/// Zeroed at the start of every `prefill_prompt` and by
/// [`ForwardState::reset`]. This describes **one** prefill, unlike the
/// streaming counters, which describe the process and survive a reset on
/// purpose; a cumulative timing across a chat session's turns would answer no
/// question anyone has. Decode contributes nothing: `forward_token` shares its
/// instrumentation with the token-major path and charges only while a prefill
/// has armed the struct.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PrefillTiming {
    /// Which path produced these numbers. `None` until a prefill has run,
    /// which is what [`PrefillTiming::ran`] asks.
    pub mode: Option<PrefillMode>,
    /// Prompt positions the run consumed.
    pub tokens: u64,
    /// Wall time of the whole `prefill_prompt` call, phases and everything
    /// between them.
    pub total: Duration,
    /// [`Phase::Attention`].
    pub attention: Duration,
    /// [`Phase::Projections`].
    pub projections: Duration,
    /// [`Phase::Router`].
    pub router: Duration,
    /// [`Phase::ExpertCompute`].
    pub expert_compute: Duration,
    /// [`Phase::ExpertIo`].
    pub expert_io: Duration,
    /// [`Phase::Elementwise`].
    pub elementwise: Duration,
}

impl PrefillTiming {
    /// The six phases together.
    #[must_use]
    pub fn accounted(&self) -> Duration {
        self.attention
            + self.projections
            + self.router
            + self.expert_compute
            + self.expert_io
            + self.elementwise
    }

    /// The share of [`PrefillTiming::total`] no phase claimed.
    ///
    /// Saturating rather than checked because the phases are disjoint spans of
    /// the total by construction: this is zero-or-positive unless the
    /// instrumentation itself is wrong, which is exactly what the unit tests
    /// assert.
    #[must_use]
    pub fn other(&self) -> Duration {
        self.total.saturating_sub(self.accounted())
    }

    /// Whether a prefill has run and left numbers here.
    #[must_use]
    pub fn ran(&self) -> bool {
        self.mode.is_some()
    }

    /// Every phase, in report order, with the unaccounted remainder last.
    ///
    /// Returned as an array rather than printed here because
    /// `ramvamp-core` does not print.
    #[must_use]
    pub fn phases(&self) -> [(&'static str, Duration); 7] {
        [
            ("attention", self.attention),
            ("expert compute", self.expert_compute),
            ("expert io", self.expert_io),
            ("projections", self.projections),
            ("router", self.router),
            ("elementwise", self.elementwise),
            ("other", self.other()),
        ]
    }

    /// A zeroed timing labelled with the run that is about to fill it.
    pub(super) fn started(mode: PrefillMode, tokens: usize) -> Self {
        Self {
            mode: Some(mode),
            tokens: tokens as u64,
            ..Self::default()
        }
    }
}

/// A stopwatch over a [`PrefillTiming`]: each [`charge`](PhaseClock::charge)
/// closes the region that began at the previous boundary and opens the next
/// one.
///
/// **One clock read per boundary, not two.** The alternative — an
/// `Instant::now()` pair around every region — doubles the syscall-free
/// `clock_gettime` count and leaves gaps between regions that silently vanish
/// instead of landing in [`PrefillTiming::other`].
///
/// The boundaries are placed around *loops*, not around iterations, wherever a
/// site is entered per row: the per-row attention loop is charged once per
/// layer, not 512 times. The two sites charged per iteration are the ones
/// whose iteration count is per expert rather than per row (~128 per layer),
/// where the resolution is worth ~25 ns.
pub(super) struct PhaseClock<'a> {
    /// `None` when this pass charges nowhere.
    timing: Option<&'a mut PrefillTiming>,
    since: Instant,
    /// When the whole pass began, for a clock that must close its own
    /// [`PrefillTiming::total`]. `None` for a prefill clock, whose total is
    /// the whole `prefill_prompt` call and is measured outside this type.
    whole: Option<Instant>,
}

impl<'a> PhaseClock<'a> {
    /// Open the first region, charging into `timing` only when `armed`.
    ///
    /// Unarmed is every `forward_token` a decode step makes *into the prefill
    /// accumulator*: the token-major prefill and decode run the same
    /// instrumented code, and a decoded token's phases belong to no prefill.
    pub(super) fn new(timing: &'a mut PrefillTiming, armed: bool) -> Self {
        let now = Instant::now();
        Self {
            timing: armed.then_some(timing),
            since: now,
            whole: None,
        }
    }

    /// A clock over one **decoded token**: the same six phases, plus the
    /// token's own wall time and the token itself when [`PhaseClock::close`]
    /// runs.
    ///
    /// A prefill is timed from outside `forward_token` by `prefill_prompt`,
    /// which knows where the pass begins and ends; a decode step has no such
    /// outer frame, so it closes its own total.
    pub(super) fn decoding(timing: &'a mut PrefillTiming) -> Self {
        let now = Instant::now();
        Self {
            timing: Some(timing),
            since: now,
            whole: Some(now),
        }
    }

    /// End the pass: on a [`PhaseClock::decoding`] clock, add everything since
    /// it was created to [`PrefillTiming::total`] and one to
    /// [`PrefillTiming::tokens`]. A no-op on any other clock.
    ///
    /// Not a `Drop` impl: a pass that failed mid-token leaves a state its
    /// caller must discard, and charging a token that produced nothing would
    /// put a lie in the only numbers anyone reads afterwards.
    pub(super) fn close(self) {
        let Some(whole) = self.whole else {
            return;
        };
        if let Some(timing) = self.timing {
            timing.total += whole.elapsed();
            timing.tokens += 1;
        }
    }

    /// Charge everything since the last boundary to `phase`, and open the
    /// next region here.
    ///
    /// A no-op, down to the clock read, on an unarmed clock.
    #[inline]
    pub(super) fn charge(&mut self, phase: Phase) {
        let Some(timing) = self.timing.as_deref_mut() else {
            return;
        };
        let now = Instant::now();
        let slot = match phase {
            Phase::Attention => &mut timing.attention,
            Phase::Projections => &mut timing.projections,
            Phase::Router => &mut timing.router,
            Phase::ExpertCompute => &mut timing.expert_compute,
            Phase::ExpertIo => &mut timing.expert_io,
            Phase::Elementwise => &mut timing.elementwise,
        };
        // Saturating: `Instant` is monotonic, but a negative delta must not be
        // a panic in library code whatever the platform's clock does.
        *slot += now.saturating_duration_since(self.since);
        self.since = now;
    }
}

/// Observer for the router's decision during prefill, called once per row per
/// layer with `(absolute position, layer, top_k)`.
///
/// The analogue of [`ExpertRouteSink`](super::ExpertRouteSink) for a pass that
/// carries many positions at once, which is why the position is an argument
/// rather than something the caller already knows.
///
/// **Record order differs from the token-major path.** Token-major emits
/// `(token, layer)` in that nesting; the sweep emits `(layer, row)`. Both
/// cover exactly the same set of `(position, layer)` pairs and the routing
/// decisions are identical — only the emission order changes, because that is
/// the order the work happens in.
pub type PrefillRouteSink<'a> = &'a mut dyn FnMut(usize, u32, &[(u32, f32)]);

/// Observer for prefill *progress*, called with
/// `(positions_done, positions_total)` after each unit of work completes.
///
/// Both numbers are relative to the call, not to the KV cache: a prefill that
/// continues a conversation from position 4,000 still counts its own new
/// tokens from zero, because "how far through this prompt am I" is the only
/// question a progress bar asks. `positions_done` is strictly increasing and
/// the last call of a successful prefill always has
/// `positions_done == positions_total == tokens.len()`.
///
/// **Granularity differs by path, deliberately.**
/// [`PrefillMode::Sweep`] fires once per chunk, because a chunk is the unit it
/// commits; [`PrefillMode::TokenMajor`] fires once per token, because that is
/// the unit *it* commits. Neither promises a fixed number of calls — the
/// sweep's chunk width is narrowed to whatever the expert slot slab can host
/// (see `plan_arena`), so it is a function of the pool, not only of
/// [`PrefillConfig::chunk`].
///
/// This is pure instrumentation: nothing downstream of it reads the callback,
/// and no arithmetic, ordering or scheduling depends on whether one is
/// installed.
pub type PrefillProgressSink<'a> = &'a mut dyn FnMut(usize, usize);

// ---------------------------------------------------------------------------
// Typed scratch sub-allocation
// ---------------------------------------------------------------------------

/// A type it is sound to reinterpret initialized scratch bytes as.
///
/// # Safety
///
/// Every initialized bit pattern of `size_of::<Self>()` bytes must be a valid
/// value of `Self`: no niches, no validity invariants, no padding whose
/// contents could be observed as anything but "some initialized bytes", and no
/// interior mutability. This holds for plain integer/float aggregates and
/// nothing else. The [`PrefillSession`] scratch is always *initialized* (the
/// slab is allocated zeroed) but never *zeroed on carve*, so a `ScratchPod`
/// slice can legitimately come back holding the previous chunk's bytes; every
/// consumer here writes before it reads.
unsafe trait ScratchPod: Copy {}

// SAFETY: every 32-bit pattern is a valid `f32` (including signalling NaNs,
// which Rust permits as values) and a valid `u32`.
unsafe impl ScratchPod for f32 {}
// SAFETY: as above.
unsafe impl ScratchPod for u32 {}
// SAFETY: `f32` + `[i8; 256]` + `[i16; 16]`, all of which accept every bit
// pattern; the aggregate is 4-aligned with no padding, so there are no
// uninitialized bytes to observe either.
unsafe impl ScratchPod for BlockQ8K {}
// SAFETY: `f32` + `[i8; 32]`; as above.
unsafe impl ScratchPod for BlockQ8_0 {}
// SAFETY: two `u32`-sized fields, `repr(C)`, no padding.
unsafe impl ScratchPod for TopkEntry {}
// SAFETY: as above.
unsafe impl ScratchPod for RowSlot {}

/// One selected expert and its renormalized router weight.
///
/// A named `repr(C)` pair rather than `(u32, f32)`, because this one is
/// reinterpreted out of raw scratch bytes and tuple layout is unspecified.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[repr(C)]
struct TopkEntry {
    /// Routed expert id.
    expert: u32,
    /// Weight this expert's output is scaled by in the reduction.
    weight: f32,
}

/// One entry of the inverse routing index: a chunk row and which of its
/// `top_k` slots the expert occupies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(C)]
struct RowSlot {
    /// Row within the chunk.
    row: u32,
    /// Index into that row's top-k, which is the staging slot to fill.
    slot: u32,
}

/// A bump allocator over one `&mut [u8]` span.
///
/// Disjointness comes from [`slice::split_at_mut`], which is safe; the only
/// unsafe step is reinterpreting an already-split byte range as a
/// [`ScratchPod`] slice, and that is guarded by an explicit alignment check
/// rather than by an assumption about the slab's base address.
struct Carver<'a> {
    rest: &'a mut [u8],
    used: usize,
}

impl<'a> Carver<'a> {
    /// Start carving at the base of `bytes`.
    fn new(bytes: &'a mut [u8]) -> Self {
        Self {
            rest: bytes,
            used: 0,
        }
    }

    /// Bytes consumed so far, padding included.
    fn used(&self) -> usize {
        self.used
    }

    /// Take `len` values of `T`, padding forward to `T`'s alignment.
    ///
    /// # Errors
    ///
    /// [`ForwardError::PrefillScratch`] when the span is exhausted or the
    /// requested length overflows a byte count;
    /// [`ForwardError::PrefillScratchAlign`] when the span cannot be aligned
    /// for `T` at all, which a page-aligned slab base rules out but which is
    /// checked rather than assumed.
    fn take<T: ScratchPod>(&mut self, len: usize) -> Result<&'a mut [T], ForwardError> {
        let align = align_of::<T>();
        let pad = self.rest.as_ptr().align_offset(align);
        // Before the byte arithmetic, not after: `usize::MAX` padding makes
        // every `checked_add` below overflow, so an unalignable span would
        // otherwise report `PrefillScratch { needed: u64::MAX }` for any
        // non-zero `len` and `PrefillScratchAlign` never. Unreachable at a
        // page-aligned slab base — but a diagnostic that lies is worse than
        // one that is merely unreachable.
        if pad == usize::MAX {
            return Err(ForwardError::PrefillScratchAlign { align });
        }
        let want = len
            .checked_mul(size_of::<T>())
            .and_then(|bytes| bytes.checked_add(pad))
            .ok_or(ForwardError::PrefillScratch {
                needed: u64::MAX,
                available: self.rest.len() as u64,
            })?;
        if want > self.rest.len() {
            return Err(ForwardError::PrefillScratch {
                needed: (self.used + want) as u64,
                available: (self.used + self.rest.len()) as u64,
            });
        }
        let rest = std::mem::take(&mut self.rest);
        let (head, tail) = rest.split_at_mut(want);
        self.rest = tail;
        self.used += want;
        let ptr = head.as_mut_ptr();
        // SAFETY: `ptr + pad` is aligned for `T` (`align_offset` computed
        // `pad` for exactly this pointer) and `len * size_of::<T>()` bytes
        // past it are inside `head`, which `split_at_mut` just made
        // exclusively ours for `'a`. Every byte of the slab was initialized
        // by `SlotPool::new`, and `T: ScratchPod` promises every such bit
        // pattern is a valid `T`.
        Ok(unsafe { std::slice::from_raw_parts_mut(ptr.add(pad).cast::<T>(), len) })
    }
}

/// Every batched buffer one chunk needs, carved out of the session scratch.
///
/// Field order here is the carve order, which is also the order
/// [`scratch_bytes`] sums; `carve_consumes_exactly_the_documented_bytes` pins
/// that the two agree.
struct Scratch<'a> {
    /// Residual stream, `[rows][hidden]`.
    residual: &'a mut [f32],
    /// RMSNorm output, `[rows][hidden]`, reused by both norm sites.
    normed: &'a mut [f32],
    /// Query projection, `[rows][q_dim]`.
    q: &'a mut [f32],
    /// Attention context, `[rows][q_dim]`.
    attn_out: &'a mut [f32],
    /// Key projection, `[rows][kv_dim]`.
    k: &'a mut [f32],
    /// Value projection, `[rows][kv_dim]`.
    v: &'a mut [f32],
    /// Batched-GEMV output staging, `[out_dim][n]` — the transpose source for
    /// Q/K/V and o_proj, then the expert down-projection's destination.
    tmat: &'a mut [f32],
    /// Staged expert outputs, `[rows][top_k][hidden]`. The buffer that makes
    /// the reduction order independent of the sweep order.
    staged: &'a mut [f32],
    /// Expert gate projection, `[moe][n]`, then SwiGLU in place.
    gate: &'a mut [f32],
    /// Expert up projection, `[moe][n]`.
    up: &'a mut [f32],
    /// SwiGLU output transposed to `[n][moe]` for per-row quantization.
    moe_t: &'a mut [f32],
    /// Per-shard attention scratch, `[shards][attn_shard]`: one whole
    /// [`attention_scratch_len`] carve per compute shard, so the per-row
    /// attention can run on every pinned core at once without a heap byte.
    /// Constant in `rows` on purpose — [`plan_arena`] recovers the per-row
    /// slope by differencing [`scratch_bytes`] and needs it to stay affine.
    attn_shards: &'a mut [f32],
    /// Router logits, `[rows][n_experts]`.
    router_logits: &'a mut [f32],
    /// Router probabilities, `[rows][n_experts]`; top-k selection consumes
    /// them destructively, per row.
    router_probs: &'a mut [f32],
    /// Q8_K quantization of `normed`, `[rows][hidden / 256]`.
    acts_hidden: &'a mut [BlockQ8K],
    /// One expert's routed rows gathered contiguously, `[n][hidden / 256]`.
    acts_gather: &'a mut [BlockQ8K],
    /// Q8_K quantization of `attn_out`, `[rows][q_dim / 256]`.
    acts_attn: &'a mut [BlockQ8K],
    /// Q8_K quantization of `moe_t`, `[n][moe / 256]`.
    acts_moe: &'a mut [BlockQ8K],
    /// Q8_0 quantization of `normed`, `[rows][hidden / 32]`.
    acts_q80: &'a mut [BlockQ8_0],
    /// Selected experts and weights, `[rows][top_k]`, in top-k order.
    topk: &'a mut [TopkEntry],
    /// Inverse routing index entries, CSR-ordered by expert.
    index: &'a mut [RowSlot],
    /// CSR offsets, `[n_experts + 1]`.
    index_start: &'a mut [u32],
    /// Fill cursors while building the index, `[n_experts]`.
    index_cursor: &'a mut [u32],
}

/// Architecture dimensions the chunk driver reads once per call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PrefillDims {
    hidden: usize,
    q_dim: usize,
    kv_dim: usize,
    moe: usize,
    top_k: usize,
    n_experts: usize,
    n_heads: usize,
    n_kv_heads: usize,
    head_dim: usize,
    /// Q8_K blocks in a `[hidden]` row.
    hidden_q8k: usize,
    /// Q8_0 blocks in a `[hidden]` row.
    hidden_q80: usize,
    /// Q8_K blocks in a `[q_dim]` row.
    attn_q8k: usize,
    /// Q8_K blocks in a `[moe]` row.
    moe_q8k: usize,
    /// `max(q_dim, hidden)`: the widest batched-GEMV output `tmat` must hold.
    wide: usize,
    /// Compute shards the per-row attention is fanned out across, which is
    /// [`ComputePool::shards`] and therefore counts the submitting thread.
    /// Here rather than passed to [`scratch_bytes`] so that all of its call
    /// sites — [`plan_arena`]'s three included — stay unchanged.
    shards: usize,
    /// The KV cache's position capacity: the longest row any chunk of this
    /// prefill can attend over, and so the width the per-shard attention
    /// carve is sized for once instead of per chunk.
    max_positions: usize,
}

/// Weights per Q8_K super-block.
const QK_K: usize = 256;
/// Weights per Q8_0 block.
const QK8_0: usize = 32;

impl PrefillDims {
    /// One compute shard's attention scratch, in f32.
    ///
    /// Sized from [`PrefillDims::max_positions`] rather than from the chunk,
    /// so the carve serves the last row of the last chunk as well as the
    /// first row of the first one. A slice longer than one call needs is
    /// accepted by `attention_at_in` and its tail ignored.
    fn attn_shard(&self) -> usize {
        attention_scratch_len(
            self.n_heads,
            self.n_kv_heads,
            self.head_dim,
            self.max_positions,
        )
    }

    /// Every shard's attention scratch together, in f32.
    fn attn_scratch(&self) -> usize {
        self.shards.saturating_mul(self.attn_shard())
    }

    /// Read the chunk geometry off `arch`, for a pool of `shards` shards
    /// against a cache holding `max_positions` positions.
    ///
    /// # Errors
    ///
    /// [`ForwardError::UnsupportedDim`] when a dimension is not a whole
    /// number of activation blocks, and [`ForwardError::InvalidTopK`] on a
    /// nonsensical router config — the same refusals
    /// [`ForwardState::with_config`] makes, restated because this reads the
    /// *argument* model.
    fn new(arch: &ArchInfo, shards: usize, max_positions: usize) -> Result<Self, ForwardError> {
        let hidden = arch.hidden as usize;
        let q_dim = arch.n_heads as usize * arch.head_dim as usize;
        let kv_dim = arch.n_kv_heads as usize * arch.head_dim as usize;
        let moe = arch.moe_intermediate as usize;
        let top_k = arch.top_k as usize;
        let n_experts = arch.n_experts as usize;
        for (what, dim, block) in [
            ("hidden", hidden, QK_K),
            ("hidden", hidden, QK8_0),
            ("moe_intermediate", moe, QK_K),
            ("n_heads * head_dim", q_dim, QK_K),
        ] {
            if dim == 0 || dim % block != 0 {
                return Err(ForwardError::UnsupportedDim { what, dim, block });
            }
        }
        if top_k == 0 || top_k > n_experts {
            return Err(ForwardError::InvalidTopK { top_k, n_experts });
        }
        if kv_dim == 0 || arch.head_dim == 0 {
            return Err(ForwardError::UnsupportedDim {
                what: "n_kv_heads * head_dim",
                dim: kv_dim,
                block: 1,
            });
        }
        Ok(Self {
            hidden,
            q_dim,
            kv_dim,
            moe,
            top_k,
            n_experts,
            n_heads: arch.n_heads as usize,
            n_kv_heads: arch.n_kv_heads as usize,
            head_dim: arch.head_dim as usize,
            hidden_q8k: hidden / QK_K,
            hidden_q80: hidden / QK8_0,
            attn_q8k: q_dim / QK_K,
            moe_q8k: moe / QK_K,
            wide: q_dim.max(hidden),
            // A pool always has at least one shard; clamping here means a
            // caller that passed zero gets a one-shard carve rather than a
            // zero-length one the fan-out would then index into.
            shards: shards.max(1),
            max_positions,
        })
    }
}

/// Add `count * unit` bytes to a running total, refusing to overflow.
fn accumulate(total: &mut usize, count: usize, unit: usize) -> Result<(), ForwardError> {
    let bytes = count
        .checked_mul(unit)
        .and_then(|bytes| total.checked_add(bytes))
        .ok_or(ForwardError::PrefillScratch {
            needed: u64::MAX,
            available: *total as u64,
        })?;
    *total = bytes;
    Ok(())
}

/// Scratch bytes one chunk of `rows` rows needs, at `dims`.
///
/// The arithmetic, in carve order. `H` is hidden, `Q` is `n_heads * head_dim`,
/// `V` is `n_kv_heads * head_dim`, `M` is `moe_intermediate`, `K` is `top_k`,
/// `E` is `n_experts`, `W` is `max(Q, H)`, `S` is the compute shard count and
/// `A` is one shard's [`attention_scratch_len`] carve:
///
/// ```text
/// f32   rows * (2H + 2Q + 2V + W + K*H + 3M + 2E)   + S*A          [attn_shards]
/// Q8_K  rows * (2 * H/256 + Q/256 + M/256)          blocks of 292 B
/// Q8_0  rows * (H/32)                               blocks of  36 B
/// pairs rows * K                                    of 8 B, twice  [topk, index]
/// u32   2E + 1                                                     [CSR]
/// ```
///
/// At the v0 pin (`rows` 512, H 2048, Q 4096, V 512, M 768, K 8, E 128,
/// `S` 6, `A` = 8 * 4096 + 2 * 128 = 33,024 f32):
///
/// ```text
/// f32     512 * 36,352 floats           = 74,448,896 B   71.00 MiB
///   of which staging (K*H)              = 33,554,432 B   32.00 MiB
///   of which q + attn_out (2Q)          = 16,777,216 B   16.00 MiB
/// attn_shards  6 * 33,024 * 4 B         =    792,576 B    0.76 MiB
/// Q8_K    512 * 35 blocks * 292 B       =  5,232,640 B    4.99 MiB
/// Q8_0    512 * 64 blocks *  36 B       =  1,179,648 B    1.13 MiB
/// topk + index  2 * 512 * 8 * 8 B       =     65,536 B
/// CSR     257 * 4 B                     =      1,028 B
/// total                                 = 81,720,324 B   77.93 MiB
/// ```
///
/// against a ~1,438 MiB slab whose sweep ring costs a further ~46.7 MiB at the
/// default dials. The 3 GiB contract is not touched: these bytes are the slot
/// pool's, already resident, borrowed for the length of the prefill. That is
/// why the sharded attention scratch lives here and not on the heap — a
/// prefill costs no *additional* bytes, whatever the headroom happens to be.
///
/// **`S*A` is constant in `rows`.** [`plan_arena`] recovers the per-row slope
/// as `scratch_bytes(2) - scratch_bytes(1)` and divides the budget by it, which
/// only answers the question while this function stays affine in `rows`.
///
/// # Errors
///
/// [`ForwardError::PrefillScratch`] if the total overflows `usize`.
fn scratch_bytes(dims: &PrefillDims, rows: usize) -> Result<usize, ForwardError> {
    let f32_bytes = size_of::<f32>();
    let mut total = 0usize;
    // Per-row f32 planes, in carve order.
    for width in [
        dims.hidden,
        dims.hidden,
        dims.q_dim,
        dims.q_dim,
        dims.kv_dim,
        dims.kv_dim,
        dims.wide,
        dims.top_k * dims.hidden,
        dims.moe,
        dims.moe,
        dims.moe,
    ] {
        accumulate(&mut total, rows.saturating_mul(width), f32_bytes)?;
    }
    accumulate(&mut total, dims.attn_scratch(), f32_bytes)?;
    accumulate(&mut total, rows.saturating_mul(dims.n_experts), f32_bytes)?;
    accumulate(&mut total, rows.saturating_mul(dims.n_experts), f32_bytes)?;
    // Activation blocks.
    let q8k = size_of::<BlockQ8K>();
    for blocks in [
        dims.hidden_q8k,
        dims.hidden_q8k,
        dims.attn_q8k,
        dims.moe_q8k,
    ] {
        accumulate(&mut total, rows.saturating_mul(blocks), q8k)?;
    }
    accumulate(
        &mut total,
        rows.saturating_mul(dims.hidden_q80),
        size_of::<BlockQ8_0>(),
    )?;
    // Routing bookkeeping.
    let pairs = rows.saturating_mul(dims.top_k);
    accumulate(&mut total, pairs, size_of::<TopkEntry>())?;
    accumulate(&mut total, pairs, size_of::<RowSlot>())?;
    accumulate(&mut total, dims.n_experts + 1, size_of::<u32>())?;
    accumulate(&mut total, dims.n_experts, size_of::<u32>())?;
    Ok(total)
}

/// Carve `bytes` into every buffer a `rows`-row chunk needs.
///
/// Called once per layer phase rather than held across the session: the
/// [`PrefillSession`] hands the same span back from
/// [`PrefillSession::scratch`] and [`PrefillSession::split`], and re-deriving
/// the split is a few dozen pointer adjustments.
///
/// # Errors
///
/// [`ForwardError::PrefillScratch`] if `bytes` is shorter than
/// [`scratch_bytes`] says.
fn carve<'a>(
    bytes: &'a mut [u8],
    dims: &PrefillDims,
    rows: usize,
) -> Result<(Scratch<'a>, usize), ForwardError> {
    let mut c = Carver::new(bytes);
    let scratch = Scratch {
        residual: c.take(rows * dims.hidden)?,
        normed: c.take(rows * dims.hidden)?,
        q: c.take(rows * dims.q_dim)?,
        attn_out: c.take(rows * dims.q_dim)?,
        k: c.take(rows * dims.kv_dim)?,
        v: c.take(rows * dims.kv_dim)?,
        tmat: c.take(rows * dims.wide)?,
        staged: c.take(rows * dims.top_k * dims.hidden)?,
        gate: c.take(rows * dims.moe)?,
        up: c.take(rows * dims.moe)?,
        moe_t: c.take(rows * dims.moe)?,
        attn_shards: c.take(dims.attn_scratch())?,
        router_logits: c.take(rows * dims.n_experts)?,
        router_probs: c.take(rows * dims.n_experts)?,
        acts_hidden: c.take(rows * dims.hidden_q8k)?,
        acts_gather: c.take(rows * dims.hidden_q8k)?,
        acts_attn: c.take(rows * dims.attn_q8k)?,
        acts_moe: c.take(rows * dims.moe_q8k)?,
        acts_q80: c.take(rows * dims.hidden_q80)?,
        topk: c.take(rows * dims.top_k)?,
        index: c.take(rows * dims.top_k)?,
        index_start: c.take(dims.n_experts + 1)?,
        index_cursor: c.take(dims.n_experts)?,
    };
    Ok((scratch, c.used()))
}

// ---------------------------------------------------------------------------
// Pool fan-out for the batched kernels
// ---------------------------------------------------------------------------

/// A row-major buffer whose rows are handed out across the pool's threads.
///
/// [`for_each_row`] gives each row to exactly one body, and a body only
/// rebuilds the rows it was given, so no two threads ever hold a view of the
/// same row. The buffer stays mutably borrowed for as long as this lives, so
/// nothing outside can see it either.
struct Rows<'a, T> {
    base: *mut T,
    width: usize,
    rows: usize,
    _borrow: PhantomData<&'a mut [T]>,
}

impl<'a, T> Rows<'a, T> {
    /// The first `rows * width` elements of `buf`, as `rows` rows.
    fn new(buf: &'a mut [T], width: usize, rows: usize) -> Result<Self, ForwardError> {
        let need = width.checked_mul(rows).ok_or(KernelError::LengthMismatch {
            what: "prefill rows: width * rows overflows",
            left: width,
            right: rows,
        })?;
        if buf.len() < need {
            return Err(KernelError::LengthMismatch {
                what: "prefill rows: buffer vs width * rows",
                left: buf.len(),
                right: need,
            }
            .into());
        }
        Ok(Self {
            base: buf.as_mut_ptr(),
            width,
            rows,
            _borrow: PhantomData,
        })
    }

    /// Row `r`.
    ///
    /// # Safety
    ///
    /// No other view of row `r` may be live. Call it only from a
    /// [`for_each_row`] body, only for the row that body was handed, and only
    /// once per call.
    #[allow(clippy::mut_from_ref)]
    unsafe fn row(&self, r: usize) -> &mut [T] {
        assert!(r < self.rows, "prefill rows: row {r} of {}", self.rows);
        // SAFETY: in bounds, because `r < rows` and `new` checked
        // `rows * width <= buf.len()`; exclusive by the caller's contract;
        // alive no longer than the borrow `PhantomData` holds.
        unsafe { std::slice::from_raw_parts_mut(self.base.add(r * self.width), self.width) }
    }
}

// SAFETY: `Rows` only ever hands out disjoint rows (see `row`), each to one
// thread, under a `&mut` borrow of the whole buffer that outlives the job.
unsafe impl<T: Send> Send for Rows<'_, T> {}
// SAFETY: see `Send`.
unsafe impl<T: Send> Sync for Rows<'_, T> {}

/// Run `body(r)` for every row `r` in `0..n`, with rows claimed in chunks by
/// every thread of the pool.
///
/// The error returned is the one a serial `for r in 0..n` would have stopped
/// at: chunks are contiguous and ascending, each stops at its own first
/// failing row, and [`record`] keeps the lowest chunk's. Rows past a failure
/// may still have run in other chunks, which does not matter, because a
/// failed pass leaves state its caller discards either way.
fn for_each_row<F>(pool: &mut ComputePool, n: usize, body: F) -> Result<(), ForwardError>
where
    F: Fn(usize) -> Result<(), ForwardError> + Sync,
{
    let failure: Mutex<Option<(usize, ForwardError)>> = Mutex::new(None);
    pool.run_chunks(n, |chunk| {
        for r in chunk.rows {
            if let Err(err) = body(r) {
                record(&failure, chunk.index, err);
                return;
            }
        }
    });
    taken(failure)
}

/// A raw pointer shared across shards.
///
/// `pub(super)` because [`super::forward`]'s decode-side attention fan-out
/// splits buffers across shards the same way and there is no reason for two
/// copies of the same soundness argument.
pub(super) struct SendPtr(pub(super) *mut f32);

impl SendPtr {
    /// The wrapped pointer.
    ///
    /// A method rather than a field access on purpose: edition 2024 closures
    /// capture disjoint *fields*, so reading `base.0` inside the shard body
    /// would capture a bare `*mut f32` and defeat the `Send`/`Sync` impls
    /// below. Going through `&self` captures the whole wrapper.
    pub(super) fn get(&self) -> *mut f32 {
        self.0
    }
}

// SAFETY: the pointer names a slice the submitting thread holds `&mut` to for
// the whole call, and `ComputePool::run` does not return until every shard has
// dropped whatever it rebuilt from it. Every use in this module rebuilds
// **disjoint** sub-slices, one per shard. This is
// `threads::ComputePool::scatter`'s argument, re-made here because the batched
// kernels shard over *weight rows* while `scatter` shards over output
// *elements*, and one weight row is `n_acts` of them.
//
// `super::forward::pool_decode_attention` used to be an exception: the kv-range
// attention kernel addressed query heads absolutely, so every shard rebuilt a
// view of the *whole* `out` and the soundness argument rested on the kernel
// reading nothing from it. Miri rejected that under both Stacked and Tree
// Borrows — overlapping `&mut` is UB whether or not the writes collide — so the
// kernel now takes only its range's sub-slice and that use is disjoint like
// every other. There is no exception left.
unsafe impl Send for SendPtr {}
// SAFETY: as above.
unsafe impl Sync for SendPtr {}

/// Fan a batched GEMV out over contiguous weight-row ranges.
///
/// `out` is `[out_dim][n_acts]` row-major, so a weight-row range maps to one
/// contiguous sub-slice and every shard writes a disjoint span. Bit-identical
/// to the whole-matrix call: [`crate::threads::shard_range`] is pure and each
/// output element is an independent dot product.
///
/// # Errors
///
/// [`KernelError::LengthMismatch`] when `out` is not `out_dim * n_acts` long,
/// plus whatever the kernel itself reports for the first shard that fails.
fn scatter_rows<F>(
    pool: &mut ComputePool,
    out: &mut [f32],
    out_dim: usize,
    n_acts: usize,
    f: F,
) -> Result<(), KernelError>
where
    F: Fn(Range<usize>, &mut [f32]) -> Result<(), KernelError> + Sync,
{
    let expected = out_dim.saturating_mul(n_acts);
    if out.len() != expected {
        return Err(KernelError::LengthMismatch {
            what: "prefill batched gemv: out vs out_dim * n_acts",
            left: out.len(),
            right: expected,
        });
    }
    if n_acts == 0 || out_dim == 0 {
        return Ok(());
    }
    let failure: Mutex<Option<(usize, KernelError)>> = Mutex::new(None);
    let base = SendPtr(out.as_mut_ptr());
    pool.run_chunks(out_dim, |chunk| {
        let index = chunk.index;
        let start = chunk.rows.start * n_acts;
        let len = chunk.rows.len() * n_acts;
        // SAFETY: chunks are disjoint sub-ranges of `0..out_dim`, each run by
        // exactly one thread, so scaling them by `n_acts` yields disjoint
        // sub-ranges of `0..out_dim * n_acts` — which is `out.len()`, checked
        // above. `out` is mutably borrowed for the whole call, and
        // `run_chunks` joins before returning.
        let dst = unsafe { std::slice::from_raw_parts_mut(base.get().add(start), len) };
        if let Err(err) = f(chunk.rows, dst) {
            record(&failure, index, err);
        }
    });
    taken(failure)
}

/// [`scatter_rows`] for a k-quant weight matrix against Q8_K activations.
#[allow(clippy::too_many_arguments)]
fn pool_batched_q8_k(
    pool: &mut ComputePool,
    format: QuantFormat,
    weight: &[u8],
    in_dim: usize,
    out_dim: usize,
    acts: &[BlockQ8K],
    n_acts: usize,
    out: &mut [f32],
) -> Result<(), KernelError> {
    scatter_rows(pool, out, out_dim, n_acts, |rows, chunk| {
        gemv_q8_k_batched(format, weight, in_dim, out_dim, acts, n_acts, rows, chunk)
    })
}

/// [`scatter_rows`] for the q8_0 `attn_k` matrix against Q8_0 activations.
fn pool_batched_q8_0(
    pool: &mut ComputePool,
    weight: &[u8],
    in_dim: usize,
    out_dim: usize,
    acts: &[BlockQ8_0],
    n_acts: usize,
    out: &mut [f32],
) -> Result<(), KernelError> {
    scatter_rows(pool, out, out_dim, n_acts, |rows, chunk| {
        gemv_q8_0_batched(weight, in_dim, out_dim, acts, n_acts, rows, chunk)
    })
}

/// Attention work a chunk's first `r` rows cost, in units of one
/// position-times-head.
///
/// Row `r` of a chunk starting at absolute position `start` attends
/// `start + r + 1` positions, so the cumulative cost of rows `0..r` is
/// `r * start + r * (r + 1) / 2`. `u128` because the product of two
/// `usize`-sized dimensions is not a `usize` claim anyone should make; the
/// real values are tiny (~2.2 million at the v0 pin).
fn attention_cost(rows: usize, start: usize) -> u128 {
    let rows = rows as u128;
    rows * start as u128 + rows * (rows + 1) / 2
}

/// The rows shard `index` of `shards` owns, split by attention *cost* rather
/// than by row count.
///
/// A pure function of `(rows, start, shards, index)` — nothing about the pool,
/// the wall clock or the order shards finish in reaches it — so the partition
/// is reproducible, and it is contiguous and ascending like
/// [`crate::threads::shard_range`], which it replaces here.
///
/// **Why not an equal-row split.** Row `r` attends `start + r + 1` positions,
/// so the last shard of an equal-row split does far more work than the first
/// and the makespan is set by that last shard. For the first 512-row chunk of
/// a prompt (`start = 0`) over six shards, the equal-row split gives the last
/// shard 39,950 of the 131,328 total cost units against an ideal 21,888 — a
/// 3.3x speedup where 6x was available. Balancing the cost instead gives every
/// shard within one row of `total / shards`.
///
/// **It cannot move a bit.** Rows are independent: each one is a separate
/// `attention_at_in` call reading an immutable `q` and an immutable cache and
/// writing only its own `[q_dim]` output. There is no cross-row reduction to
/// reassociate, so *any* partition of `0..rows` produces the same bytes as the
/// serial loop — which is why the split is free to be cost-balanced rather
/// than merely deterministic.
fn attention_shard_range(rows: usize, start: usize, shards: usize, index: usize) -> Range<usize> {
    if shards == 0 || index >= shards {
        return 0..0;
    }
    if shards == 1 {
        return 0..rows;
    }
    let total = attention_cost(rows, start);
    let lo = attention_boundary(rows, start, total, shards, index);
    let hi = attention_boundary(rows, start, total, shards, index + 1);
    lo..hi
}

/// The first row at which `index / shards` of the chunk's attention cost has
/// been paid: the lower edge of shard `index`'s range.
///
/// [`attention_cost`] is strictly increasing in `rows`, so this is a binary
/// search, and the targets ascend with `index`, so consecutive boundaries
/// never cross.
fn attention_boundary(
    rows: usize,
    start: usize,
    total: u128,
    shards: usize,
    index: usize,
) -> usize {
    if index == 0 {
        return 0;
    }
    if index >= shards {
        return rows;
    }
    let target = total * index as u128 / shards as u128;
    let (mut lo, mut hi) = (0usize, rows);
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        if attention_cost(mid, start) < target {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    lo
}

/// Fan one layer's causal attention out over the compute pool, one row per
/// call.
///
/// EXP-017 measured this loop at 61.3% of a 512-token prefill and 85.2% of an
/// 1891-token one, running on the submitting thread while the other pinned
/// cores sat parked. Rows are independent, so this is the parallel region with
/// the least to argue about in the whole pass: shard `s` calls
/// [`attention_at_in`] on the rows [`attention_shard_range`] gave it, with its
/// own scratch slice out of the session arena and its own `[q_dim]` span of
/// `out`. Nothing is reduced across shards, nothing accumulates in completion
/// order, and every call is bit-identical to the serial `attention_at` on the
/// same row.
///
/// `scratch` is `shards * shard_scratch` f32 — the [`Scratch::attn_shards`]
/// carve — and `out` is `rows * q_dim`.
///
/// # Errors
///
/// [`KernelError::LengthMismatch`] when `q` or `out` is not `rows * q_dim`
/// long, [`ForwardError::PrefillScratch`] when `scratch` is shorter than the
/// pool's shard count needs, and [`ForwardError::Attention`] from the
/// **lowest-indexed** shard that reports one. Lowest index, not first to the
/// mutex: a whole job can fail at once (a short carve fails on every shard),
/// and an error picked by thread race would make the same input report
/// different errors from run to run. The two length checks are what make the
/// raw-pointer splits below sound; they are not a convenience.
///
/// **`out` is not untouched on error**, unlike every other entry point in this
/// module. Shards write rows into `out` as they finish and a failing shard
/// abandons its remaining rows where it stands, so an error leaves an arbitrary
/// prefix of some shards' rows written and the rest holding whatever the arena
/// carve held. That is deliberate — buffering a chunk's worth of attention
/// output to make the write atomic would cost `rows * q_dim` f32 that prefill
/// is not allowed to allocate — and it is harmless because the only caller
/// propagates the error straight out of the layer loop, and
/// [`prefill_prompt`]'s own contract already says the state must be assumed
/// mid-chunk and discarded on any error. Nothing reads `s.attn_out` again on
/// that path.
#[allow(clippy::too_many_arguments)]
fn scatter_attention(
    pool: &mut ComputePool,
    kv: &KvCache,
    layer: usize,
    start: usize,
    rows: usize,
    q_dim: usize,
    scale: f32,
    shard_scratch: usize,
    q: &[f32],
    scratch: &mut [f32],
    out: &mut [f32],
) -> Result<(), ForwardError> {
    if rows == 0 {
        return Ok(());
    }
    let span = rows.saturating_mul(q_dim);
    for (what, len) in [
        ("attention fan-out: q", q.len()),
        ("attention fan-out: out", out.len()),
    ] {
        if len != span {
            return Err(KernelError::LengthMismatch {
                what,
                left: len,
                right: span,
            }
            .into());
        }
    }
    // Checked once, here, rather than inside the shard body: `shard.index <
    // shard.count <= pool.shards()` always holds, so this single comparison is
    // what makes `scratch[index * shard_scratch ..]` in-bounds for every shard
    // — and therefore what makes the raw-pointer split below sound.
    let need = pool.shards().saturating_mul(shard_scratch);
    if scratch.len() < need {
        return Err(ForwardError::PrefillScratch {
            needed: need as u64,
            available: scratch.len() as u64,
        });
    }
    let failure: Mutex<Option<(usize, AttentionError)>> = Mutex::new(None);
    let out_base = SendPtr(out.as_mut_ptr());
    let scratch_base = SendPtr(scratch.as_mut_ptr());
    pool.run(rows, |shard| {
        // `shard.count`, not `pool.shards()`: a job with fewer rows than
        // shards runs inline as a single shard, and the split must agree with
        // the shard it is actually running on.
        let index = shard.index;
        let mine = attention_shard_range(rows, start, shard.count, index);
        // SAFETY: shard indices are distinct across the job and each is
        // visited by exactly one thread, so `index * shard_scratch` names a
        // disjoint `shard_scratch`-long run per shard; the bound check above
        // puts every one of them inside `scratch`, which is mutably borrowed
        // for the whole call and which `run` joins before releasing.
        let slice = unsafe {
            std::slice::from_raw_parts_mut(
                scratch_base.get().add(index * shard_scratch),
                shard_scratch,
            )
        };
        for r in mine {
            // SAFETY: `attention_shard_range` partitions `0..rows` into
            // disjoint contiguous ranges, so row `r` belongs to exactly one
            // shard and `r * q_dim .. (r + 1) * q_dim` is a disjoint run
            // inside `out`, whose length the caller pins at `rows * q_dim`.
            let row_out =
                unsafe { std::slice::from_raw_parts_mut(out_base.get().add(r * q_dim), q_dim) };
            if let Err(err) = attention_at_in(
                &q[r * q_dim..(r + 1) * q_dim],
                kv,
                layer,
                start + r + 1,
                scale,
                slice,
                row_out,
            ) {
                // Abandons this shard's remaining rows and leaves `out` part
                // written; see this function's `# Errors`.
                record(&failure, index, err);
                return;
            }
        }
    });
    taken(failure)?;
    Ok(())
}

/// `dst[c * rows + r] = src[r * cols + c]`.
///
/// Pure data movement: no float arithmetic happens here, so nothing about it
/// can move a bit.
///
/// **Both slices must be exactly `rows * cols` long.** The size contract is
/// checked rather than clamped on purpose: this module's thesis is that the
/// driver may not assume the scratch it was handed is zeroed, and a silently
/// truncated source or a silently dropped destination write would leave the
/// previous chunk's arena bytes in `q`, `k`, `v` or `moe_t` — a numerical
/// divergence with no error attached. Every call site passes exactly-sized
/// slices today; a future sizing mistake gets a [`ForwardError`], not a wrong
/// answer.
///
/// # Errors
///
/// [`ForwardError::Kernel`] with [`KernelError::LengthMismatch`] when either
/// slice is not `rows * cols` long, or when that product overflows.
fn transpose(
    pool: &mut ComputePool,
    src: &[f32],
    rows: usize,
    cols: usize,
    dst: &mut [f32],
) -> Result<(), ForwardError> {
    let expected = rows.checked_mul(cols).ok_or(KernelError::LengthMismatch {
        what: "prefill transpose: rows * cols overflows",
        left: rows,
        right: cols,
    })?;
    for (what, len) in [
        ("prefill transpose: src vs rows * cols", src.len()),
        ("prefill transpose: dst vs rows * cols", dst.len()),
    ] {
        if len != expected {
            return Err(KernelError::LengthMismatch {
                what,
                left: len,
                right: expected,
            }
            .into());
        }
    }
    if expected == 0 {
        return Ok(());
    }
    // One output row per body: output row `c` is column `c` of `src`. A plain
    // copy, so how the rows are split cannot change a bit.
    let out = Rows::new(dst, rows, cols)?;
    for_each_row(pool, cols, |c| {
        // SAFETY: `for_each_row` hands row `c` to this body once.
        let out = unsafe { out.row(c) };
        for (r, value) in out.iter_mut().enumerate() {
            *value = src[r * cols + c];
        }
        Ok(())
    })
}

// ---------------------------------------------------------------------------
// Arena planning
// ---------------------------------------------------------------------------

/// Bytes of sweep ring one [`PrefillSession`] reserves at `config`.
///
/// Mirrors `io::sweep::ring_span`: `windows_in_flight` buffers of the widest
/// window any layer produces, where a window is capped at the layer's own
/// expert count. Recomputed here because the driver has to know whether the
/// carve will fit *before* it asks for one.
fn ring_bytes(layout: &ExpertsLayout, experts_per_window: u32, windows_in_flight: u32) -> u64 {
    let widest = layout
        .layers
        .iter()
        .map(|layer| u64::from(experts_per_window.min(layer.n_experts.max(1))) * layer.stride)
        .max()
        .unwrap_or(0);
    widest.saturating_mul(u64::from(windows_in_flight))
}

/// The chunk width and sweep dials that fit inside the slot slab.
///
/// The configured chunk is the ceiling, never the floor: on a small pool (the
/// unit-test fixture reserves under 1 MiB) a 512-row staging buffer simply
/// does not exist, and refusing to prefill at all would be the wrong answer
/// when a narrower chunk is correct and merely slower. Windows in flight are
/// given up only after the chunk has already been narrowed to one row, since
/// total prefill bytes scale with `ceil(prompt / chunk)` and read-ahead is
/// worth far less than chunk width.
///
/// Dials are validated, never coerced: a zero on either sweep dial is
/// [`PrefillConfig::validate`]'s refusal, and narrowing is only ever applied to
/// values that were legal to begin with.
///
/// # Errors
///
/// [`ForwardError::PrefillScratch`] when not even a single-row chunk fits
/// beside a one-window ring; whatever [`PrefillConfig::validate`] refuses.
fn plan_arena(
    layout: &ExpertsLayout,
    dims: &PrefillDims,
    config: PrefillConfig,
    want_rows: usize,
    pool_bytes: u64,
) -> Result<(usize, SweepConfig), ForwardError> {
    const PAGE: u64 = 4096;
    let config = config.validate()?;
    let mut in_flight = config.windows_in_flight;
    let mut smallest_need = u64::MAX;
    loop {
        let ring = ring_bytes(layout, config.experts_per_window, in_flight);
        // `PrefillSession::begin` pads the scratch up to a page before the
        // ring, so the usable scratch is the page-floor of what is left.
        let budget = scratch_budget(pool_bytes, ring, PAGE);
        // `scratch_bytes` is affine in `rows` — every term is either a
        // constant or `rows * constant`, with no alignment padding (see
        // `every_scratch_type_packs_without_padding`) — so the widest viable
        // chunk is a division rather than a search.
        let one = scratch_bytes(dims, 1)? as u64;
        let two = scratch_bytes(dims, 2)? as u64;
        let per_row = two.saturating_sub(one).max(1);
        let fixed = one.saturating_sub(per_row);
        let mut rows = want_rows
            .max(1)
            .min(usize::try_from(budget.saturating_sub(fixed) / per_row).unwrap_or(usize::MAX));
        // The division is the answer, not a guess; the loop is the belt and
        // braces that keeps a future non-affine term from overflowing the
        // carve instead of narrowing it.
        while rows > 0 && scratch_bytes(dims, rows)? as u64 > budget {
            rows -= 1;
        }
        if rows > 0 {
            if rows < want_rows || in_flight < config.windows_in_flight {
                tracing::debug!(
                    asked_rows = want_rows,
                    rows,
                    asked_windows = config.windows_in_flight,
                    windows_in_flight = in_flight,
                    pool_bytes,
                    "prefill narrowed to fit the expert slot slab"
                );
            }
            return Ok((
                rows,
                SweepConfig {
                    experts_per_window: config.experts_per_window,
                    windows_in_flight: in_flight,
                },
            ));
        }
        smallest_need = smallest_need.min(one.saturating_add(ring));
        if in_flight == 1 {
            return Err(ForwardError::PrefillScratch {
                needed: smallest_need,
                available: pool_bytes,
            });
        }
        in_flight -= 1;
    }
}

/// Scratch bytes left in a `pool_bytes` slab once the ring is reserved.
///
/// The page floor is not decoration: [`PrefillSession`] rounds the scratch
/// request up to a page before placing the ring, so a request that merely
/// fits would push the ring past the slab.
fn scratch_budget(pool_bytes: u64, ring: u64, page: u64) -> u64 {
    pool_bytes.saturating_sub(ring) / page * page
}

// ---------------------------------------------------------------------------
// The driver
// ---------------------------------------------------------------------------

/// Everything outside the scratch span that one chunk mutates.
struct ChunkState<'a> {
    kv: &'a mut KvCache,
    pool: &'a mut ComputePool,
    plan: &'a mut SweepPlan,
    /// Deduplicated routed expert ids for the layer being swept. Owned
    /// outside the scratch because [`PrefillSession::split`] takes it while it
    /// is also handing the scratch back, and the two may not alias.
    routed: &'a mut Vec<u32>,
    /// `(expert, weight)` staging for [`PrefillRouteSink`], which speaks the
    /// same tuple the token-major sink does.
    sink_buf: &'a mut Vec<(u32, f32)>,
    /// The `[vocab]` output, written for the final row of the final chunk.
    logits: &'a mut [f32],
}

/// Run `tokens` through the model, leaving the KV cache advanced by
/// `tokens.len()` positions and the last token's logits in the state.
///
/// This is the prefill entry point: [`crate::generate::generate`] calls it,
/// and so should any driver that wants a prompt consumed at prefill cost
/// rather than decode cost. The path is chosen by
/// [`ForwardState::prefill_config`] — [`PrefillMode::Sweep`] by default,
/// [`PrefillMode::TokenMajor`] for the A/B.
///
/// `tokens` must be non-empty and must continue the KV cache: position `p` is
/// `state.seq_len() + i` for token `i`.
///
/// # Errors
///
/// [`ForwardError::EmptyPrefill`] for an empty prompt;
/// [`ForwardError::Kv`] when the context cap cannot hold the prompt;
/// [`ForwardError::PrefillScratch`] when the expert slot slab cannot host a
/// chunk; [`ForwardError::Sweep`] when a layer sweep fails; kernel, model and
/// I/O failures pass through typed. On error the state must be assumed
/// mid-chunk — the KV cache may be ragged — and discarded.
pub fn prefill_prompt<'s>(
    model: &Model,
    state: &'s mut ForwardState,
    tokens: &[u32],
    on_route: Option<PrefillRouteSink<'_>>,
) -> Result<&'s [f32], ForwardError> {
    prefill_prompt_with_progress(model, state, tokens, on_route, None)
}

/// [`prefill_prompt`] reporting how far through the prompt it is.
///
/// `on_progress` is called after each unit of work commits — a chunk under
/// [`PrefillMode::Sweep`], a token under [`PrefillMode::TokenMajor`] — with
/// `(positions_done, positions_total)`; see [`PrefillProgressSink`] for what
/// those mean and what they do not promise. A long prompt is otherwise a
/// silent multi-second stall for anything driving the runtime, which is the
/// only reason this exists.
///
/// Passing `None` is exactly [`prefill_prompt`], down to the branch: the
/// callback is only reached through an `if let` at the fire site, so an
/// uninstrumented prefill pays one null check per chunk.
///
/// # Errors
///
/// Exactly [`prefill_prompt`]'s. A failed prefill simply stops reporting;
/// `positions_done` never reaches `positions_total`.
pub fn prefill_prompt_with_progress<'s>(
    model: &Model,
    state: &'s mut ForwardState,
    tokens: &[u32],
    on_route: Option<PrefillRouteSink<'_>>,
    on_progress: Option<PrefillProgressSink<'_>>,
) -> Result<&'s [f32], ForwardError> {
    prefill(model, state, tokens, on_route, on_progress, None)
}

/// [`prefill_prompt`], also scoring every prompt position from `first` on
/// against the token that follows it.
///
/// `out[j]` receives `ln p(tokens[first + j + 1] | tokens[..=first + j])`,
/// so `out.len()` must be `tokens.len() - 1 - first`. This is what perplexity
/// needs: one log-probability per scored position, where a plain prefill
/// keeps the last position's logits only. The log-softmax is computed the way
/// llama.cpp's `llama-perplexity` computes it; see [`log_prob`].
///
/// Under [`PrefillMode::Sweep`] no `[rows][vocab]` buffer is ever built: the
/// scored rows go through `lm_head` a block at a time inside the scratch the
/// chunk already holds (see [`score_rows`]). Under
/// [`PrefillMode::TokenMajor`] each scored token's own logits are reduced as
/// they are produced. The two agree bit for bit, as plain prefill does.
///
/// The KV cache and the returned last-token logits are exactly what
/// [`prefill_prompt`] would have left.
///
/// # Errors
///
/// [`ForwardError::ScoreRange`] when `first` and `out.len()` do not describe
/// at least one position `first..tokens.len() - 1`;
/// [`ForwardError::Model`] wrapping
/// [`ModelError::TokenOutOfRange`](super::ModelError::TokenOutOfRange) for a
/// token outside the vocabulary, checked before anything runs because a
/// target can sit in a chunk that has not been embedded yet; otherwise
/// exactly [`prefill_prompt`]'s.
pub fn prefill_prompt_scored<'s>(
    model: &Model,
    state: &'s mut ForwardState,
    tokens: &[u32],
    first: usize,
    out: &mut [f64],
) -> Result<&'s [f32], ForwardError> {
    prefill_scored_in_blocks(model, state, tokens, first, out, MAX_SCORE_BLOCK)
}

/// [`prefill_prompt_scored`] with the `lm_head` block capped at `block`
/// rows, so the tests can make a few rows span several blocks.
fn prefill_scored_in_blocks<'s>(
    model: &Model,
    state: &'s mut ForwardState,
    tokens: &[u32],
    first: usize,
    out: &mut [f64],
    block: usize,
) -> Result<&'s [f32], ForwardError> {
    let scored = tokens
        .len()
        .checked_sub(1)
        .and_then(|last| last.checked_sub(first))
        .filter(|&count| count > 0);
    if scored != Some(out.len()) {
        return Err(ForwardError::ScoreRange {
            first,
            prompt: tokens.len(),
            out: out.len(),
        });
    }
    let vocab = model.arch().vocab;
    if let Some(&token) = tokens.iter().find(|&&t| t >= vocab) {
        return Err(super::ModelError::TokenOutOfRange { token, vocab }.into());
    }
    let mut score = Score {
        tokens,
        first,
        out,
        block: block.clamp(1, MAX_SCORE_BLOCK),
    };
    prefill(model, state, tokens, None, None, Some(&mut score))
}

/// Most rows one scoring block holds. It bounds the per-row accumulators of
/// [`block_log_probs`], which live on the stack. At the v0 dims the `staged`
/// plane holds 55 rows of logits, so the block there is 52, the largest
/// multiple of the batched GEMV's four-row tile that fits.
const MAX_SCORE_BLOCK: usize = 64;

/// The batched GEMV's activation tile. A block is rounded down to a multiple
/// of it when it holds at least one, so every block but the last runs whole
/// tiles. Only a speed matter: the kernel is bit-identical at any width.
const SCORE_TILE: usize = 4;

/// What [`prefill_prompt_scored`] asks of one pass.
struct Score<'a> {
    /// The whole prompt, because a row's target can be in the next chunk.
    tokens: &'a [u32],
    /// The first prompt index scored.
    first: usize,
    /// One slot per scored index, `out[i - first]` for index `i`.
    out: &'a mut [f64],
    /// Most rows one `lm_head` block may hold.
    block: usize,
}

impl Score<'_> {
    /// Whether prompt index `i` is scored.
    fn wants(&self, i: usize) -> bool {
        i >= self.first && i + 1 < self.tokens.len()
    }
}

/// Both prefill entry points, with or without scoring.
fn prefill<'s>(
    model: &Model,
    state: &'s mut ForwardState,
    tokens: &[u32],
    on_route: Option<PrefillRouteSink<'_>>,
    on_progress: Option<PrefillProgressSink<'_>>,
    score: Option<&mut Score<'_>>,
) -> Result<&'s [f32], ForwardError> {
    if tokens.is_empty() {
        return Err(ForwardError::EmptyPrefill);
    }
    let mode = state.prefill_config().validate()?.mode;
    // Armed before the run and closed after it whatever the run did, so a
    // prefill that failed mid-chunk still leaves a `total` the phases can be
    // read against instead of a struct that claims a run is still in flight.
    state.arm_prefill_timing(mode, tokens.len());
    let started = Instant::now();
    let outcome = match mode {
        PrefillMode::TokenMajor => {
            prefill_token_major(model, state, tokens, on_route, on_progress, score)
        }
        PrefillMode::Sweep => prefill_sweep(model, state, tokens, on_route, on_progress, score),
    };
    state.close_prefill_timing(started.elapsed());
    outcome?;
    Ok(state.logits())
}

/// The phase-5 path: one `forward_token` per prompt token.
fn prefill_token_major(
    model: &Model,
    state: &mut ForwardState,
    tokens: &[u32],
    mut on_route: Option<PrefillRouteSink<'_>>,
    mut on_progress: Option<PrefillProgressSink<'_>>,
    mut score: Option<&mut Score<'_>>,
) -> Result<(), ForwardError> {
    let start = state.seq_len()?;
    let last = tokens.len() - 1;
    for (i, &id) in tokens.iter().enumerate() {
        let position = start + i;
        let scored = score.as_deref().is_some_and(|score| score.wants(i));
        let want_logits = i == last || scored;
        match on_route.as_deref_mut() {
            Some(sink) => {
                let mut per_layer = |layer: u32, topk: &[(u32, f32)]| sink(position, layer, topk);
                super::forward_token_traced(
                    model,
                    state,
                    id,
                    position,
                    want_logits,
                    Some(&mut per_layer),
                )?;
            }
            None => {
                super::forward_token(model, state, id, position, want_logits)?;
            }
        }
        if scored && let Some(score) = score.as_deref_mut() {
            score.out[i - score.first] = log_prob(state.logits(), tokens[i + 1])?;
        }
        // Once the token is committed, never before: a progress report is a
        // claim about work that has already happened. This path has no
        // chunks, so its unit is the token — finer than the sweep's, which
        // is the honest granularity rather than a synthetic one.
        if let Some(progress) = on_progress.as_deref_mut() {
            progress(i + 1, tokens.len());
        }
    }
    Ok(())
}

/// The chunked layer-major path.
fn prefill_sweep(
    model: &Model,
    state: &mut ForwardState,
    tokens: &[u32],
    mut on_route: Option<PrefillRouteSink<'_>>,
    mut on_progress: Option<PrefillProgressSink<'_>>,
    mut score: Option<&mut Score<'_>>,
) -> Result<(), ForwardError> {
    let arch = model.arch();
    state.check_arch(arch)?;
    // The shard count and the context cap are part of the carve: the per-row
    // attention runs one shard per pinned core, each with its own scratch
    // slice, and the widest row any chunk can attend is the cache's capacity.
    let dims = PrefillDims::new(arch, state.shards(), state.context_cap())?;
    let config = state.prefill_config().validate()?;

    // The whole prompt is checked against the cap up front, not row by row:
    // a chunk that ran out of cache halfway through would leave the layers
    // ragged, which is a state only a discarded `ForwardState` can hold.
    let start = state.seq_len()?;
    let capacity = state.context_cap();
    if start.saturating_add(tokens.len()) > capacity {
        return Err(ForwardError::Kv(KvError::CapacityExceeded {
            layer: 0,
            capacity,
        }));
    }

    let want_rows = config.chunk.min(tokens.len()).max(1);
    let (rows, sweep_config) = plan_arena(
        model.layout(),
        &dims,
        config,
        want_rows,
        state.cache_bytes(),
    )?;
    let bytes = scratch_bytes(&dims, rows)?;
    tracing::debug!(
        rows,
        prompt = tokens.len(),
        scratch_bytes = bytes,
        sweep = %sweep_config,
        "prefill sweep starting"
    );

    let parts = state.prefill_parts();
    let timing = parts.timing;
    let mut chunk_state = ChunkState {
        kv: parts.kv,
        pool: parts.pool,
        plan: parts.sweep_plan,
        routed: parts.routed,
        sink_buf: parts.topk,
        logits: parts.logits,
    };
    let mut session = parts.stream.begin_prefill(bytes, sweep_config)?;

    // Started here, after the arena exists: the plan and `begin_prefill` are
    // per-pass setup that belongs to no phase, and leaving them outside every
    // region puts them in `other` rather than on the first `Elementwise`
    // boundary that happens to close. The clock is a parameter of `run_chunk`
    // rather than a `ChunkState` field so that it and the chunk driver's
    // field-by-field reborrows stay independent. Always armed: this function
    // is only reachable from `prefill_prompt`, which armed it.
    let mut clock = PhaseClock::new(timing, true);

    let mut position = start;
    let mut rest = tokens;
    while !rest.is_empty() {
        let n = rows.min(rest.len());
        let (chunk, tail) = rest.split_at(n);
        run_chunk(
            model,
            arch,
            &dims,
            rows,
            &mut session,
            &mut chunk_state,
            chunk,
            position,
            tail.is_empty(),
            &mut on_route,
            score.as_deref_mut().map(|score| (score, position - start)),
            &mut clock,
        )?;
        position += n;
        rest = tail;
        // After `run_chunk`, so the report describes committed work, and
        // outside the clock's regions, so an expensive observer is charged to
        // `other` rather than to whichever phase happened to be open. Counted
        // from the start of *this* prompt (`position - start`), not from the
        // start of the cache.
        if let Some(progress) = on_progress.as_deref_mut() {
            progress(position - start, tokens.len());
        }
    }
    session.finish()?;
    Ok(())
}

/// One chunk of `tokens.len()` positions starting at absolute `start`.
///
/// `rows` is the width the scratch was carved for, which is `>= tokens.len()`;
/// a short final chunk simply uses the leading rows of every buffer. `score`
/// carries a scoring request and the prompt index of this chunk's first row.
#[allow(clippy::too_many_arguments)]
fn run_chunk(
    model: &Model,
    arch: &ArchInfo,
    dims: &PrefillDims,
    rows: usize,
    session: &mut PrefillSession<'_>,
    state: &mut ChunkState<'_>,
    tokens: &[u32],
    start: usize,
    want_logits: bool,
    on_route: &mut Option<PrefillRouteSink<'_>>,
    score: Option<(&mut Score<'_>, usize)>,
    clock: &mut PhaseClock<'_>,
) -> Result<(), ForwardError> {
    let n = tokens.len();
    let eps = arch.rms_eps as f32;
    let theta = arch.rope_theta as f32;
    let scale = 1.0 / (dims.head_dim as f32).sqrt();
    let (hidden, q_dim, kv_dim, top_k) = (dims.hidden, dims.q_dim, dims.kv_dim, dims.top_k);

    // 1. Embed every row of the chunk.
    {
        let (s, _) = carve(session.scratch(), dims, rows)?;
        for (r, &token) in tokens.iter().enumerate() {
            model.embed(token, &mut s.residual[r * hidden..(r + 1) * hidden])?;
        }
    }

    for layer in 0..model.n_layers() {
        let lw = model.layer(layer)?;
        let layer_idx = layer as usize;

        // 2a-2i. Everything before the expert phase, with no sweep running.
        {
            let (mut s, _) = carve(session.scratch(), dims, rows)?;

            // (a) attention RMSNorm and (b) both activation quantizations.
            {
                let residual = &*s.residual;
                let normed = Rows::new(&mut *s.normed, hidden, n)?;
                let acts_k = Rows::new(&mut *s.acts_hidden, dims.hidden_q8k, n)?;
                let acts_0 = Rows::new(&mut *s.acts_q80, dims.hidden_q80, n)?;
                for_each_row(state.pool, n, |r| {
                    // SAFETY: `for_each_row` hands row `r` to this body once.
                    let (normed, acts_k, acts_0) =
                        unsafe { (normed.row(r), acts_k.row(r), acts_0.row(r)) };
                    rmsnorm(
                        &residual[r * hidden..(r + 1) * hidden],
                        lw.attn_norm,
                        eps,
                        normed,
                    )?;
                    quantize_row_q8_k(normed, acts_k)?;
                    quantize_row_q8_0(normed, acts_0)?;
                    Ok(())
                })?;
            }

            // (c) Q, K and V for the whole chunk, then transposed back to
            // row-major so every per-row step below reads a contiguous row.
            clock.charge(Phase::Elementwise);
            pool_batched_q8_k(
                state.pool,
                lw.attn_q.format,
                lw.attn_q.bytes,
                hidden,
                q_dim,
                &s.acts_hidden[..n * dims.hidden_q8k],
                n,
                &mut s.tmat[..q_dim * n],
            )?;
            clock.charge(Phase::Projections);
            transpose(
                state.pool,
                &s.tmat[..q_dim * n],
                q_dim,
                n,
                &mut s.q[..n * q_dim],
            )?;
            clock.charge(Phase::Elementwise);
            pool_batched_q8_0(
                state.pool,
                lw.attn_k.bytes,
                hidden,
                kv_dim,
                &s.acts_q80[..n * dims.hidden_q80],
                n,
                &mut s.tmat[..kv_dim * n],
            )?;
            clock.charge(Phase::Projections);
            transpose(
                state.pool,
                &s.tmat[..kv_dim * n],
                kv_dim,
                n,
                &mut s.k[..n * kv_dim],
            )?;
            clock.charge(Phase::Elementwise);
            pool_batched_q8_k(
                state.pool,
                lw.attn_v.format,
                lw.attn_v.bytes,
                hidden,
                kv_dim,
                &s.acts_hidden[..n * dims.hidden_q8k],
                n,
                &mut s.tmat[..kv_dim * n],
            )?;
            clock.charge(Phase::Projections);
            transpose(
                state.pool,
                &s.tmat[..kv_dim * n],
                kv_dim,
                n,
                &mut s.v[..n * kv_dim],
            )?;

            // (d) Per-head QK-RMSNorm then RoPE, at this row's absolute
            // position. HF order, exactly as `forward_token` does it.
            {
                let q_rows = Rows::new(&mut *s.q, q_dim, n)?;
                let k_rows = Rows::new(&mut *s.k, kv_dim, n)?;
                for_each_row(state.pool, n, |r| {
                    let position = start + r;
                    let rope_pos = u32::try_from(position)
                        .map_err(|_| ForwardError::PositionOverflow { position })?;
                    // SAFETY: `for_each_row` hands row `r` to this body once.
                    let (q, k) = unsafe { (q_rows.row(r), k_rows.row(r)) };
                    for head in q.chunks_exact_mut(dims.head_dim) {
                        rmsnorm_in_place(head, lw.attn_q_norm, eps)?;
                    }
                    rope_neox_heads(q, dims.n_heads, dims.head_dim, rope_pos, theta)?;
                    for head in k.chunks_exact_mut(dims.head_dim) {
                        rmsnorm_in_place(head, lw.attn_k_norm, eps)?;
                    }
                    rope_neox_heads(k, dims.n_kv_heads, dims.head_dim, rope_pos, theta)?;
                    Ok(())
                })?;
            }

            // (e) The inversion: the whole chunk's K/V goes in before any of
            // it is attended. The cache is ragged from here until the layer
            // loop moves on.
            for r in 0..n {
                state.kv.append(
                    layer_idx,
                    &s.k[r * kv_dim..(r + 1) * kv_dim],
                    &s.v[r * kv_dim..(r + 1) * kv_dim],
                )?;
            }

            // (f) Causal attention: row r sees positions 0..=start + r and
            // nothing of the rows queued behind it.
            //
            // Charged once around the whole parallel region, not per row: at a
            // 512-row chunk this is 512 calls per layer, and the boundary is
            // worth ~25 ns each while the region is the phase under
            // investigation.
            clock.charge(Phase::Elementwise);
            scatter_attention(
                state.pool,
                state.kv,
                layer_idx,
                start,
                n,
                q_dim,
                scale,
                dims.attn_shard(),
                &s.q[..n * q_dim],
                s.attn_shards,
                &mut s.attn_out[..n * q_dim],
            )?;

            clock.charge(Phase::Attention);

            // (g) Output projection and the attention residual add.
            {
                let attn_out = &*s.attn_out;
                let acts = Rows::new(&mut *s.acts_attn, dims.attn_q8k, n)?;
                for_each_row(state.pool, n, |r| {
                    // SAFETY: `for_each_row` hands row `r` to this body once.
                    let acts = unsafe { acts.row(r) };
                    quantize_row_q8_k(&attn_out[r * q_dim..(r + 1) * q_dim], acts)?;
                    Ok(())
                })?;
            }
            clock.charge(Phase::Elementwise);
            pool_batched_q8_k(
                state.pool,
                lw.attn_output.format,
                lw.attn_output.bytes,
                q_dim,
                hidden,
                &s.acts_attn[..n * dims.attn_q8k],
                n,
                &mut s.tmat[..hidden * n],
            )?;
            clock.charge(Phase::Projections);
            // The attention residual add, then (h) the FFN RMSNorm and the
            // expert activations, one row at a time on whichever thread
            // claims it.
            {
                let tmat = &*s.tmat;
                let residual_rows = Rows::new(&mut *s.residual, hidden, n)?;
                let normed = Rows::new(&mut *s.normed, hidden, n)?;
                let acts_k = Rows::new(&mut *s.acts_hidden, dims.hidden_q8k, n)?;
                for_each_row(state.pool, n, |r| {
                    // SAFETY: `for_each_row` hands row `r` to this body once.
                    let (residual, normed, acts_k) =
                        unsafe { (residual_rows.row(r), normed.row(r), acts_k.row(r)) };
                    for (h, value) in residual.iter_mut().enumerate() {
                        // The same single f32 add `vec_add` performs; only the
                        // source's layout differs.
                        *value += tmat[h * n + r];
                    }
                    rmsnorm(residual, lw.ffn_norm, eps, normed)?;
                    quantize_row_q8_k(normed, acts_k)?;
                    Ok(())
                })?;
            }

            // (i) Routing, per row, exactly as `forward_token` routes. Each
            // row's matvec stays one serial f32 sum per expert, in the same
            // order as decode's: splitting rows across threads leaves every
            // row's arithmetic alone, where vectorizing the sum would reorder
            // it and could flip a near-tie in the top-k.
            clock.charge(Phase::Elementwise);
            {
                let normed = &*s.normed;
                let router = lw.router.data();
                let logits_rows = Rows::new(&mut *s.router_logits, dims.n_experts, n)?;
                let probs_rows = Rows::new(&mut *s.router_probs, dims.n_experts, n)?;
                let topk_rows = Rows::new(&mut *s.topk, top_k, n)?;
                for_each_row(state.pool, n, |r| {
                    let normed = &normed[r * hidden..(r + 1) * hidden];
                    // SAFETY: `for_each_row` hands row `r` to this body once.
                    let (logits, probs, topk) =
                        unsafe { (logits_rows.row(r), probs_rows.row(r), topk_rows.row(r)) };
                    for (row, logit) in router.chunks_exact(hidden).zip(logits.iter_mut()) {
                        *logit = dot_f32(row, normed);
                    }
                    probs.copy_from_slice(logits);
                    softmax(probs)?;
                    for entry in topk.iter_mut() {
                        let mut best_e = 0usize;
                        let mut best_p = f32::NEG_INFINITY;
                        for (e, &p) in probs.iter().enumerate() {
                            if p > best_p {
                                best_p = p;
                                best_e = e;
                            }
                        }
                        *entry = TopkEntry {
                            expert: best_e as u32,
                            weight: best_p,
                        };
                        probs[best_e] = f32::NEG_INFINITY;
                    }
                    if arch.norm_topk_prob {
                        let sum: f32 = topk.iter().map(|entry| entry.weight).sum();
                        for entry in topk.iter_mut() {
                            entry.weight /= sum;
                        }
                    }
                    Ok(())
                })?;
            }
            // The sink is the caller's and sees rows in order, as before.
            if let Some(sink) = on_route.as_deref_mut() {
                for r in 0..n {
                    let topk = &s.topk[r * top_k..(r + 1) * top_k];
                    state.sink_buf.clear();
                    state
                        .sink_buf
                        .extend(topk.iter().map(|entry| (entry.expert, entry.weight)));
                    sink(start + r, layer, state.sink_buf);
                }
            }

            clock.charge(Phase::Router);

            // (j) The inverse index, and the routed set the sweep plans on.
            build_index(&mut s, dims, n)?;
            state.routed.clear();
            for expert in 0..dims.n_experts {
                if s.index_start[expert + 1] > s.index_start[expert] {
                    state.routed.push(expert as u32);
                }
            }
            clock.charge(Phase::Elementwise);
        }

        // 2k. Sweep the layer, computing each expert against all its rows.
        //
        // The two boundaries here *are* per iteration, unlike the per-row
        // loops above: this loop turns once per routed expert (~128 a layer,
        // not ~512 a chunk), and splitting the window wait from the arithmetic
        // is the whole question this instrumentation exists to answer.
        let covered = {
            let (bytes, mut sweep) = session.split(state.plan, layer, state.routed)?;
            let (mut s, _) = carve(bytes, dims, rows)?;
            let mut covered = 0usize;
            loop {
                let next = sweep.next_expert()?;
                clock.charge(Phase::ExpertIo);
                let Some(expert) = next else { break };
                covered += run_expert(state.pool, dims, &mut s, n, &expert)?;
                clock.charge(Phase::ExpertCompute);
            }
            sweep.finish()?;
            clock.charge(Phase::ExpertIo);
            covered
        };
        if covered != n * top_k {
            return Err(ForwardError::PrefillCoverage {
                layer,
                covered,
                expected: n * top_k,
            });
        }

        // 2l. Reduce each row's staging in top-k order and add the residual.
        {
            let (mut s, _) = carve(session.scratch(), dims, rows)?;
            reduce_experts(state.pool, &mut s, dims, n)?;
        }
        clock.charge(Phase::Elementwise);
    }

    // 3. The tail. Rows a scored prefill asked for go through `lm_head` a
    //    block at a time; a `[rows][vocab]` logit buffer would be 296.75 MiB
    //    at the v0 dims. The last row's logits follow either way. Scoring
    //    writes the same `normed` and `acts_hidden` bits for that row that
    //    the last-row step does, so the order between the two moves nothing.
    if let Some((score, offset)) = score {
        score_rows(
            model, dims, rows, session, state.pool, score, offset, n, clock,
        )?;
    }
    if want_logits {
        let (s, _) = carve(session.scratch(), dims, rows)?;
        let last = n - 1;
        let residual = &s.residual[last * hidden..(last + 1) * hidden];
        let normed = &mut s.normed[last * hidden..(last + 1) * hidden];
        rmsnorm(residual, model.final_norm(), eps, normed)?;
        let acts = &mut s.acts_hidden[last * dims.hidden_q8k..(last + 1) * dims.hidden_q8k];
        quantize_row_q8_k(normed, acts)?;
        clock.charge(Phase::Elementwise);
        let head = model.lm_head();
        pool_gemv_q8_k(
            state.pool,
            head.format,
            head.bytes,
            head.in_dim,
            head.out_dim,
            acts,
            state.logits,
        )?;
        clock.charge(Phase::Projections);
    }
    Ok(())
}

/// Score this chunk's share of the rows [`prefill_prompt_scored`] asked for.
///
/// Row `r` is prompt index `offset + r`, scored when [`Score::wants`] it,
/// against `tokens[offset + r + 1]`. Those rows get the final RMSNorm and the
/// Q8_K quantization the last-row tail gives its row; then `lm_head` runs
/// batched over up to `block` of them at a time into the `staged` plane, as
/// `[vocab][block]`, and [`block_log_probs`] reduces each column to its
/// target's log-probability.
///
/// `staged` is free here: the last layer's reduction has consumed it, and the
/// next chunk's first sweep rewrites it before reading it. At the v0 dims it
/// holds 55 rows of logits, so a block is 52 rows (30.1 MiB) and scoring adds
/// no byte to the prefill's footprint.
///
/// The batched GEMV is bit-identical per element to the single-row one the
/// last-row tail uses, so a scored row's logits are the bits a prefill that
/// ended at that row would have produced.
#[allow(clippy::too_many_arguments)]
fn score_rows(
    model: &Model,
    dims: &PrefillDims,
    rows: usize,
    session: &mut PrefillSession<'_>,
    pool: &mut ComputePool,
    score: &mut Score<'_>,
    offset: usize,
    n: usize,
    clock: &mut PhaseClock<'_>,
) -> Result<(), ForwardError> {
    // The scored indices are one range, `first..tokens.len() - 1`, so the
    // scored rows of this chunk are one range too.
    let lo = score.first.saturating_sub(offset).min(n);
    let hi = (score.tokens.len() - 1).saturating_sub(offset).min(n);
    if lo >= hi {
        return Ok(());
    }
    let (hidden, hidden_q8k) = (dims.hidden, dims.hidden_q8k);
    let eps = model.arch().rms_eps as f32;
    let final_norm = model.final_norm();
    let (s, _) = carve(session.scratch(), dims, rows)?;
    {
        let residual = &*s.residual;
        let normed = Rows::new(&mut *s.normed, hidden, hi)?;
        let acts = Rows::new(&mut *s.acts_hidden, hidden_q8k, hi)?;
        for_each_row(pool, hi - lo, |j| {
            let r = lo + j;
            // SAFETY: `for_each_row` hands `j`, and so row `r`, to this body
            // once.
            let (normed, acts) = unsafe { (normed.row(r), acts.row(r)) };
            rmsnorm(
                &residual[r * hidden..(r + 1) * hidden],
                final_norm,
                eps,
                normed,
            )?;
            quantize_row_q8_k(normed, acts)?;
            Ok(())
        })?;
    }
    clock.charge(Phase::Elementwise);

    let head = model.lm_head();
    let vocab = head.out_dim;
    let block = score_block(score.block, s.staged.len(), vocab)?;
    let mut r = lo;
    while r < hi {
        let count = block.min(hi - r);
        let logits = &mut s.staged[..vocab * count];
        pool_batched_q8_k(
            pool,
            head.format,
            head.bytes,
            head.in_dim,
            vocab,
            &s.acts_hidden[r * hidden_q8k..(r + count) * hidden_q8k],
            count,
            logits,
        )?;
        clock.charge(Phase::Projections);
        let at = offset + r;
        let slots = at - score.first..at - score.first + count;
        block_log_probs(
            logits,
            count,
            &score.tokens[at + 1..at + 1 + count],
            &mut score.out[slots],
        )?;
        clock.charge(Phase::Elementwise);
        r += count;
    }
    Ok(())
}

/// Rows one `lm_head` block holds: `requested`, capped by what a `staged`
/// plane of `staged` f32 holds at `vocab` logits a row, then rounded down to
/// whole [`SCORE_TILE`]s when it holds at least one.
///
/// At the v0 dims a 512-row chunk's plane holds 55 rows, so the block is 52.
///
/// # Errors
///
/// [`ForwardError::PrefillScratch`] when the plane cannot hold one row of
/// logits. At the v0 dims that is a prefill chunk under 10 rows, which a
/// plain prefill would accept: scoring needs the wider chunk.
fn score_block(requested: usize, staged: usize, vocab: usize) -> Result<usize, ForwardError> {
    let block = requested.min(staged / vocab.max(1));
    if block == 0 {
        return Err(ForwardError::PrefillScratch {
            needed: (vocab * size_of::<f32>()) as u64,
            available: (staged * size_of::<f32>()) as u64,
        });
    }
    Ok(if block >= SCORE_TILE {
        block - block % SCORE_TILE
    } else {
        block
    })
}

/// `ln p(target)` under `logits`, computed the way `llama-perplexity`
/// computes it (llama.cpp b10217, `tools/perplexity/perplexity.cpp`,
/// `log_softmax`): the max in f32, each `exp(logit - max)` in f32 and summed
/// into an f64, then `(logits[target] - max)` in f32 less `ln(sum)` in f64.
///
/// Gate 5 is scored against that tool, so this follows it rather than
/// [`softmax`]. The max uses its `max < l` comparison as well, which skips a
/// NaN instead of propagating it; a NaN logit still reaches the sum and
/// makes the result NaN.
///
/// # Errors
///
/// [`KernelError::LengthMismatch`] when `target` is not inside `logits`.
fn log_prob(logits: &[f32], target: u32) -> Result<f64, ForwardError> {
    let t = target as usize;
    let Some(&picked) = logits.get(t) else {
        return Err(KernelError::LengthMismatch {
            what: "log_prob: target vs vocab",
            left: t,
            right: logits.len(),
        }
        .into());
    };
    let mut max = logits[0];
    for &l in &logits[1..] {
        if max < l {
            max = l;
        }
    }
    let mut sum = 0.0f64;
    for &l in logits {
        sum += f64::from((l - max).exp());
    }
    Ok(f64::from(picked - max) - sum.ln())
}

/// [`log_prob`] for every column of a `[vocab][n]` block: column `c`
/// against `targets[c]`, into `out[c]`.
///
/// The columns are reduced side by side in one pass down the vocabulary, so
/// the block is read in order rather than at a stride of `n`. Each column's
/// max and sum still see its logits in vocabulary order, so `out[c]` is
/// bit-identical to [`log_prob`] over column `c` laid out on its own.
///
/// # Errors
///
/// [`KernelError::LengthMismatch`] when `n` is zero or above
/// [`MAX_SCORE_BLOCK`], when `block` is not a whole number of `n`-wide rows,
/// when `targets` or `out` is not `n` long, or when a target is outside the
/// vocabulary.
fn block_log_probs(
    block: &[f32],
    n: usize,
    targets: &[u32],
    out: &mut [f64],
) -> Result<(), ForwardError> {
    if n == 0
        || n > MAX_SCORE_BLOCK
        || block.is_empty()
        || !block.len().is_multiple_of(n)
        || targets.len() != n
        || out.len() != n
    {
        return Err(KernelError::LengthMismatch {
            what: "block_log_probs: block, targets and out vs n",
            left: block.len(),
            right: n,
        }
        .into());
    }
    let vocab = block.len() / n;
    let mut max = [0.0f32; MAX_SCORE_BLOCK];
    let max = &mut max[..n];
    max.copy_from_slice(&block[..n]);
    for row in block.chunks_exact(n).skip(1) {
        for (m, &l) in max.iter_mut().zip(row) {
            if *m < l {
                *m = l;
            }
        }
    }
    let mut sum = [0.0f64; MAX_SCORE_BLOCK];
    let sum = &mut sum[..n];
    for row in block.chunks_exact(n) {
        for ((s, &l), &m) in sum.iter_mut().zip(row).zip(max.iter()) {
            *s += f64::from((l - m).exp());
        }
    }
    for (c, (&target, slot)) in targets.iter().zip(out.iter_mut()).enumerate() {
        let t = target as usize;
        if t >= vocab {
            return Err(KernelError::LengthMismatch {
                what: "block_log_probs: target vs vocab",
                left: t,
                right: vocab,
            }
            .into());
        }
        *slot = f64::from(block[t * n + c] - max[c]) - sum[c].ln();
    }
    Ok(())
}

/// Build the CSR inverse routing index: for each expert, the `(row, slot)`
/// pairs that route to it.
///
/// The index is a permutation of the chunk's `n * top_k` `(row, slot)` pairs
/// by construction — a counting sort over expert id — which is what lets the
/// coverage check in [`run_chunk`] be a single equality.
///
/// # Errors
///
/// [`ForwardError::RoutedExpertOutOfRange`] if a selection named an expert the
/// layer does not have. Unreachable through the router (the argmax runs over
/// exactly `n_experts` probabilities) and reported rather than trusted,
/// because the alternative is an out-of-bounds index into the CSR arrays.
fn build_index(s: &mut Scratch<'_>, dims: &PrefillDims, n: usize) -> Result<(), ForwardError> {
    s.index_start.fill(0);
    for entry in &s.topk[..n * dims.top_k] {
        let expert = entry.expert as usize;
        let slot =
            s.index_start
                .get_mut(expert + 1)
                .ok_or(ForwardError::RoutedExpertOutOfRange {
                    expert: entry.expert,
                    n_experts: dims.n_experts,
                })?;
        *slot += 1;
    }
    // No row may select the same expert twice — the top-k argmax blanks each
    // winner with `-inf`, so it cannot — and the batch buffers depend on it:
    // `gate`, `up`, `moe_t` and `tmat` are all carved for `rows` activations,
    // and an expert routed by more `(row, slot)` pairs than the chunk has
    // rows would index past every one of them. Checked, not assumed.
    for e in 0..dims.n_experts {
        let count = s.index_start[e + 1] as usize;
        if count > n {
            return Err(ForwardError::RepeatedRoutedExpert {
                expert: e as u32,
                count,
                rows: n,
            });
        }
        s.index_start[e + 1] += s.index_start[e];
    }
    s.index_cursor
        .copy_from_slice(&s.index_start[..dims.n_experts]);
    for r in 0..n {
        for slot in 0..dims.top_k {
            let entry = s.topk[r * dims.top_k + slot];
            let cursor = &mut s.index_cursor[entry.expert as usize];
            let at = *cursor as usize;
            s.index[at] = RowSlot {
                row: r as u32,
                slot: slot as u32,
            };
            *cursor += 1;
        }
    }
    Ok(())
}

/// Compute one swept expert against every chunk row routed to it, staging each
/// result into that row's top-k slot. Returns how many `(row, slot)` pairs it
/// covered.
fn run_expert(
    pool: &mut ComputePool,
    dims: &PrefillDims,
    s: &mut Scratch<'_>,
    n_rows: usize,
    expert: &SweepExpert<'_>,
) -> Result<usize, ForwardError> {
    let e = expert.expert as usize;
    let (lo, hi) = match (s.index_start.get(e), s.index_start.get(e + 1)) {
        (Some(&lo), Some(&hi)) => (lo as usize, hi as usize),
        _ => {
            return Err(ForwardError::RoutedExpertOutOfRange {
                expert: expert.expert,
                n_experts: dims.n_experts,
            });
        }
    };
    if hi <= lo {
        // The sweep only yields routed experts, so this cannot happen through
        // the driver; a chunk that routes nothing to `e` simply has no work.
        return Ok(0);
    }
    let count = hi - lo;
    debug_assert!(count <= n_rows * dims.top_k);
    let (hidden, moe) = (dims.hidden, dims.moe);
    let blocks = dims.hidden_q8k;

    // Gather this expert's rows' activations into one contiguous batch: the
    // batched kernels take `n_acts` consecutive rows, and a routed set is by
    // nature scattered across the chunk.
    let entries = &s.index[lo..hi];
    // Every destination row the scatter at the end writes, checked once up
    // front: it writes through a raw pointer, where an out-of-range row would
    // be undefined behaviour rather than a panic.
    let staged_rows = n_rows * dims.top_k;
    for entry in entries {
        let (row, slot) = (entry.row as usize, entry.slot as usize);
        if row >= n_rows || slot >= dims.top_k {
            return Err(KernelError::LengthMismatch {
                what: "prefill expert scatter: staged row vs n_rows * top_k",
                left: row * dims.top_k + slot,
                right: staged_rows,
            }
            .into());
        }
    }
    {
        let acts_hidden = &*s.acts_hidden;
        let gather = Rows::new(&mut *s.acts_gather, blocks, count)?;
        for_each_row(pool, count, |j| {
            let src = entries[j].row as usize * blocks;
            // SAFETY: `for_each_row` hands row `j` to this body once.
            let dst = unsafe { gather.row(j) };
            dst.copy_from_slice(&acts_hidden[src..src + blocks]);
            Ok(())
        })?;
    }
    let acts = &s.acts_gather[..count * blocks];

    let view = &expert.view;
    let gate_slab = view.gate();
    let up_slab = view.up();
    let down_slab = view.down();
    pool_batched_q8_k(
        pool,
        gate_slab.format,
        gate_slab.bytes,
        hidden,
        moe,
        acts,
        count,
        &mut s.gate[..moe * count],
    )?;
    pool_batched_q8_k(
        pool,
        up_slab.format,
        up_slab.bytes,
        hidden,
        moe,
        acts,
        count,
        &mut s.up[..moe * count],
    )?;
    // SwiGLU is elementwise, so it is layout-agnostic: running it over the
    // whole `[moe][count]` plane performs exactly the per-row operations.
    // SwiGLU is elementwise, so the flat `[moe][count]` buffer splits
    // anywhere.
    {
        let up = &s.up[..moe * count];
        let failure: Mutex<Option<(usize, ForwardError)>> = Mutex::new(None);
        pool.scatter_chunks(&mut s.gate[..moe * count], |chunk, gate| {
            if let Err(err) = swiglu_combine(gate, &up[chunk.rows]) {
                record(&failure, chunk.index, err.into());
            }
        });
        taken(failure)?;
    }
    // Transpose to `[count][moe]` and quantize, one output row at a time:
    // row `j` of `moe_t` is column `j` of `gate`, copied, then the same
    // per-row quantization as before.
    {
        let gate = &s.gate[..moe * count];
        let moe_t = Rows::new(&mut *s.moe_t, moe, count)?;
        let acts_moe = Rows::new(&mut *s.acts_moe, dims.moe_q8k, count)?;
        for_each_row(pool, count, |j| {
            // SAFETY: `for_each_row` hands row `j` to this body once.
            let (row, acts) = unsafe { (moe_t.row(j), acts_moe.row(j)) };
            for (i, value) in row.iter_mut().enumerate() {
                *value = gate[i * count + j];
            }
            quantize_row_q8_k(row, acts)?;
            Ok(())
        })?;
    }
    pool_batched_q8_k(
        pool,
        down_slab.format,
        down_slab.bytes,
        moe,
        hidden,
        &s.acts_moe[..count * dims.moe_q8k],
        count,
        &mut s.tmat[..hidden * count],
    )?;
    // Back to `[row][slot][hidden]` staging, split by hidden column: each
    // thread writes its own columns of every destination row, so two threads
    // never write the same element, whatever the index holds.
    {
        let tmat = &s.tmat[..hidden * count];
        let staged = SendPtr(s.staged.as_mut_ptr());
        pool.run_chunks(hidden, |chunk| {
            for h in chunk.rows {
                let src = &tmat[h * count..(h + 1) * count];
                for (entry, &value) in entries.iter().zip(src) {
                    let at = (entry.row as usize * dims.top_k + entry.slot as usize) * hidden + h;
                    // SAFETY: in bounds, because every entry's row and slot
                    // were checked against `n_rows * top_k` above, `h <
                    // hidden`, and `staged` is `[n_rows][top_k][hidden]`.
                    // Disjoint across threads, because each owns its own
                    // `h`s. No reference to `staged` is formed while the job
                    // runs, only these element writes.
                    unsafe { staged.get().add(at).write(value) };
                }
            }
        });
    }
    Ok(count)
}

/// Reduce each row's staged expert outputs **in top-k order** and add them to
/// the residual.
///
/// This is the whole bit-identity argument in one function. The sweep hands
/// experts back in ascending blob order; `forward_token` accumulates
/// `acc += w_i * d_i` for `i` in `0..top_k`, descending router probability.
/// f32 addition is not associative, so the two orders give different bits, and
/// the only way to have both a blob-order sweep and a top-k-order sum is to
/// stage every expert's output and reduce afterwards — which is exactly what
/// `forward_token` already does for its own two-phase hit/miss split.
///
/// The operations are literally the same as `forward_token`'s: separate
/// multiply and add (never `mul_add`, whose single rounding differs), an
/// accumulator starting at 0.0 that takes each slot in top-k order, and one add
/// into the residual. Rows are independent, so they are split across the pool.
fn reduce_experts(
    pool: &mut ComputePool,
    s: &mut Scratch<'_>,
    dims: &PrefillDims,
    n: usize,
) -> Result<(), ForwardError> {
    let (hidden, top_k) = (dims.hidden, dims.top_k);
    let (topk, staged) = (&*s.topk, &*s.staged);
    let residual_rows = Rows::new(&mut *s.residual, hidden, n)?;
    for_each_row(pool, n, |r| {
        // SAFETY: `for_each_row` hands row `r` to this body once.
        let residual = unsafe { residual_rows.row(r) };
        let weights = &topk[r * top_k..(r + 1) * top_k];
        let staged = &staged[r * top_k * hidden..(r + 1) * top_k * hidden];
        // Element by element, the same operations in the same order as
        // `forward_token` accumulating whole rows into a zeroed `expert_acc`
        // and then `vec_add`ing it: start at 0.0, add each slot's
        // `weight * d` in slot order, then one add into the residual. Only
        // the loop nest is turned inside out, which is what lets it run
        // without a shared accumulator row.
        for (h, value) in residual.iter_mut().enumerate() {
            let mut acc = 0.0f32;
            for (slot, entry) in weights.iter().enumerate() {
                acc += entry.weight * staged[slot * hidden + h];
            }
            *value += acc;
        }
        Ok(())
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::{ExpertsLayout, LayerLayout};
    use crate::io::testutil::{Fixture, build_install};
    use crate::io::{LoadOptions, SweepError};
    use crate::model::RuntimeConfig;
    use crate::model::testsupport::temper_install;

    const SKIP: LoadOptions = LoadOptions {
        skip_hashes: true,
        verify_layer_hashes: false,
        common_memory: crate::io::CommonMemory::Mapped,
    };

    /// A small unpinned pool for the helpers that fan out on their own.
    fn test_pool() -> crate::threads::ComputePool {
        crate::threads::ComputePool::with_config(crate::threads::PoolConfig {
            shards: Some(3),
            placement: crate::threads::Placement::Off,
            pin_caller: false,
            ..crate::threads::PoolConfig::default()
        })
    }

    fn load_fixture(tag: &str) -> (Fixture, Model) {
        let fx = build_install(tag);
        temper_install(&fx);
        let model = Model::load(&fx.root, SKIP).unwrap();
        (fx, model)
    }

    /// A state over the tiny fixture with an explicit prefill config.
    fn state_with(model: &Model, cap: usize, prefill: PrefillConfig) -> ForwardState {
        let mut st = ForwardState::with_config(model, cap, RuntimeConfig::testing()).unwrap();
        st.set_prefill_config(prefill).unwrap();
        st
    }

    fn sweep_config(chunk: usize) -> PrefillConfig {
        PrefillConfig {
            mode: PrefillMode::Sweep,
            chunk,
            // The fixture pool is under 1 MiB; one narrow window keeps the
            // ring small enough to leave room for a several-row chunk.
            experts_per_window: 1,
            windows_in_flight: 1,
        }
    }

    fn token_major_config() -> PrefillConfig {
        PrefillConfig {
            mode: PrefillMode::TokenMajor,
            ..sweep_config(1)
        }
    }

    fn logit_bits(logits: &[f32]) -> Vec<u32> {
        logits.iter().map(|v| v.to_bits()).collect()
    }

    /// The second bit-identity fixture: a geometry chosen so that no two of
    /// the driver's widths can accidentally agree.
    ///
    /// [`build_install`] is one hard-coded geometry — `hidden 256`, `q_dim
    /// 256`, `moe 256`, `4` experts, `top_k 2` — and every prefill test above
    /// runs it at `experts_per_window: 1, windows_in_flight: 1`. Four things
    /// the driver does are therefore never exercised there, each of which is
    /// a place a future defect would hide silently rather than fail:
    ///
    /// - **`wide = max(q_dim, hidden)` is degenerate** at `256 == 256`, so
    ///   `tmat`'s four slicings (`q_dim * n`, `kv_dim * n`, `hidden * n`,
    ///   `hidden * count`) collapse to one width and a wrong one would still
    ///   read the right bytes. The shipped model is `q_dim 4096` against
    ///   `hidden 2048`.
    /// - **`hidden_q8k == 1`**, so [`run_expert`]'s `acts_gather` block copy
    ///   is a single-block copy. The shipped model has `2048 / 256 = 8`.
    /// - **`experts_per_window == 1`**, so the sweep's intra-window
    ///   `within * stride` offset is never reached from this driver. The
    ///   production default is 8.
    /// - **No skip pressure**: 4 experts at 1 per window leaves nothing for a
    ///   chunk's routing to miss.
    ///
    /// `scripts/bitident.py` closes none of them either — its prompts are
    /// 4-12 tokens and single-chunk. Hence this: `hidden 512`, `q_dim 768`,
    /// `kv_dim 192`, `moe 256` (**pairwise different**, so a wrong width
    /// cannot accidentally agree), `hidden_q8k 2`, `attn_q8k 3`, 16 experts
    /// at `top_k 4`.
    ///
    /// The builder is `io::testutil::build_install_with`; this module is
    /// only the geometry and the payload policy handed to it.
    mod wide {
        use crate::io::testutil::{Fixture, Geometry, build_install_with};
        use crate::model::testsupport::temper_install;

        /// Layers in the fixture.
        pub(super) const N_LAYERS: u32 = 2;
        /// Experts per layer — enough that a chunk's routing cannot cover
        /// them all, which is what produces skipped windows.
        pub(super) const N_EXPERTS: u32 = 16;
        /// Experts per token.
        pub(super) const TOP_K: u32 = 4;
        /// Hidden dimension: two Q8_K super-blocks per row, unlike the
        /// single-block fixture.
        pub(super) const HIDDEN: usize = 512;
        /// Per-expert FFN intermediate — deliberately not `HIDDEN`.
        pub(super) const MOE: usize = 256;
        /// Query heads.
        pub(super) const N_HEADS: usize = 12;
        /// KV heads: 4:1 GQA.
        pub(super) const N_KV_HEADS: usize = 3;
        /// Head dimension.
        pub(super) const HEAD_DIM: usize = 64;
        /// `n_heads * head_dim` = 768, so `wide = q_dim > hidden`.
        pub(super) const Q_DIM: usize = N_HEADS * HEAD_DIM;
        /// `n_kv_heads * head_dim` = 192.
        pub(super) const KV_DIM: usize = N_KV_HEADS * HEAD_DIM;
        /// Vocabulary size.
        pub(super) const VOCAB: usize = 40;

        /// RMSNorm weight near 1, varying per element.
        ///
        /// `io::testutil`'s ramp reaches 128 at `hidden 512`, which pushes the
        /// value projections out of the KV cache's f16 range; this fixture is
        /// twice as wide, so its norms are gentler on purpose.
        fn norm_value(name: &str, index: usize) -> f32 {
            1.0 + (((index * 7 + name.len()) % 13) as f32) / 64.0
        }

        /// Router weight: signed and non-monotonic, so different tokens
        /// genuinely select different experts. A ramp would make every row
        /// route to the same top-k and leave the skip logic untested.
        ///
        /// Unlike [`norm_value`] this ignores the tensor name; the builder
        /// passes one for both so a geometry can vary either.
        fn router_value(_name: &str, index: usize) -> f32 {
            ((((index * 37 + 11) % 29) as f32) - 14.0) / 64.0
        }

        /// The geometry this fixture hands `io::testutil::build_install_with`.
        pub(super) const GEOMETRY: Geometry = Geometry {
            n_layers: N_LAYERS,
            n_experts: N_EXPERTS,
            top_k: TOP_K,
            hidden: HIDDEN,
            moe_intermediate: MOE,
            n_heads: N_HEADS,
            n_kv_heads: N_KV_HEADS,
            head_dim: HEAD_DIM,
            vocab: VOCAB,
            model_id: "fixture-moe-wide-2l",
            hf_repo: "test/fixture-wide",
            source_file: "fixture-wide-Q4_K_M.gguf",
            norm_value,
            router_value,
        };

        /// Build a complete, tempered install under a fresh temp dir.
        ///
        /// Load it with `skip_hashes`: the tempering rewrites block scales
        /// after the manifest digests are taken, exactly as
        /// `io::testutil` + `temper_install` do for the narrow fixture.
        pub(super) fn build(tag: &str) -> Fixture {
            let fx = build_install_with(tag, &GEOMETRY);
            temper_install(&fx);
            fx
        }
    }

    /// Prefill `ids` through a fresh state and return the final logits' bits.
    fn run(model: &Model, prefill: PrefillConfig, ids: &[u32]) -> Vec<u32> {
        let mut st = state_with(model, 64, prefill);
        let logits = prefill_prompt(model, &mut st, ids, None).unwrap();
        assert_eq!(logits.len(), crate::io::testutil::VOCAB);
        logit_bits(logits)
    }

    // ---- the load-bearing test ------------------------------------------

    /// **The** test: the sweep and the token-major loop must agree bit for
    /// bit, across chunk sizes, at prompt lengths that are an exact multiple
    /// of the chunk, that are not, and that are shorter than one chunk.
    #[test]
    fn sweep_and_token_major_agree_bit_for_bit() {
        let (_fx, model) = load_fixture("prefill-bitident");
        let prompt: Vec<u32> = (0..12u32).map(|i| (i * 5 + 1) % 32).collect();

        for &len in &[1usize, 2, 3, 4, 6, 7, 8, 12] {
            let ids = &prompt[..len];
            let want = run(&model, token_major_config(), ids);
            for &chunk in &[1usize, 2, 3, 4, 8, 512] {
                let got = run(&model, sweep_config(chunk), ids);
                assert_eq!(
                    got,
                    want,
                    "prompt len {len}, chunk {chunk}: sweep prefill diverged \
                     (exact multiple: {})",
                    len % chunk == 0
                );
            }
        }
    }

    // ---- the same test, on a geometry that cannot hide a width bug --------

    /// A state over [`wide`]. Its expert blobs are ~252 KiB against the narrow
    /// fixture's ~26 KiB, so the 4 MiB [`RuntimeConfig::testing`] budget
    /// cannot host a multi-window ring beside a chunk and [`plan_arena`] would
    /// narrow `windows_in_flight` straight back to 1 — which is the dial these
    /// tests exist to raise. 24 MiB leaves ~16 MiB of scratch beside the
    /// widest ring used here.
    fn wide_state(model: &Model, cap: usize, prefill: PrefillConfig) -> ForwardState {
        let runtime = RuntimeConfig {
            cache_bytes: 24 * 1024 * 1024,
            threads: Some(2),
            placement: crate::threads::Placement::Off,
        };
        let mut st = ForwardState::with_config(model, cap, runtime).unwrap();
        st.set_prefill_config(prefill).unwrap();
        st
    }

    fn wide_dials(
        mode: PrefillMode,
        chunk: usize,
        experts_per_window: u32,
        windows_in_flight: u32,
    ) -> PrefillConfig {
        PrefillConfig {
            mode,
            chunk,
            experts_per_window,
            windows_in_flight,
        }
    }

    fn load_wide(tag: &str) -> (Fixture, Model) {
        let fx = wide::build(tag);
        let model = Model::load(&fx.root, SKIP).unwrap();
        (fx, model)
    }

    /// Prefill `ids` through a fresh wide state and return the logits' bits.
    fn wide_run(model: &Model, prefill: PrefillConfig, ids: &[u32]) -> Vec<u32> {
        let mut st = wide_state(model, 64, prefill);
        let logits = prefill_prompt(model, &mut st, ids, None).unwrap();
        assert_eq!(logits.len(), wide::VOCAB);
        assert!(
            logits.iter().all(|v| v.is_finite()),
            "the wide fixture produced non-finite logits, so bit-identity \
             between two NaN-producing paths would prove nothing"
        );
        logit_bits(logits)
    }

    /// The fixture is only worth its runtime if every width it was built to
    /// separate is actually separated. Asserted rather than commented,
    /// because a later edit that quietly collapses two of them would make
    /// every test below pass for the wrong reason.
    #[test]
    fn the_wide_geometry_separates_every_width() {
        let (_fx, model) = load_wide("prefill-wide-geometry");
        let dims = PrefillDims::new(model.arch(), 2, 64).unwrap();

        // The builder derives the projection widths from the head counts, so
        // pin them here: a head-count edit that collapsed `q_dim` onto
        // `hidden` would otherwise reach the driver as a plausible geometry.
        assert_eq!((dims.q_dim, dims.kv_dim), (wide::Q_DIM, wide::KV_DIM));

        let widths = [dims.hidden, dims.q_dim, dims.kv_dim, dims.moe];
        for (i, a) in widths.iter().enumerate() {
            for b in &widths[i + 1..] {
                assert_ne!(a, b, "{widths:?} are not pairwise distinct");
            }
        }
        // `wide = max(q_dim, hidden)` is no longer both of them at once, so a
        // `tmat` slicing that used the wrong one would read the wrong bytes.
        assert_eq!(dims.wide, dims.q_dim);
        assert!(dims.wide > dims.hidden, "`wide` is degenerate again");
        // `run_expert`'s `acts_gather` copy is a multi-block copy.
        assert_eq!(dims.hidden_q8k, 2);
        assert_eq!(dims.attn_q8k, 3);
        assert_eq!(dims.moe_q8k, 1);
        assert_eq!(dims.hidden_q80, 16);
        // Enough experts that a chunk's routing cannot cover them all.
        assert_eq!((dims.n_experts, dims.top_k), (16, 4));

        // And [`wide_state`]'s budget really does host the dials the tests
        // below raise: `plan_arena` hands them back unnarrowed, so those tests
        // run at the dials they name rather than quietly falling back to one
        // expert per window and one window in flight.
        let cache_bytes =
            wide_state(&model, 8, wide_dials(PrefillMode::Sweep, 512, 8, 3)).cache_bytes();
        for (experts_per_window, windows_in_flight) in [(1u32, 1u32), (4, 1), (4, 2), (8, 3)] {
            let config = wide_dials(
                PrefillMode::Sweep,
                512,
                experts_per_window,
                windows_in_flight,
            );
            let (rows, planned) =
                plan_arena(model.layout(), &dims, config, 9, cache_bytes).unwrap();
            assert_eq!(rows, 9, "the chunk was narrowed at {config:?}");
            assert_eq!(planned.experts_per_window, experts_per_window);
            assert_eq!(
                planned.windows_in_flight, windows_in_flight,
                "read-ahead was given up at {config:?}"
            );
        }
    }

    /// [`sweep_and_token_major_agree_bit_for_bit`], run through [`wide`] at
    /// `experts_per_window` **1 and above** and several `windows_in_flight`.
    ///
    /// What this covers that the narrow fixture cannot:
    ///
    /// - every `tmat` slicing is a distinguishable width (`q_dim * n` 768n,
    ///   `kv_dim * n` 192n, `hidden * n` 512n) against a buffer carved for
    ///   `wide = 768`, so a slicing that took the wrong dimension would read
    ///   stale arena bytes rather than the right ones by coincidence;
    /// - `run_expert`'s `acts_gather` gather is a two-block copy;
    /// - `experts_per_window > 1` puts more than one expert in a window, which
    ///   is the only way the sweep's intra-window `within * stride` offset is
    ///   reached from this driver;
    /// - `windows_in_flight > 1` overlaps window reads with compute.
    ///
    /// Prompt lengths and chunk widths still cross seams (5 at chunk 2, 8 at
    /// chunk 3), land on exact multiples (4 at chunk 2, 8 at chunk 4, 9 at
    /// chunk 3), leave a ragged final chunk (5 at chunk 4, 9 at chunk 4) and
    /// run shorter than one chunk (every length at chunk 512).
    #[test]
    fn wide_sweep_and_token_major_agree_bit_for_bit() {
        let (_fx, model) = load_wide("prefill-wide-bitident");
        let vocab = wide::VOCAB as u32;
        let prompt: Vec<u32> = (0..9u32).map(|i| (i * 11 + 3) % vocab).collect();
        let dials: [(u32, u32); 4] = [(1, 1), (4, 1), (4, 2), (8, 3)];

        for &len in &[1usize, 3, 4, 5, 8, 9] {
            let ids = &prompt[..len];
            let want = wide_run(&model, wide_dials(PrefillMode::TokenMajor, 1, 1, 1), ids);
            for &chunk in &[2usize, 3, 4, 512] {
                for &(experts_per_window, windows_in_flight) in &dials {
                    let got = wide_run(
                        &model,
                        wide_dials(
                            PrefillMode::Sweep,
                            chunk,
                            experts_per_window,
                            windows_in_flight,
                        ),
                        ids,
                    );
                    assert_eq!(
                        got,
                        want,
                        "prompt len {len}, chunk {chunk}, {experts_per_window} experts/window, \
                         {windows_in_flight} in flight: sweep prefill diverged \
                         (exact multiple: {})",
                        len % chunk == 0
                    );
                }
            }
        }

        // Not a degenerate model whose logits ignore their input: a prompt one
        // token longer must land somewhere else, and the vocabulary must not
        // come back flat. Without this the agreement above could be two paths
        // agreeing on a constant.
        let dials = wide_dials(PrefillMode::Sweep, 4, 4, 2);
        let eight = wide_run(&model, dials, &prompt[..8]);
        assert_ne!(wide_run(&model, dials, &prompt), eight);
        assert!(eight.iter().any(|&bits| bits != eight[0]));
    }

    // ---- scored prefill (gate 5) -----------------------------------------

    /// Score `ids` from `first` on `state` with `lm_head` blocks of at most
    /// `block` rows. Returns the scores' bits and the last logits' bits.
    fn scored(
        model: &Model,
        state: &mut ForwardState,
        ids: &[u32],
        first: usize,
        block: usize,
    ) -> (Vec<u64>, Vec<u32>) {
        let mut out = vec![0.0f64; ids.len() - 1 - first];
        let logits = prefill_scored_in_blocks(model, state, ids, first, &mut out, block).unwrap();
        let logits = logit_bits(logits);
        assert!(
            out.iter().all(|v| v.is_finite() && *v <= 0.0),
            "not log-probabilities: {out:?}"
        );
        (out.iter().map(|v| v.to_bits()).collect(), logits)
    }

    /// Each prefix of `ids` prefilled on its own, its last logits reduced by
    /// [`log_prob`] against the token after it: what every scored position
    /// must reproduce.
    fn prefix_scores(
        model: &Model,
        mut fresh: impl FnMut() -> ForwardState,
        ids: &[u32],
    ) -> Vec<u64> {
        (0..ids.len() - 1)
            .map(|i| {
                let mut st = fresh();
                let logits = prefill_prompt(model, &mut st, &ids[..=i], None).unwrap();
                log_prob(logits, ids[i + 1]).unwrap().to_bits()
            })
            .collect()
    }

    /// **Gate 5's load-bearing test.** Every scored position must get the
    /// bits a prefill that *ended* at that position gives its next token. The
    /// last-row tail is the path gates 1 to 4 already cover, so a scored row
    /// that matches it bit for bit inherits their coverage.
    ///
    /// Across both prefill modes, chunk widths that split the scored rows over
    /// several chunks, and `lm_head` blocks that split one chunk's rows over
    /// several blocks, including blocks that are not whole tiles. The scored
    /// prefill must also leave the plain prefill's last logits and KV length.
    #[test]
    fn scored_rows_match_a_prefill_that_ends_there() {
        let (_fx, model) = load_fixture("prefill-scored");
        let vocab = crate::io::testutil::VOCAB as u32;
        let ids: Vec<u32> = (0..12u32).map(|i| (i * 7 + 3) % vocab).collect();
        let want = prefix_scores(&model, || state_with(&model, 64, sweep_config(512)), &ids);
        let last = run(&model, sweep_config(512), &ids);
        assert!(
            want.iter().any(|&bits| bits != want[0]),
            "every position scored the same, so agreement would prove nothing"
        );

        let configs = [
            token_major_config(),
            sweep_config(1),
            sweep_config(3),
            sweep_config(4),
            sweep_config(5),
            sweep_config(512),
        ];
        for &first in &[0usize, 1, 5, 10] {
            for config in configs {
                for &block in &[1usize, 3, 4, 5, MAX_SCORE_BLOCK] {
                    let mut st = state_with(&model, 64, config);
                    let (got, logits) = scored(&model, &mut st, &ids, first, block);
                    assert_eq!(
                        got,
                        want[first..],
                        "first {first}, {config:?}, block {block}"
                    );
                    assert_eq!(
                        logits, last,
                        "last logits moved: first {first}, {config:?}, block {block}"
                    );
                    assert_eq!(st.seq_len().unwrap(), ids.len());
                }
            }
        }
    }

    /// The same on [`wide`], where a row is two Q8_K blocks and the sweep
    /// runs several experts per window.
    #[test]
    fn wide_scored_rows_match_a_prefill_that_ends_there() {
        let (_fx, model) = load_wide("prefill-wide-scored");
        let vocab = wide::VOCAB as u32;
        let ids: Vec<u32> = (0..9u32).map(|i| (i * 11 + 3) % vocab).collect();
        let token_major = wide_dials(PrefillMode::TokenMajor, 1, 1, 1);
        let want = prefix_scores(&model, || wide_state(&model, 64, token_major), &ids);

        for &first in &[0usize, 4] {
            for &(chunk, experts_per_window, windows_in_flight) in
                &[(2usize, 4u32, 2u32), (3, 8, 3), (512, 4, 1)]
            {
                let dials = wide_dials(
                    PrefillMode::Sweep,
                    chunk,
                    experts_per_window,
                    windows_in_flight,
                );
                for &block in &[1usize, 4, 5, MAX_SCORE_BLOCK] {
                    let mut st = wide_state(&model, 64, dials);
                    let (got, _) = scored(&model, &mut st, &ids, first, block);
                    assert_eq!(
                        got,
                        want[first..],
                        "first {first}, {dials:?}, block {block}"
                    );
                }
            }
        }
    }

    /// A scored prefill that continues a cached prefix scores the same bits
    /// as one that started from empty: chunk offsets are counted from the
    /// prompt's first token, not from the start of the cache.
    #[test]
    fn scored_prefill_continues_a_cache() {
        let (_fx, model) = load_fixture("prefill-scored-continue");
        let vocab = crate::io::testutil::VOCAB as u32;
        let ids: Vec<u32> = (0..12u32).map(|i| (i * 7 + 3) % vocab).collect();
        let want = prefix_scores(&model, || state_with(&model, 64, sweep_config(512)), &ids);
        for config in [token_major_config(), sweep_config(3), sweep_config(512)] {
            let mut st = state_with(&model, 64, config);
            prefill_prompt(&model, &mut st, &ids[..4], None).unwrap();
            let (got, _) = scored(&model, &mut st, &ids[4..], 1, 3);
            assert_eq!(got, want[5..], "{config:?}");
            assert_eq!(st.seq_len().unwrap(), ids.len());
        }
    }

    /// The block size: capped by the plane, whole tiles when it can be,
    /// refused when not even one row of logits fits. The fixtures never reach
    /// the cap (their vocabularies are tiny), so it is pinned here at the v0
    /// dims, where it is what sets the block.
    #[test]
    fn score_block_is_capped_by_the_staged_plane() {
        let vocab = 151_936;
        // v0: a 512-row chunk's `staged` is 512 * 8 * 2,048 f32, 55 rows.
        let staged = 512 * 8 * 2_048;
        assert_eq!(score_block(MAX_SCORE_BLOCK, staged, vocab).unwrap(), 52);
        assert_eq!(score_block(MAX_SCORE_BLOCK, 7 * vocab, vocab).unwrap(), 4);
        assert_eq!(score_block(MAX_SCORE_BLOCK, 3 * vocab, vocab).unwrap(), 3);
        assert_eq!(score_block(5, staged, vocab).unwrap(), 4);
        assert_eq!(score_block(3, staged, vocab).unwrap(), 3);
        // Nine rows' chunk at v0: 9 * 8 * 2,048 f32 is under one vocab row.
        assert!(matches!(
            score_block(MAX_SCORE_BLOCK, 9 * 8 * 2_048, vocab),
            Err(ForwardError::PrefillScratch { .. })
        ));
    }

    /// The side-by-side column reduction is the contiguous one, bit for bit,
    /// at every block width up to the cap.
    #[test]
    fn block_log_probs_match_log_prob_per_column() {
        let vocab = 37;
        for n in [1usize, 2, 4, 5, MAX_SCORE_BLOCK] {
            let block: Vec<f32> = (0..vocab * n)
                .map(|i| (((i * 7919) % 1013) as f32 - 506.0) / 37.0)
                .collect();
            let targets: Vec<u32> = (0..n).map(|c| ((c * 13 + 5) % vocab) as u32).collect();
            let mut out = vec![0.0; n];
            block_log_probs(&block, n, &targets, &mut out).unwrap();
            for c in 0..n {
                let column: Vec<f32> = (0..vocab).map(|v| block[v * n + c]).collect();
                assert_eq!(
                    out[c].to_bits(),
                    log_prob(&column, targets[c]).unwrap().to_bits(),
                    "n {n}, column {c}"
                );
            }
        }
        let mut out = [0.0; 2];
        assert!(block_log_probs(&[0.0; 6], 2, &[0, 3], &mut out).is_err());
        assert!(block_log_probs(&[0.0; 5], 2, &[0, 1], &mut out).is_err());
        assert!(block_log_probs(&[0.0; 6], 2, &[0], &mut out).is_err());
    }

    /// [`log_prob`] is a log-softmax: within float error of a plain f64 one,
    /// and its probabilities sum to one.
    #[test]
    fn log_prob_is_a_log_softmax() {
        let logits: Vec<f32> = (0..300)
            .map(|i| ((i * 31 % 97) as f32 - 48.0) / 5.0)
            .collect();
        let max = logits
            .iter()
            .fold(f64::NEG_INFINITY, |m, &l| m.max(f64::from(l)));
        let lse = max
            + logits
                .iter()
                .map(|&l| (f64::from(l) - max).exp())
                .sum::<f64>()
                .ln();
        let mut total = 0.0;
        for (t, &l) in logits.iter().enumerate() {
            let got = log_prob(&logits, t as u32).unwrap();
            assert!(
                (got - (f64::from(l) - lse)).abs() < 1e-5,
                "token {t}: {got}"
            );
            total += got.exp();
        }
        assert!((total - 1.0).abs() < 1e-5, "{total}");
        assert!(log_prob(&logits, 300).is_err());
    }

    /// A range that cannot be scored is refused before anything runs, and so
    /// is a token outside the vocabulary, even one that is only a target.
    #[test]
    fn scored_prefill_refuses_what_it_cannot_score() {
        let (_fx, model) = load_fixture("prefill-scored-refusals");
        let ids = [1u32, 2, 3, 4];
        let mut st = state_with(&model, 64, sweep_config(512));
        for (prompt, first, slots) in [
            (&ids[..], 0usize, 2usize),
            (&ids[..], 0, 4),
            (&ids[..], 2, 0),
            (&ids[..], 3, 0),
            (&ids[..], 4, 0),
            (&ids[..1], 0, 0),
            (&ids[..0], 0, 0),
        ] {
            let mut out = vec![0.0; slots];
            let err = prefill_prompt_scored(&model, &mut st, prompt, first, &mut out).unwrap_err();
            assert!(
                matches!(err, ForwardError::ScoreRange { .. }),
                "{} tokens, first {first}, {slots} slots: {err}",
                prompt.len()
            );
        }
        let bad = [1u32, 2, crate::io::testutil::VOCAB as u32];
        let mut out = [0.0; 2];
        let err = prefill_prompt_scored(&model, &mut st, &bad, 0, &mut out).unwrap_err();
        assert!(
            matches!(
                err,
                ForwardError::Model(crate::model::ModelError::TokenOutOfRange { .. })
            ),
            "{err}"
        );
        assert_eq!(st.seq_len().unwrap(), 0, "a refused request ran anyway");
    }

    /// The wide fixture's KV cache agrees too, at a dial pair the narrow
    /// fixture cannot reach.
    #[test]
    fn wide_paths_leave_the_same_kv_cache() {
        let (_fx, model) = load_wide("prefill-wide-kv");
        let ids: Vec<u32> = (0..7u32)
            .map(|i| (i * 5 + 2) % wide::VOCAB as u32)
            .collect();

        let mut token_major = wide_state(&model, 32, wide_dials(PrefillMode::TokenMajor, 1, 1, 1));
        prefill_prompt(&model, &mut token_major, &ids, None).unwrap();
        let mut sweep = wide_state(&model, 32, wide_dials(PrefillMode::Sweep, 3, 4, 2));
        prefill_prompt(&model, &mut sweep, &ids, None).unwrap();

        assert_eq!(sweep.seq_len().unwrap(), ids.len());
        for layer in 0..model.n_layers() as usize {
            assert_eq!(
                sweep.kv_k_layer(layer).unwrap(),
                token_major.kv_k_layer(layer).unwrap(),
                "layer {layer} keys"
            );
            assert_eq!(
                sweep.kv_v_layer(layer).unwrap(),
                token_major.kv_v_layer(layer).unwrap(),
                "layer {layer} values"
            );
        }
    }

    /// Windows no row routed are skipped, and the routing that produces them
    /// is genuinely row-dependent.
    ///
    /// The narrow fixture has 4 experts at 1 per window and `top_k 2`, so a
    /// chunk of two rows can cover every window and the skip path may never
    /// run. Here 16 experts at `top_k 4` guarantee it: a one-row chunk names
    /// 4 experts, which at 1 and 2 experts per window cannot reach more than
    /// 4 of the 16 (resp. 8) windows.
    ///
    /// The second assertion is the one that keeps the first honest — a
    /// fixture whose router picked the same 4 experts for every token would
    /// skip windows for a reason that has nothing to do with the driver.
    #[test]
    fn the_wide_sweep_skips_windows_nothing_routed_to() {
        use std::collections::BTreeSet;

        let (_fx, model) = load_wide("prefill-wide-skips");
        let ids: Vec<u32> = (0..6u32)
            .map(|i| (i * 13 + 5) % wide::VOCAB as u32)
            .collect();

        for experts_per_window in [1u32, 2] {
            let mut st = wide_state(
                &model,
                32,
                wide_dials(PrefillMode::Sweep, 1, experts_per_window, 2),
            );
            let mut routed: BTreeSet<u32> = BTreeSet::new();
            {
                let mut sink = |_pos: usize, _layer: u32, topk: &[(u32, f32)]| {
                    routed.extend(topk.iter().map(|&(expert, _)| expert));
                };
                prefill_prompt(&model, &mut st, &ids, Some(&mut sink)).unwrap();
            }

            let stats = st.stream_stats();
            assert_eq!(
                stats.accesses(),
                0,
                "a swept prefill bypasses the expert cache entirely"
            );
            assert!(stats.sweep_windows_read > 0, "{experts_per_window}/window");
            assert!(
                stats.sweep_windows_skipped > 0,
                "{experts_per_window} experts/window: no window went unrouted, \
                 so the skip path is still untested"
            );
            assert!(
                routed.len() > model.arch().top_k as usize,
                "the router picks the same experts for every row, so the skips \
                 above prove nothing about the driver: {routed:?}"
            );
        }
    }

    /// `experts_per_window > 1` really does reach the sweep's intra-window
    /// `within * stride` slice.
    ///
    /// Every other prefill test runs one expert per window, where `within` is
    /// always 0 and slicing the window at the wrong offset would still hand
    /// back the right blob. The bit-identity test above runs at 4 and 8
    /// experts per window and would fail if the slice were wrong — but only if
    /// a routed expert ever sits somewhere other than the head of its window.
    /// That precondition is asserted here rather than assumed, because it
    /// depends on the fixture's router and nothing else would notice if it
    /// stopped holding.
    #[test]
    fn a_wide_window_slices_experts_at_a_non_zero_offset() {
        const EXPERTS_PER_WINDOW: u32 = 4;
        let (_fx, model) = load_wide("prefill-wide-within");
        let ids: Vec<u32> = (0..6u32)
            .map(|i| (i * 13 + 5) % wide::VOCAB as u32)
            .collect();

        // Chunk 1, so each layer's sweep plans on exactly one row's top-k and
        // the sink reports that set directly.
        let mut st = wide_state(
            &model,
            32,
            wide_dials(PrefillMode::Sweep, 1, EXPERTS_PER_WINDOW, 2),
        );
        let mut off_head = 0usize;
        {
            let mut sink = |_pos: usize, _layer: u32, topk: &[(u32, f32)]| {
                off_head += topk
                    .iter()
                    .filter(|&&(expert, _)| expert % EXPERTS_PER_WINDOW != 0)
                    .count();
            };
            prefill_prompt(&model, &mut st, &ids, Some(&mut sink)).unwrap();
        }
        assert!(
            off_head > 0,
            "every routed expert led its window, so `within` was always 0 and \
             the intra-window offset is still untested"
        );
    }

    // ---- back to the narrow fixture --------------------------------------

    /// The KV cache the two paths leave behind must also agree: same length,
    /// same stored f16 bits, on every layer.
    #[test]
    fn both_paths_leave_the_same_kv_cache() {
        let (_fx, model) = load_fixture("prefill-kv-agree");
        let ids: Vec<u32> = (0..7u32).map(|i| (i * 3 + 2) % 32).collect();

        let mut token_major = state_with(&model, 32, token_major_config());
        prefill_prompt(&model, &mut token_major, &ids, None).unwrap();
        let mut sweep = state_with(&model, 32, sweep_config(3));
        prefill_prompt(&model, &mut sweep, &ids, None).unwrap();

        assert_eq!(token_major.seq_len().unwrap(), ids.len());
        assert_eq!(sweep.seq_len().unwrap(), ids.len());
        for layer in 0..model.n_layers() as usize {
            assert_eq!(
                sweep.kv_k_layer(layer).unwrap(),
                token_major.kv_k_layer(layer).unwrap(),
                "layer {layer} keys"
            );
            assert_eq!(
                sweep.kv_v_layer(layer).unwrap(),
                token_major.kv_v_layer(layer).unwrap(),
                "layer {layer} values"
            );
        }
    }

    /// Decode must continue cleanly off a swept prefill: the cache is
    /// uniform, the slot pool is a cache again, and the next token lands on
    /// the position prefill stopped at.
    #[test]
    fn decode_continues_off_a_swept_prefill() {
        let (_fx, model) = load_fixture("prefill-then-decode");
        let ids = [1u32, 2, 3, 4, 5];

        let mut a = state_with(&model, 32, token_major_config());
        prefill_prompt(&model, &mut a, &ids, None).unwrap();
        let want = logit_bits(
            super::super::forward_token(&model, &mut a, 6, 5, true)
                .unwrap()
                .unwrap(),
        );

        let mut b = state_with(&model, 32, sweep_config(2));
        prefill_prompt(&model, &mut b, &ids, None).unwrap();
        assert_eq!(
            b.seq_len().unwrap(),
            5,
            "the cache is uniform after a chunk"
        );
        let got = logit_bits(
            super::super::forward_token(&model, &mut b, 6, 5, true)
                .unwrap()
                .unwrap(),
        );
        assert_eq!(got, want);
    }

    // ---- attention positions --------------------------------------------

    /// Row `r` must attend over exactly `start + r + 1` positions. Proven
    /// where it is observable: the logits of a prompt prefilled as one chunk
    /// equal the logits of the same prompt fed one row at a time, which is
    /// only true if no row saw a position behind it. A row that saw the whole
    /// chunk would make the answer depend on the chunk width.
    #[test]
    fn a_row_never_attends_past_its_own_position() {
        let (_fx, model) = load_fixture("prefill-causal");
        let ids: Vec<u32> = (0..9u32).map(|i| (i * 7 + 3) % 32).collect();

        // Chunk 1 is a row-at-a-time sweep: every row is the last position in
        // its own chunk, so its mask is unambiguous.
        let want = run(&model, sweep_config(1), &ids);
        for chunk in [2usize, 3, 4, 9] {
            assert_eq!(
                run(&model, sweep_config(chunk), &ids),
                want,
                "chunk {chunk} let a row see the future"
            );
        }

        // And the same prompt with one token appended must differ, so the
        // test above is not passing on a degenerate model whose logits ignore
        // the context entirely.
        let mut longer = ids.clone();
        longer.push(11);
        assert_ne!(run(&model, sweep_config(4), &longer), want);
    }

    /// Mid-chunk the KV cache is deliberately ragged — layer `L` holds the
    /// whole chunk while every layer after it still holds `start` — and
    /// [`crate::kv::KvCache::seq_len`] reports that as an error. Two things
    /// follow, and both are asserted here.
    ///
    /// **The driver cannot use `seq_len` per layer**, which is why
    /// [`ForwardState::kv_len`] exists; the window in which `seq_len` refuses
    /// is reproduced directly below, because no successful prefill can be
    /// paused inside it.
    ///
    /// **The raggedness never escapes**: every chunk boundary and the end of
    /// the prompt leave every layer level, at every chunk width, and a prompt
    /// past the context cap is refused before a single row is appended rather
    /// than halfway through one.
    #[test]
    fn the_cache_is_ragged_mid_chunk_and_level_after() {
        let (_fx, model) = load_fixture("prefill-ragged");
        let n_layers = model.n_layers() as usize;

        // The mid-chunk window, reproduced: a layer-major append of a
        // 3-row chunk leaves the cache in a state `seq_len` refuses, and
        // levels it again only when the last layer catches up.
        let arch = model.arch();
        let mut kv = KvCache::new(
            n_layers,
            arch.n_kv_heads as usize,
            arch.head_dim as usize,
            8,
        )
        .unwrap();
        let row = vec![0.25f32; arch.n_kv_heads as usize * arch.head_dim as usize];
        for layer in 0..n_layers {
            for _ in 0..3 {
                kv.append(layer, &row, &row).unwrap();
            }
            assert_eq!(kv.len(layer).unwrap(), 3);
            if layer + 1 < n_layers {
                assert!(
                    matches!(kv.seq_len(), Err(KvError::RaggedLayers { .. })),
                    "layer {layer}: a half-swept chunk must read as ragged"
                );
            }
        }
        assert_eq!(kv.seq_len().unwrap(), 3);

        // Clean runs: level after every chunk boundary, at chunk widths that
        // divide the prompt differently.
        for chunk in [1usize, 2, 3, 4, 5] {
            let mut st = state_with(&model, 16, sweep_config(chunk));
            prefill_prompt(&model, &mut st, &[1, 2, 3, 4, 5], None).unwrap();
            assert_eq!(st.seq_len().unwrap(), 5, "chunk {chunk}");
            for layer in 0..n_layers {
                assert_eq!(st.kv_len(layer).unwrap(), 5, "chunk {chunk} layer {layer}");
            }
        }

        // A prompt past the cap is refused up front, so the cache is left
        // untouched and level rather than half-appended: the check is on the
        // whole prompt, not on the row that would have overflowed.
        let mut st = state_with(&model, 3, sweep_config(2));
        assert!(prefill_prompt(&model, &mut st, &[1, 2, 3, 4], None).is_err());
        assert_eq!(st.seq_len().unwrap(), 0);
        for layer in 0..n_layers {
            assert_eq!(st.kv_len(layer).unwrap(), 0);
        }
    }

    // ---- the inverse index ----------------------------------------------

    /// The index must be a permutation: every `(row, slot)` appears exactly
    /// once, every row contributes all `top_k` of its slots, and each
    /// expert's run holds only entries that named it.
    #[test]
    fn the_inverse_index_is_a_permutation() {
        let dims = PrefillDims {
            hidden: 256,
            q_dim: 256,
            kv_dim: 128,
            moe: 256,
            top_k: 3,
            n_experts: 5,
            n_heads: 4,
            n_kv_heads: 2,
            head_dim: 64,
            hidden_q8k: 1,
            hidden_q80: 8,
            attn_q8k: 1,
            moe_q8k: 1,
            wide: 256,
            shards: 2,
            max_positions: 8,
        };
        let rows = 6usize;
        let mut bytes = vec![0u8; scratch_bytes(&dims, rows).unwrap()];
        let (mut s, _) = carve(&mut bytes, &dims, rows).unwrap();

        // A deliberately lumpy assignment: expert 0 takes many rows, expert 4
        // takes none, and one expert is chosen by every row.
        for r in 0..rows {
            for slot in 0..dims.top_k {
                s.topk[r * dims.top_k + slot] = TopkEntry {
                    expert: ((r * dims.top_k + slot) % 4) as u32,
                    weight: 1.0,
                };
            }
        }
        build_index(&mut s, &dims, rows).unwrap();

        assert_eq!(s.index_start[0], 0);
        assert_eq!(
            s.index_start[dims.n_experts] as usize,
            rows * dims.top_k,
            "the index covers every (row, slot) pair"
        );
        let mut seen = vec![false; rows * dims.top_k];
        for expert in 0..dims.n_experts {
            let (lo, hi) = (
                s.index_start[expert] as usize,
                s.index_start[expert + 1] as usize,
            );
            assert!(lo <= hi, "expert {expert} has a reversed run");
            for entry in &s.index[lo..hi] {
                let flat = entry.row as usize * dims.top_k + entry.slot as usize;
                assert!(
                    !seen[flat],
                    "(row {}, slot {}) twice",
                    entry.row, entry.slot
                );
                seen[flat] = true;
                assert_eq!(
                    s.topk[flat].expert as usize, expert,
                    "entry filed under the wrong expert"
                );
            }
        }
        assert!(seen.iter().all(|&hit| hit), "a (row, slot) pair was lost");
        // Expert 4 is routed by nobody, so its run is empty and the sweep
        // would never be asked for it.
        assert_eq!(s.index_start[4], s.index_start[5]);
    }

    /// A row that selected the same expert twice would give that expert more
    /// activations than the batch buffers hold. The router cannot produce it;
    /// the index refuses it anyway, because the alternative is a slice past
    /// the end of `gate`, `up`, `moe_t` and `tmat` alike.
    #[test]
    fn a_repeated_routed_expert_is_typed() {
        let dims = PrefillDims {
            top_k: 2,
            ..tiny_dims()
        };
        let mut bytes = vec![0u8; scratch_bytes(&dims, 1).unwrap()];
        let (mut s, _) = carve(&mut bytes, &dims, 1).unwrap();
        s.topk[0] = TopkEntry {
            expert: 3,
            weight: 0.5,
        };
        s.topk[1] = TopkEntry {
            expert: 3,
            weight: 0.5,
        };
        assert!(
            matches!(
                build_index(&mut s, &dims, 1).unwrap_err(),
                ForwardError::RepeatedRoutedExpert {
                    expert: 3,
                    count: 2,
                    rows: 1
                }
            ),
            "a doubly-routed expert must be refused"
        );
    }

    /// A selection naming an expert the layer does not have is a typed
    /// refusal, not an out-of-bounds index into the CSR arrays.
    #[test]
    fn an_out_of_range_routed_expert_is_typed() {
        let dims = PrefillDims {
            hidden: 256,
            q_dim: 256,
            kv_dim: 128,
            moe: 256,
            top_k: 2,
            n_experts: 4,
            n_heads: 4,
            n_kv_heads: 2,
            head_dim: 64,
            hidden_q8k: 1,
            hidden_q80: 8,
            attn_q8k: 1,
            moe_q8k: 1,
            wide: 256,
            shards: 2,
            max_positions: 8,
        };
        let mut bytes = vec![0u8; scratch_bytes(&dims, 1).unwrap()];
        let (mut s, _) = carve(&mut bytes, &dims, 1).unwrap();
        s.topk[0] = TopkEntry {
            expert: 4,
            weight: 1.0,
        };
        s.topk[1] = TopkEntry {
            expert: 0,
            weight: 1.0,
        };
        assert!(matches!(
            build_index(&mut s, &dims, 1).unwrap_err(),
            ForwardError::RoutedExpertOutOfRange {
                expert: 4,
                n_experts: 4
            }
        ));
    }

    // ---- the reduction order --------------------------------------------

    /// The reduction must run in top-k order, not arrival order. Built to
    /// fail if it did not: three staged values whose f32 sum is
    /// order-dependent, weighted so that summing them by ascending expert id
    /// (which is the order a sweep yields them in) gives different bits from
    /// summing them by top-k rank.
    #[test]
    fn the_reduction_runs_in_top_k_order_not_arrival_order() {
        let dims = PrefillDims {
            hidden: 4,
            q_dim: 4,
            kv_dim: 4,
            moe: 4,
            top_k: 3,
            n_experts: 3,
            n_heads: 1,
            n_kv_heads: 1,
            head_dim: 4,
            hidden_q8k: 1,
            hidden_q80: 1,
            attn_q8k: 1,
            moe_q8k: 1,
            wide: 4,
            shards: 2,
            max_positions: 8,
        };
        let mut bytes = vec![0u8; scratch_bytes(&dims, 1).unwrap()];
        let (mut s, _) = carve(&mut bytes, &dims, 1).unwrap();

        // Classic non-associative triple. Half an ulp added to 1.0 is a tie
        // and rounds to even, i.e. back to 1.0, twice over — but the two
        // halves summed *first* make a whole ulp, which 1.0 does keep.
        let big = 1.0f32;
        let small = f32::EPSILON / 2.0;
        // Top-k order is (expert 2, expert 0, expert 1): the sweep would
        // deliver 0, 1, 2 instead.
        s.topk[0] = TopkEntry {
            expert: 2,
            weight: 1.0,
        };
        s.topk[1] = TopkEntry {
            expert: 0,
            weight: 1.0,
        };
        s.topk[2] = TopkEntry {
            expert: 1,
            weight: 1.0,
        };
        let staged = [big, small, small];
        for (slot, &value) in staged.iter().enumerate() {
            for h in 0..dims.hidden {
                s.staged[slot * dims.hidden + h] = value;
            }
        }
        s.residual.fill(0.0);
        reduce_experts(&mut test_pool(), &mut s, &dims, 1).unwrap();

        // Top-k order sums big first, so both small terms vanish.
        let want_topk = ((0.0f32 + big) + small) + small;
        // Arrival (ascending expert id) order would sum slot 1 and slot 2
        // first — the two smalls — and their sum survives the add to `big`.
        let arrival = ((0.0f32 + small) + small) + big;
        assert_ne!(
            want_topk.to_bits(),
            arrival.to_bits(),
            "the fixture is not order-sensitive; the test proves nothing"
        );
        for (h, &value) in s.residual.iter().enumerate() {
            assert_eq!(value.to_bits(), want_topk.to_bits(), "element {h}");
        }
    }

    // ---- the sub-allocator ----------------------------------------------

    fn tiny_dims() -> PrefillDims {
        PrefillDims {
            hidden: 512,
            q_dim: 768,
            kv_dim: 256,
            moe: 256,
            top_k: 4,
            n_experts: 9,
            n_heads: 6,
            n_kv_heads: 2,
            head_dim: 128,
            hidden_q8k: 2,
            hidden_q80: 16,
            attn_q8k: 3,
            moe_q8k: 1,
            wide: 768,
            // Two shards over a 16-position cache: `attn_shard` is
            // `3 * 16 + 2 * 128 = 304` f32, so the carve is small enough that
            // the overlap and packing tests still run on a few KiB.
            shards: 2,
            max_positions: 16,
        }
    }

    /// The v0 dims, so the arithmetic quoted on [`scratch_bytes`] is a
    /// checked claim rather than a comment that rots. Six shards is the
    /// shipped pin (six P-cores, the submitting thread among them) and 4096
    /// is the shipped context cap; both are part of the carve now.
    fn qwen3_30b_a3b_dims() -> PrefillDims {
        PrefillDims {
            hidden: 2048,
            q_dim: 32 * 128,
            kv_dim: 4 * 128,
            moe: 768,
            top_k: 8,
            n_experts: 128,
            n_heads: 32,
            n_kv_heads: 4,
            head_dim: 128,
            hidden_q8k: 8,
            hidden_q80: 64,
            attn_q8k: 16,
            moe_q8k: 3,
            wide: 4096,
            shards: 6,
            max_positions: 4096,
        }
    }

    /// The documented v0 figures, to the byte. A 512-row chunk costs 77.93
    /// MiB of the ~1,438 MiB slot slab, of which the `[rows][top_k][hidden]`
    /// staging that makes the reduction order-independent is 32 MiB and the
    /// six per-shard attention carves are 0.76 MiB.
    #[test]
    fn the_documented_v0_scratch_arithmetic_holds() {
        let dims = qwen3_30b_a3b_dims();
        assert_eq!(scratch_bytes(&dims, 512).unwrap(), 81_720_324);
        // Just under 77.94 MiB.
        assert_eq!(81_720_324 / 1024 / 1024, 77);
        // Staging alone, and the pair of `[rows][q_dim]` planes.
        assert_eq!(512 * dims.top_k * dims.hidden * 4, 33_554_432);
        assert_eq!(2 * 512 * dims.q_dim * 4, 16_777_216);
        // The attention carve: `(32/4) * 4096 + 2 * 128` f32 per shard, six
        // shards, which is exactly what the previous total grew by.
        assert_eq!(dims.attn_shard(), 33_024);
        assert_eq!(dims.attn_scratch() * 4, 792_576);
        assert_eq!(80_927_748 + 792_576, 81_720_324);
        // Affine in rows, which `plan_arena` divides by: the attention carve
        // is per *shard*, not per row, so the slope is untouched.
        let per_row = scratch_bytes(&dims, 2).unwrap() - scratch_bytes(&dims, 1).unwrap();
        assert_eq!(per_row, 145_408 + 35 * 292 + 64 * 36 + 2 * 8 * 8);
        assert_eq!(
            scratch_bytes(&dims, 512).unwrap(),
            scratch_bytes(&dims, 1).unwrap() + 511 * per_row
        );

        // Beside the default sweep ring, against the shipped slab: 125 MiB
        // of 1,438, so neither dial is anywhere near the constraint.
        let shipped = layout_of(&[(3_059_712, 128), (2_654_208, 128)]);
        let ring = ring_bytes(&shipped, 8, 2);
        assert_eq!(ring, 48_955_392);
        assert!(ring + 81_720_324 < 1_438 * 1024 * 1024);
    }

    // ---- the attention split ---------------------------------------------

    /// [`attention_shard_range`] is a partition: contiguous, ascending, every
    /// row in exactly one shard, and no shard reaching past `rows`.
    ///
    /// The parallel attention region's whole soundness argument rests on this
    /// — a row visited twice would be two threads writing one `[q_dim]` span,
    /// and a row visited never would be a silently wrong answer.
    #[test]
    fn the_attention_split_partitions_every_row() {
        for rows in [0usize, 1, 2, 5, 6, 7, 8, 63, 512, 1891] {
            for start in [0usize, 1, 7, 512, 4095] {
                for shards in [1usize, 2, 3, 6, 8, 16] {
                    let mut seen = vec![0u32; rows];
                    let mut next = 0usize;
                    for index in 0..shards {
                        let mine = attention_shard_range(rows, start, shards, index);
                        assert!(mine.start <= mine.end, "{mine:?} is reversed");
                        assert_eq!(mine.start, next, "shards {shards} index {index} not flush");
                        assert!(mine.end <= rows, "{mine:?} runs past {rows}");
                        next = mine.end;
                        for r in mine {
                            seen[r] += 1;
                        }
                    }
                    assert_eq!(next, rows, "rows {rows} shards {shards} left a tail");
                    assert!(
                        seen.iter().all(|&hits| hits == 1),
                        "rows {rows} start {start} shards {shards}: {seen:?}"
                    );
                }
            }
        }
    }

    /// The split is a pure function of `(rows, start, shards, index)`.
    ///
    /// Purity is not what makes the region bit-neutral — rows are independent,
    /// so *any* partition gives the same bytes — but it is what makes a run
    /// reproducible, and reproducibility is what makes a bit-identity failure
    /// debuggable instead of a coin flip.
    #[test]
    fn the_attention_split_is_a_pure_function() {
        for (rows, start, shards) in [(512usize, 0usize, 6usize), (355, 1536, 6), (17, 512, 3)] {
            for index in 0..shards {
                let once = attention_shard_range(rows, start, shards, index);
                for _ in 0..4 {
                    assert_eq!(attention_shard_range(rows, start, shards, index), once);
                }
            }
        }
    }

    /// The split balances *cost*, not row count: row `r` attends
    /// `start + r + 1` positions, so an equal-row split leaves the last shard
    /// of the first 512-row chunk with 39,950 of 131,328 cost units against an
    /// ideal 21,888 — a 3.3x makespan where 6x was available. This is the
    /// assertion that a future edit reverting to `shard_range` would fail.
    #[test]
    fn the_attention_split_balances_cost_not_rows() {
        let (rows, start, shards) = (512usize, 0usize, 6usize);
        let total = attention_cost(rows, start);
        assert_eq!(total, 131_328);
        let ideal = total / shards as u128;

        let mut widest = 0u128;
        for index in 0..shards {
            let mine = attention_shard_range(rows, start, shards, index);
            let cost = attention_cost(mine.end, start) - attention_cost(mine.start, start);
            // Every shard within one row's worth of the ideal, which at this
            // chunk is at most 512 units against an ideal of 21,888.
            let slack = cost.abs_diff(ideal);
            assert!(
                slack <= (start + rows) as u128,
                "shard {index} {mine:?} costs {cost}, ideal {ideal}"
            );
            widest = widest.max(cost);
        }
        // Cost-balanced means row-unbalanced, and deliberately so: the cheap
        // early rows come in bulk and the expensive late ones do not.
        let first = attention_shard_range(rows, start, shards, 0).len();
        let last = attention_shard_range(rows, start, shards, shards - 1).len();
        assert!(first > last * 2, "{first} rows against {last}");

        // The equal-row split's last shard, for contrast: 39,950 cost units
        // against the balanced split's 22,175 makespan, an ideal of 21,888.
        let naive = attention_cost(rows, start) - attention_cost(rows - rows / shards, start);
        assert!(
            widest * 3 < naive * 2,
            "cost balancing bought too little: {widest} vs {naive}"
        );
    }

    /// The carve consumes exactly what [`scratch_bytes`] promised. The two
    /// walk the same sequence in the same order, and this is what keeps them
    /// from drifting: a buffer added to one and not the other fails here.
    #[test]
    fn carve_consumes_exactly_the_documented_bytes() {
        let dims = tiny_dims();
        for rows in [1usize, 2, 7, 33] {
            let total = scratch_bytes(&dims, rows).unwrap();
            let mut bytes = vec![0u8; total];
            let (_, used) = carve(&mut bytes, &dims, rows).unwrap();
            assert_eq!(used, total, "rows {rows}");
        }
    }

    /// Every block type the carve hands out is 4-aligned with a size that is
    /// a whole number of 4-byte units, which is why no padding ever appears
    /// between two carved buffers and `scratch_bytes` can be a plain sum.
    #[test]
    fn every_scratch_type_packs_without_padding() {
        for (name, size, align) in [
            ("f32", size_of::<f32>(), align_of::<f32>()),
            ("u32", size_of::<u32>(), align_of::<u32>()),
            ("BlockQ8K", size_of::<BlockQ8K>(), align_of::<BlockQ8K>()),
            ("BlockQ8_0", size_of::<BlockQ8_0>(), align_of::<BlockQ8_0>()),
            ("TopkEntry", size_of::<TopkEntry>(), align_of::<TopkEntry>()),
            ("RowSlot", size_of::<RowSlot>(), align_of::<RowSlot>()),
        ] {
            assert_eq!(align, 4, "{name} alignment");
            assert_eq!(size % 4, 0, "{name} size {size}");
        }
        assert_eq!(size_of::<BlockQ8K>(), 292);
        assert_eq!(size_of::<BlockQ8_0>(), 36);
    }

    /// The carved buffers are disjoint and in bounds: stamping each one with
    /// a distinct byte and reading the span back finds every stamp intact.
    #[test]
    fn carved_buffers_do_not_overlap() {
        let dims = tiny_dims();
        let rows = 5usize;
        let total = scratch_bytes(&dims, rows).unwrap();
        let mut bytes = vec![0u8; total];
        {
            let (s, _) = carve(&mut bytes, &dims, rows).unwrap();
            s.residual.fill(f32::from_bits(0x0101_0101));
            s.normed.fill(f32::from_bits(0x0202_0202));
            s.q.fill(f32::from_bits(0x0303_0303));
            s.staged.fill(f32::from_bits(0x0404_0404));
            s.attn_shards.fill(f32::from_bits(0x0808_0808));
            s.index_start.fill(0x0606_0606);
            s.index_cursor.fill(0x0707_0707);
        }
        // Re-carve and check every stamp survived, which it cannot if two
        // buffers overlapped.
        let (s, _) = carve(&mut bytes, &dims, rows).unwrap();
        assert!(s.residual.iter().all(|v| v.to_bits() == 0x0101_0101));
        assert!(s.normed.iter().all(|v| v.to_bits() == 0x0202_0202));
        assert!(s.q.iter().all(|v| v.to_bits() == 0x0303_0303));
        assert!(s.staged.iter().all(|v| v.to_bits() == 0x0404_0404));
        assert!(s.attn_shards.iter().all(|v| v.to_bits() == 0x0808_0808));
        assert!(s.index_start.iter().all(|&v| v == 0x0606_0606));
        assert!(s.index_cursor.iter().all(|&v| v == 0x0707_0707));
        assert_eq!(s.residual.len(), rows * dims.hidden);
        assert_eq!(s.staged.len(), rows * dims.top_k * dims.hidden);
        assert_eq!(s.attn_shards.len(), dims.shards * dims.attn_shard());
        assert_eq!(s.index_start.len(), dims.n_experts + 1);
    }

    /// A span one byte short of the layout is a typed refusal, not a panic
    /// and not a silently truncated buffer.
    #[test]
    fn a_short_scratch_span_is_typed() {
        let dims = tiny_dims();
        let total = scratch_bytes(&dims, 3).unwrap();
        let mut bytes = vec![0u8; total - 1];
        assert!(matches!(
            carve(&mut bytes, &dims, 3),
            Err(ForwardError::PrefillScratch { .. })
        ));
        let mut empty: [u8; 0] = [];
        assert!(matches!(
            carve(&mut empty, &dims, 1),
            Err(ForwardError::PrefillScratch { .. })
        ));
    }

    /// The carve does not assume the span starts on a page: it pads to each
    /// type's alignment from wherever it actually is.
    #[test]
    fn the_carve_aligns_from_an_offset_base() {
        let dims = tiny_dims();
        let rows = 2usize;
        let total = scratch_bytes(&dims, rows).unwrap();
        // Three bytes of lead-in, so the base is deliberately misaligned.
        let mut bytes = vec![0u8; total + 8];
        let (s, used) = carve(&mut bytes[3..], &dims, rows).unwrap();
        assert!(used <= total + 3, "padding ran away: {used} vs {total}");
        assert_eq!(s.residual.as_ptr() as usize % align_of::<f32>(), 0);
        assert_eq!(s.acts_hidden.as_ptr() as usize % align_of::<BlockQ8K>(), 0);
    }

    // ---- arena planning --------------------------------------------------

    fn layout_of(strides: &[(u64, u32)]) -> ExpertsLayout {
        ExpertsLayout {
            layers: strides
                .iter()
                .enumerate()
                .map(|(i, &(stride, n_experts))| LayerLayout {
                    file: format!("experts/layer_{i:02}.bin"),
                    stride,
                    n_experts,
                    projections: Vec::new(),
                })
                .collect(),
        }
    }

    /// The ring estimate must match `io::sweep`'s: the widest layer's window,
    /// capped at that layer's expert count, times the windows in flight.
    #[test]
    fn the_ring_estimate_caps_windows_at_the_expert_count() {
        // The shipped geometry: two stride classes, 128 experts, 8 per
        // window, 2 in flight.
        let shipped = layout_of(&[(3_059_712, 128), (2_654_208, 128)]);
        assert_eq!(ring_bytes(&shipped, 8, 2), 2 * 8 * 3_059_712);
        // A layer with fewer experts than the dial cannot make a full window.
        let tiny = layout_of(&[(4096, 3)]);
        assert_eq!(ring_bytes(&tiny, 8, 2), 2 * 3 * 4096);
        // And a zero-expert layer does not produce a zero-wide ring.
        let empty = layout_of(&[(4096, 0)]);
        assert_eq!(ring_bytes(&empty, 8, 1), 4096);
    }

    /// A pool too small for the requested chunk narrows the chunk rather than
    /// refusing to prefill, and gives up read-ahead only after the chunk is
    /// down to a single row.
    #[test]
    fn the_arena_plan_narrows_before_it_refuses() {
        let dims = tiny_dims();
        let layout = layout_of(&[(65_536, 4)]);
        let config = PrefillConfig {
            mode: PrefillMode::Sweep,
            chunk: 512,
            experts_per_window: 8,
            windows_in_flight: 2,
        };

        // Roomy: the full chunk and the full read-ahead.
        let (rows, sweep) = plan_arena(&layout, &dims, config, 512, 64 * 1024 * 1024).unwrap();
        assert_eq!(rows, 512);
        assert_eq!(sweep.windows_in_flight, 2);

        // Tight: the ring is 512 KiB, so the chunk has to shrink.
        let (rows, sweep) = plan_arena(&layout, &dims, config, 512, 1024 * 1024).unwrap();
        assert!((1..512).contains(&rows), "rows {rows}");
        assert_eq!(sweep.windows_in_flight, 2, "read-ahead is given up last");

        // Tighter still: one window's worth plus a row.
        let one_window = 4 * 65_536;
        let (rows, sweep) = plan_arena(
            &layout,
            &dims,
            config,
            512,
            one_window + scratch_bytes(&dims, 1).unwrap() as u64 + 8192,
        )
        .unwrap();
        assert_eq!(rows, 1);
        assert_eq!(sweep.windows_in_flight, 1);

        // Hopeless: a typed refusal naming what it would have needed.
        let err = plan_arena(&layout, &dims, config, 512, one_window).unwrap_err();
        assert!(
            matches!(err, ForwardError::PrefillScratch { .. }),
            "unexpected error: {err}"
        );
    }

    /// The chunk dial is a ceiling, never a floor: a prompt shorter than one
    /// chunk carves for the prompt, not for 512 rows.
    #[test]
    fn a_short_prompt_carves_for_the_prompt() {
        let dims = tiny_dims();
        let layout = layout_of(&[(65_536, 4)]);
        let config = PrefillConfig {
            mode: PrefillMode::Sweep,
            chunk: 512,
            experts_per_window: 8,
            windows_in_flight: 2,
        };
        let (rows, _) = plan_arena(&layout, &dims, config, 3, 64 * 1024 * 1024).unwrap();
        assert_eq!(rows, 3);
    }

    // ---- misc -------------------------------------------------------------

    #[test]
    fn transpose_moves_every_element() {
        let src: Vec<f32> = (0..12).map(|i| i as f32).collect();
        let mut dst = vec![0.0f32; 12];
        transpose(&mut test_pool(), &src, 3, 4, &mut dst).unwrap();
        for r in 0..3 {
            for c in 0..4 {
                assert_eq!(dst[c * 3 + r], src[r * 4 + c]);
            }
        }
        // Degenerate shapes are no-ops rather than panics, as long as both
        // slices agree with `rows * cols == 0`.
        let mut empty: [f32; 0] = [];
        transpose(&mut test_pool(), &[], 0, 4, &mut empty).unwrap();
        transpose(&mut test_pool(), &[], 3, 0, &mut empty).unwrap();
    }

    /// A mis-sized `transpose` is a typed refusal, not a partial copy.
    ///
    /// The old shape dropped out-of-range writes with `dst.get_mut` and
    /// truncated a short source with `chunks_exact(cols).take(rows)`. Both are
    /// silent, and in a module whose whole thesis is that the driver may not
    /// assume its scratch is zeroed, either one would leave the *previous*
    /// chunk's arena bytes in `q`, `k`, `v` or `moe_t` and carry them into the
    /// residual. A numerical divergence with no error attached is the one
    /// failure this module cannot afford; every call site is exactly sized
    /// today, and this is what keeps that a checked fact.
    #[test]
    fn a_mis_sized_transpose_is_typed() {
        let src: Vec<f32> = (0..12).map(|i| i as f32).collect();
        let mut dst = vec![0.0f32; 12];

        // A source one row short would have been silently truncated, leaving
        // the last output column holding whatever `dst` already had.
        assert!(matches!(
            transpose(&mut test_pool(), &src[..8], 3, 4, &mut dst),
            Err(ForwardError::Kernel(KernelError::LengthMismatch {
                left: 8,
                right: 12,
                ..
            }))
        ));
        // A destination one element short would have dropped that write.
        assert!(matches!(
            transpose(&mut test_pool(), &src, 3, 4, &mut dst[..11]),
            Err(ForwardError::Kernel(KernelError::LengthMismatch {
                left: 11,
                right: 12,
                ..
            }))
        ));
        // And a degenerate shape does not excuse a mis-sized slice either.
        assert!(transpose(&mut test_pool(), &[], 0, 4, &mut dst).is_err());
        // `rows * cols` overflowing is typed rather than wrapping.
        assert!(transpose(&mut test_pool(), &src, usize::MAX, 2, &mut dst).is_err());
    }

    /// All three dials refuse at one point.
    ///
    /// They used to refuse at three: the chunk in [`PrefillConfig::validate`],
    /// `experts_per_window == 0` nowhere (it was silently coerced to 1 by
    /// [`plan_arena`]), and an oversized `windows_in_flight` only once the
    /// sweep session was already being opened. Every field is `pub`, so every
    /// field is caller-supplied.
    #[test]
    fn every_prefill_dial_refuses_at_validate() {
        let base = PrefillConfig::default();
        assert!(base.validate().is_ok());

        assert!(matches!(
            PrefillConfig { chunk: 0, ..base }.validate().unwrap_err(),
            ForwardError::InvalidPrefillChunk { chunk: 0 }
        ));
        for bad in [
            PrefillConfig {
                experts_per_window: 0,
                ..base
            },
            PrefillConfig {
                windows_in_flight: 0,
                ..base
            },
            PrefillConfig {
                windows_in_flight: crate::io::MAX_WINDOWS_IN_FLIGHT + 1,
                ..base
            },
        ] {
            let err = bad.validate().unwrap_err();
            assert!(
                matches!(err, ForwardError::Sweep(SweepError::BadDials { .. })),
                "unexpected error for {bad:?}: {err}"
            );
        }

        // And the same refusal reaches the driver's own entry points rather
        // than being coerced by either of them.
        let layout = layout_of(&[(65_536, 4)]);
        assert!(matches!(
            plan_arena(
                &layout,
                &tiny_dims(),
                PrefillConfig {
                    experts_per_window: 0,
                    ..base
                },
                4,
                64 * 1024 * 1024,
            )
            .unwrap_err(),
            ForwardError::Sweep(SweepError::BadDials { .. })
        ));
        let (_fx, model) = load_fixture("prefill-dials");
        let mut st = state_with(&model, 8, sweep_config(4));
        assert!(matches!(
            st.set_prefill_config(PrefillConfig {
                windows_in_flight: crate::io::MAX_WINDOWS_IN_FLIGHT + 1,
                ..sweep_config(4)
            })
            .unwrap_err(),
            ForwardError::Sweep(SweepError::BadDials { .. })
        ));
    }

    #[test]
    fn an_empty_prompt_is_typed() {
        let (_fx, model) = load_fixture("prefill-empty");
        let mut st = state_with(&model, 8, sweep_config(4));
        assert!(matches!(
            prefill_prompt(&model, &mut st, &[], None).unwrap_err(),
            ForwardError::EmptyPrefill
        ));
    }

    #[test]
    fn a_zero_chunk_is_typed() {
        let (_fx, model) = load_fixture("prefill-zero-chunk");
        let mut st = state_with(&model, 8, sweep_config(4));
        assert!(matches!(
            st.set_prefill_config(PrefillConfig {
                chunk: 0,
                ..sweep_config(4)
            })
            .unwrap_err(),
            ForwardError::InvalidPrefillChunk { chunk: 0 }
        ));
    }

    #[test]
    fn a_prompt_past_the_context_cap_is_typed() {
        let (_fx, model) = load_fixture("prefill-cap");
        let mut st = state_with(&model, 3, sweep_config(4));
        let err = prefill_prompt(&model, &mut st, &[1, 2, 3, 4], None).unwrap_err();
        assert!(
            matches!(
                err,
                ForwardError::Kv(KvError::CapacityExceeded { capacity: 3, .. })
            ),
            "unexpected error: {err}"
        );
    }

    /// The route sink sees every `(position, layer)` pair exactly once, with
    /// the same selections the token-major path reports — only the order
    /// differs, which the type's docs promise.
    #[test]
    fn the_route_sink_covers_every_position_and_layer() {
        let (_fx, model) = load_fixture("prefill-sink");
        let ids = [1u32, 2, 3, 4, 5];
        let n_layers = model.n_layers();
        let top_k = model.arch().top_k as usize;

        let collect = |config: PrefillConfig| {
            let mut st = state_with(&model, 16, config);
            let mut seen: Vec<(usize, u32, Vec<u32>)> = Vec::new();
            {
                let mut sink = |pos: usize, layer: u32, topk: &[(u32, f32)]| {
                    seen.push((pos, layer, topk.iter().map(|&(e, _)| e).collect()));
                };
                prefill_prompt(&model, &mut st, &ids, Some(&mut sink)).unwrap();
            }
            seen.sort_by_key(|(pos, layer, _)| (*pos, *layer));
            seen
        };

        let want = collect(token_major_config());
        assert_eq!(want.len(), ids.len() * n_layers as usize);
        assert!(want.iter().all(|(_, _, experts)| experts.len() == top_k));
        assert_eq!(collect(sweep_config(2)), want);
        assert_eq!(collect(sweep_config(5)), want);
    }

    /// The environment override is read, and nonsense in it is ignored rather
    /// than fatal.
    #[test]
    fn the_env_override_parses_or_is_ignored() {
        // `from_env` reads process-global state, so this test only asserts
        // the parse table via the same match, not by mutating the
        // environment (which would race every other test in the binary).
        let base = PrefillConfig::default();
        assert_eq!(base.mode, PrefillMode::Sweep);
        assert_eq!(base.chunk, DEFAULT_PREFILL_CHUNK);
        assert_eq!(
            base.sweep_config(),
            SweepConfig {
                experts_per_window: base.experts_per_window,
                windows_in_flight: base.windows_in_flight,
            }
        );
        assert!(base.validate().is_ok());
        assert!(PrefillConfig { chunk: 0, ..base }.validate().is_err());
    }

    // ---- the phase split ------------------------------------------------
    //
    // Nothing here asserts a *duration*. This machine runs the model under a
    // cgroup while these tests run, so any "attention took at least X" would
    // flake; what is asserted is the arithmetic — that the phases are disjoint
    // spans of the total, that a run starts from zero, and that a reset drops
    // them. A double-charged phase pushes `accounted` past `total` and every
    // one of these catches it.

    /// [`PrefillTiming::other`] closes the sum by construction, and
    /// [`PrefillTiming::accounted`] is exactly the six phases. Pure
    /// arithmetic: no model, no clock, nothing to flake.
    #[test]
    fn the_unaccounted_remainder_closes_the_sum() {
        let ms = Duration::from_millis;
        let timing = PrefillTiming {
            mode: Some(PrefillMode::Sweep),
            tokens: 512,
            total: ms(1000),
            attention: ms(400),
            projections: ms(30),
            router: ms(5),
            expert_compute: ms(450),
            expert_io: ms(90),
            elementwise: ms(20),
        };
        assert_eq!(timing.accounted(), ms(995));
        assert_eq!(timing.other(), ms(5));
        assert_eq!(
            timing.accounted() + timing.other(),
            timing.total,
            "the phases and the remainder must be the whole run"
        );
        assert!(timing.ran());

        // A total shorter than its phases would be an instrumentation bug, not
        // a panic: `other` saturates.
        let broken = PrefillTiming {
            total: ms(1),
            ..timing
        };
        assert_eq!(broken.other(), Duration::ZERO);

        // The default has run nothing and claims nothing.
        let fresh = PrefillTiming::default();
        assert!(!fresh.ran());
        assert_eq!(fresh.accounted(), Duration::ZERO);
        assert_eq!(fresh.other(), Duration::ZERO);
        assert_eq!(fresh.phases().len(), 7);
    }

    /// Both paths report, and both report phases that fit inside their own
    /// total. This is what makes the sweep and the token-major loop
    /// comparable phase by phase, which is the whole point of instrumenting
    /// the A/B path too.
    #[test]
    fn both_prefill_paths_report_phases_inside_their_total() {
        let (_fx, model) = load_fixture("prefill-timing-split");
        let ids = [1u32, 2, 3, 4, 5, 6];

        for (want_mode, config) in [
            (PrefillMode::Sweep, sweep_config(4)),
            (PrefillMode::TokenMajor, token_major_config()),
        ] {
            let mut st = state_with(&model, 32, config);
            assert!(
                !st.prefill_timing().ran(),
                "{want_mode:?}: a fresh state has no prefill to report"
            );
            prefill_prompt(&model, &mut st, &ids, None).unwrap();

            let timing = st.prefill_timing();
            assert_eq!(timing.mode, Some(want_mode));
            assert_eq!(timing.tokens, ids.len() as u64);
            assert!(timing.ran());
            assert!(
                timing.accounted() <= timing.total,
                "{want_mode:?}: phases {:?} exceed the total {:?} — a region is \
                 charged twice",
                timing.accounted(),
                timing.total
            );
            assert_eq!(
                timing.accounted() + timing.other(),
                timing.total,
                "{want_mode:?}: the split must account for the whole run"
            );
            assert!(
                timing.total > Duration::ZERO,
                "{want_mode:?}: a prefill that ran took some time"
            );
        }
    }

    /// Every prefill starts from zero. Run a long prompt, then a one-token
    /// one: if the phases accumulated across runs, the second run's phases
    /// would carry the first run's work and overflow its much smaller total.
    #[test]
    fn every_prefill_rearms_the_timing() {
        let (_fx, model) = load_fixture("prefill-timing-rearm");
        let long: Vec<u32> = (0..12u32).map(|i| (i * 5 + 1) % 32).collect();

        let mut st = state_with(&model, 64, sweep_config(4));
        prefill_prompt(&model, &mut st, &long, None).unwrap();
        assert_eq!(st.prefill_timing().tokens, long.len() as u64);

        // A fresh sequence on the same state, on the other path.
        st.reset();
        st.set_prefill_config(token_major_config()).unwrap();
        prefill_prompt(&model, &mut st, &long[..1], None).unwrap();

        let timing = st.prefill_timing();
        assert_eq!(timing.tokens, 1, "the token count is per run, not summed");
        assert_eq!(
            timing.mode,
            Some(PrefillMode::TokenMajor),
            "the mode is the run's, not the state's history"
        );
        assert!(
            timing.accounted() <= timing.total,
            "phases {:?} exceed this run's total {:?}: the previous run leaked in",
            timing.accounted(),
            timing.total
        );
    }

    /// [`ForwardState::reset`] drops the timing, unlike the streaming counters
    /// beside it. A per-phase split left over from a sequence that has been
    /// thrown away would be read as belonging to the one that replaced it.
    #[test]
    fn a_reset_drops_the_prefill_timing() {
        let (_fx, model) = load_fixture("prefill-timing-reset");
        let mut st = state_with(&model, 32, sweep_config(4));
        prefill_prompt(&model, &mut st, &[1, 2, 3, 4, 5], None).unwrap();
        assert!(st.prefill_timing().ran());

        st.reset();
        assert_eq!(
            st.prefill_timing(),
            PrefillTiming::default(),
            "a reset state reports no prefill at all"
        );
        assert!(!st.prefill_timing().ran());
    }

    /// Decode charges nothing. `forward_token` carries the same
    /// instrumentation the token-major prefill does, and the only thing
    /// keeping generation out of a prompt's numbers is that a prefill has to
    /// arm the timing first.
    #[test]
    fn decode_does_not_charge_the_prefill_timing() {
        let (_fx, model) = load_fixture("prefill-timing-decode");
        let ids = [1u32, 2, 3, 4, 5];
        let mut st = state_with(&model, 32, sweep_config(4));
        prefill_prompt(&model, &mut st, &ids, None).unwrap();
        let after_prefill = st.prefill_timing();

        for step in 0..3usize {
            let position = ids.len() + step;
            crate::model::forward_token(&model, &mut st, 7, position, true).unwrap();
        }
        assert_eq!(
            st.prefill_timing(),
            after_prefill,
            "three decode tokens moved a prefill counter"
        );
    }

    /// The GEMV sub-split rides the same arming rule one level down: the
    /// token-major prefill runs the *same* pooled fan-outs `forward_token`
    /// does, and charges none of them.
    ///
    /// This is the disarmed half of the instrument, asserted where it actually
    /// matters: not that a `None` clock returns early — a unit test in
    /// `forward` pins that — but that the path which shares the instrumented
    /// function with decode leaves every bucket, and every scatter count, at
    /// zero. A prompt's fan-outs folded into a decode's `own`/`wait` would put
    /// hundreds of prefill GEMVs under a heading that says decode.
    #[test]
    fn a_token_major_prefill_charges_no_decode_gemvs() {
        let (_fx, model) = load_fixture("prefill-gemv-subsplit");
        let ids = [1u32, 2, 3, 4, 5];
        let mut st = state_with(&model, 32, token_major_config());

        prefill_prompt(&model, &mut st, &ids, None).unwrap();
        let after_prefill = st.decode_gemv_split();
        for &(label, own, wait, scatters) in &after_prefill {
            assert_eq!(
                (own, wait, scatters),
                (Duration::ZERO, Duration::ZERO, 0),
                "the prefill charged {label}: {after_prefill:?}"
            );
        }

        // The same state, now decoding: the instrument is armed and every
        // bucket fills.
        for step in 0..2usize {
            let position = ids.len() + step;
            crate::model::forward_token(&model, &mut st, 7, position, true).unwrap();
        }
        for &(label, own, _, scatters) in &st.decode_gemv_split() {
            assert!(scatters > 0, "{label} charged no fan-out after decoding");
            assert!(own > Duration::ZERO, "{label} charged no own time");
        }
    }
}